Token导航 LogoToken导航

Agent Skill · 开发

how-i-made-your-machine(我是如何制造你的机器的)

how-i-made-your-machine 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

how-i-made-your-machine 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 19,628。

总安装 264周安装 11GitHub Stars 公开资料未说明下载 88核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:how-i-made-your-machine(我是如何制造你的机器的)
来源仓库:https://github.com/kstonekuan/how-i-made-your-machine
仓库路径:skills/how-i-made-your-machine
安装命令:
npx skills add https://github.com/kstonekuan/how-i-made-your-machine --skill how-i-made-your-machine
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/kstonekuan/how-i-made-your-machine --skill how-i-made-your-machine

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。适合围绕仓库状态、代码变更或协作事项进行整理和分析。

安装命令:npx skills add https://github.com/kstonekuan/how-i-made-your-machine --skill how-i-made-your-machine。适用于 Codex、Claude、Cursor、Gemini CLI,通过 GitHub 安装。

建议确认权限范围和维护状态,注意是否触发联网或文件读写操作。

来源仓库内路径:skills/how-i-made-your-machine

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/kstonekuan/how-i-made-your-machine --skill how…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

how-i-made-your-machine 怎么安装?

在终端执行 npx skills add https://github.com/kstonekuan/how-i-made-your-machine --skill how-i-made-yo…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

how-i-made-your-machine 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

how-i-made-your-machine 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

how-i-made-your-machine 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

how-i-made-your-machine 用的人多吗?

公开数据是累计安装 264 次,近一周安装 11 次,下载 88 次。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

how-i-made-your-machine 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
how-i-made-your-machine

我是如何制造你的机器的 · 本页

264—需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

How I Made Your Machine

*A guide to writing software for humans and agents: the story of how I made your machine.*

Agent Usage

  1. Read this guide before implementing, refactoring, or reviewing code.
  2. Treat these rules as defaults unless the user requests a different tradeoff.
  3. Model finite values and mutually exclusive states with explicit variants/enums/unions.
  4. Prefer domain-specific types and function signatures over generic primitives.
  5. Preserve behavior-first testing: test business outcomes, not framework internals or third-party behavior.
  6. Call out justified exceptions explicitly when constraints force weaker typing or non-ideal structure.
  7. Keep unrelated code unchanged; apply the guide to the task scope instead of broad rewrites.

Agent Workflow

  1. Identify which sections below apply to the current task.
  2. Implement or refactor using the relevant patterns.
  3. Review the result against the Core Principles and Type Design Signals.
  4. Explain key changes in terms of maintainability, type safety, and behavior correctness.

Purpose

This guide lays out how we should write code for maintainability, type safety, and behavior-first testing across projects. It sets strong defaults, with room for justified exceptions when the tradeoff is clear.

Core Principles

  • Make invalid states hard to represent.
  • Model domain concepts explicitly instead of using ad-hoc primitives.
  • Use the type system and compiler as first-line quality gates.
  • Optimize for readable intent over clever implementation.
  • Parse external input into domain types at system boundaries; trust refined types downstream.
  • Test business behavior rather than framework or library internals.

Type Safety and Relying on the Compiler

Using a type-safe language is not enough on its own. We have to be intentional about how we model data and behavior so the compiler and static analysis can do real work for us. It is easy to write code that technically type-checks while still side-stepping most of those guarantees.

Here are some patterns that are useful to follow:

  • Prefer domain types over raw strings and loosely typed containers.
  • Use unions/enums/typed variants when valid values are finite.
  • Favor exhaustive pattern matching where possible.
  • Represent unknown external values explicitly (Unknown*) instead of falling back silently.
  • Avoid weakening types (any, broad casts, untyped flows) unless unavoidable.
  • Prefer functions that return refined types over void-returning validation that discards what it learns.
  • Avoid duplicating the same fact across multiple fields or structures; keep one source of truth.

Type Design Signals

  • If the value set is finite, use a union/enum instead of string.
  • If states are mutually exclusive, use one state union/enum instead of multiple booleans.
  • If function inputs represent domain concepts, use those domain types directly.
  • If a function validates a condition and returns void, it is probably discarding information — return a refined type instead.
  • If the same value is stored in two places, one will eventually be wrong — derive it or pick a single owner.

Example 1: Finite Value Set as Variants

Under-modeled:
  status: string

Better modeled:
  Status = "draft" | "published" | "archived"
  status: Status
// Bad: unconstrained string allows invalid values.
const underModeledStatus: string = "draff";

// Good: finite union prevents invalid states.
type Status = "draft" | "published" | "archived";
const modeledStatus: Status = "draft";
// Bad: free-form string can carry invalid values.
let under_modeled_status = "draff";

// Good: enum constrains the value set.
enum Status {
    Draft,
    Published,
    Archived,
}

let modeled_status = Status::Draft;
let _ = (under_modeled_status, modeled_status);
# Bad: unconstrained string allows invalid values.
under_modeled_status: str = "draff"

# Good: StrEnum constrains valid values.
from enum import StrEnum

class Status(StrEnum):
    DRAFT = "draft"
    PUBLISHED = "published"
    ARCHIVED = "archived"

modeled_status: Status = Status.DRAFT

Example 2: Boolean Combinations to State Variants

Under-modeled:
  is_draft: boolean
  is_published: boolean
  is_archived: boolean

Better modeled:
  ContentState = "draft" | "published" | "archived"
  content_state: ContentState
// Bad: boolean combinations allow impossible states.
const isDraft = true;
const isPublished = true;
const isArchived = false;

// Good: one variant encodes one valid state.
type ContentState = "draft" | "published" | "archived";
const contentState: ContentState = "published";
void [isDraft, isPublished, isArchived];
// Bad: booleans can contradict each other.
struct UnderModeledContentState {
    is_draft: bool,
    is_published: bool,
    is_archived: bool,
}

// Good: enum enforces one state at a time.
enum ContentState {
    Draft,
    Published,
    Archived,
}

let under_modeled_content_state = UnderModeledContentState {
    is_draft: true,
    is_published: true,
    is_archived: false,
};
let modeled_content_state = ContentState::Published;
let _ = (
    under_modeled_content_state.is_draft,
    under_modeled_content_state.is_published,
    under_modeled_content_state.is_archived,
    modeled_content_state,
);
# Bad: booleans can represent impossible combinations.
is_draft = True
is_published = True
is_archived = False

# Good: Literal constrains to one valid state.
from typing import Literal

ContentState = Literal["draft", "published", "archived"]

content_state: ContentState = "published"
_ = (is_draft, is_published, is_archived, content_state)

Example 3: Functions Consume Domain Types

Under-modeled:
  schedule_message(channel: string, is_immediate: boolean, is_scheduled: boolean)

Better modeled:
  Channel = "email" | "sms" | "push"
  DeliveryMode = "immediate" | "scheduled"
  schedule_message(channel: Channel, delivery_mode: DeliveryMode)
// Bad: primitives hide domain intent and allow contradictions.
function scheduleMessageUnderModeled(
  channel: string,
  isImmediate: boolean,
  isScheduled: boolean,
): void {
  void [channel, isImmediate, isScheduled];
}

// Good: explicit domain types make valid states clear.
type Channel = "email" | "sms" | "push";
type DeliveryMode = "immediate" | "scheduled";

function scheduleMessage(channel: Channel, deliveryMode: DeliveryMode): void {
  void [channel, deliveryMode];
}
// Bad: primitives allow invalid channels and conflicting mode flags.
fn schedule_message_under_modeled(channel: &str, is_immediate: bool, is_scheduled: bool) {
    let _ = (channel, is_immediate, is_scheduled);
}

// Good: domain enums constrain function inputs.
enum Channel {
    Email,
    Sms,
    Push,
}

enum DeliveryMode {
    Immediate,
    Scheduled,
}

fn schedule_message(channel: Channel, delivery_mode: DeliveryMode) {
    let _ = (channel, delivery_mode);
}
# Bad: primitive inputs accept invalid values and contradictory flags.
def schedule_message_under_modeled(
    channel: str,
    is_immediate: bool,
    is_scheduled: bool,
) -> None:
    _ = (channel, is_immediate, is_scheduled)

# Good: domain literals constrain allowed values.
from typing import Literal

Channel = Literal["email", "sms", "push"]
DeliveryMode = Literal["immediate", "scheduled"]

def schedule_message(channel: Channel, delivery_mode: DeliveryMode) -> None:
    _ = (channel, delivery_mode)

Parse at Boundaries

Validation checks a condition and throws or returns nothing. Parsing checks the same condition but returns a refined type that carries the proof forward. When we validate and discard what we learned, every downstream function has to re-check or trust blindly. Alexis King's Parse, Don't Validate describes this well and clearly. The full article is included as a reference.

Parse external input at system boundaries — user input, API responses, config files, webhook payloads — then pass the refined type through the rest of the system. Avoid scattering validation logic across business code (sometimes called "shotgun parsing"), where invalid input may be partially processed before being rejected. Example 12 in Exceptions shows a real-world instance of this pattern for partner webhooks.

Example 4: Return a Refined Type Instead of Void

Validation (discards knowledge):
  validate_email(input: string) -> void     # throws on failure
  send_welcome(email: string)               # must trust caller or re-check

Parsing (preserves knowledge):
  parse_email(input: string) -> Email       # returns proof or error
  send_welcome(email: Email)                # type guarantees validity
// Bad: validates but returns void — caller still holds a raw string.
function validateEmail(input: string): void {
  if (!input.includes("@")) {
    throw new Error("invalid email");
  }
}

function sendWelcomeUnderModeled(email: string): void {
  validateEmail(email);
  // email is still string — nothing prevents passing an unchecked value.
  void email;
}

// Good: parse once at the boundary, carry proof in the type.
type Email = string & { readonly __brand: "Email" };

function parseEmail(input: string): Email {
  if (!input.includes("@")) {
    throw new Error("invalid email");
  }
  return input as Email;
}

function sendWelcome(email: Email): void {
  // No re-validation needed — the type proves it was parsed.
  void email;
}
// Bad: validates but returns nothing — caller still holds a raw &str.
fn validate_email(input: &str) {
    if !input.contains('@') {
        panic!("invalid email");
    }
}

fn send_welcome_under_modeled(email: &str) {
    validate_email(email);
    // email is still &str — nothing prevents passing an unchecked value.
    let _ = email;
}

// Good: parse once at the boundary, carry proof in the type.
struct Email(String);

impl Email {
    fn parse(input: &str) -> Result<Self, String> {
        if !input.contains('@') {
            return Err(format!("invalid email: {input}"));
        }
        Ok(Self(input.to_owned()))
    }
}

fn send_welcome(email: &Email) {
    // No re-validation needed — the type proves it was parsed.
    let _ = email;
}

let _ = (send_welcome_under_modeled as fn(&str), send_welcome as fn(&Email));
# Bad: validates but returns None — caller still holds a raw str.
def validate_email(input: str) -> None:
    if "@" not in input:
        raise ValueError("invalid email")

def send_welcome_under_modeled(email: str) -> None:
    validate_email(email)
    # email is still str — nothing prevents passing an unchecked value.
    _ = email

# Good: parse once at the boundary, carry proof in the type.
from typing import NewType

Email = NewType("Email", str)

def parse_email(input: str) -> Email:
    if "@" not in input:
        raise ValueError("invalid email")
    return Email(input)

def send_welcome(email: Email) -> None:
    # No re-validation needed — the type proves it was parsed.
    _ = email

Example 5: Smart Constructors for Non-Structural Invariants

When an invariant cannot be captured by a union or enum — like a numeric range, a non-empty list, or a formatted string — use an opaque type with a constructing function that enforces the constraint. Downstream code receives the refined type and never needs to re-validate.

Under-modeled:
  percentage: number               # caller must remember 0-100

Better modeled:
  Percentage = opaque(number)      # only created through constructor
  make_percentage(n: number) -> Percentage | error
// Bad: raw number allows out-of-range values.
function applyDiscountUnderModeled(percentage: number): void {
  void percentage; // nothing prevents 150 or -3
}

// Good: branded type enforces range at construction.
type Percentage = number & { readonly __brand: "Percentage" };

function makePercentage(value: number): Percentage {
  if (value < 0 || value > 100) {
    throw new RangeError(`percentage out of range: ${value}`);
  }
  return value as Percentage;
}

function applyDiscount(percentage: Percentage): void {
  // Safe to use directly — construction guarantees 0-100.
  void percentage;
}
// Bad: raw f64 allows out-of-range values.
fn apply_discount_under_modeled(percentage: f64) {
    let _ = percentage; // nothing prevents 150.0 or -3.0
}

// Good: newtype with a constructor enforces the range.
struct Percentage(f64);

impl Percentage {
    fn new(value: f64) -> Result<Self, String> {
        if !(0.0..=100.0).contains(&value) {
            return Err(format!("percentage out of range: {value}"));
        }
        Ok(Self(value))
    }

    fn value(&self) -> f64 {
        self.0
    }
}

fn apply_discount(percentage: &Percentage) {
    // Safe to use directly — construction guarantees 0-100.
    let _ = percentage.value();
}

let _ = apply_discount_under_modeled;
# Bad: raw float allows out-of-range values.
def apply_discount_under_modeled(percentage: float) -> None:
    _ = percentage  # nothing prevents 150.0 or -3.0

# Good: NewType + constructor enforces the range.
from typing import NewType

Percentage = NewType("Percentage", float)

def make_percentage(value: float) -> Percentage:
    if not (0 <= value <= 100):
        raise ValueError(f"percentage out of range: {value}")
    return Percentage(value)

def apply_discount(percentage: Percentage) -> None:
    # Safe to use directly — construction guarantees 0-100.
    _ = percentage

Self-Documenting Code

Self-documenting code is usually better than writing comments everywhere. Comments go stale quickly, while clear naming and structure have to evolve with the program.

  • Prefer descriptive, domain-aligned names even when verbose.
  • Keep function and type names intention-revealing.
  • Add comments only for non-obvious decisions, invariants, or tradeoffs.
  • Avoid comments that restate what code already makes obvious.

Example 6: Document the Why, Not the Obvious What

Low-value comment:
  // Increment retry count
  retry_count = retry_count + 1

High-value comment:
  // Billing provider closes refunds at next-day midnight, so keep a one-day grace period.
  refund_grace_period_days = 1
  is_refund_eligible = days_since_purchase <= refund_window_days + refund_grace_period_days
// Bad: restates obvious code behavior without context.
function incrementRetryCount(retryCount: number): number {
  // Increment retry count.
  return retryCount + 1;
}

// Good: documents a non-obvious business constraint.
function isRefundEligible(
  daysSincePurchase: number,
  refundWindowDays: number,
): boolean {
  // Billing provider closes refunds at next-day midnight, so we keep a one-day grace period.
  const refundGracePeriodInDays = 1;
  return daysSincePurchase <= refundWindowDays + refundGracePeriodInDays;
}
// Bad: restates obvious behavior.
fn increment_retry_count(retry_count: u32) -> u32 {
    // Increment retry count.
    retry_count + 1
}

// Good: documents a non-obvious business constraint.
fn is_refund_eligible(days_since_purchase: u32, refund_window_days: u32) -> bool {
    // Billing provider closes refunds at next-day midnight, so we keep a one-day grace period.
    let refund_grace_period_in_days = 1;
    days_since_purchase <= refund_window_days + refund_grace_period_in_days
}

let _ = increment_retry_count(0);
# Bad: restates obvious behavior.
def increment_retry_count(retry_count: int) -> int:
    # Increment retry count.
    return retry_count + 1

# Good: documents a non-obvious business constraint.
def is_refund_eligible(days_since_purchase: int, refund_window_days: int) -> bool:
    # Billing provider closes refunds at next-day midnight, so we keep a one-day grace period.
    refund_grace_period_in_days = 1
    return days_since_purchase <= refund_window_days + refund_grace_period_in_days

_ = increment_retry_count(0)

Testing Business Logic First

Tests are important for verifying behavior and preventing regression at both unit and integration levels. But we should avoid writing tests for the sake of writing tests: they add maintenance cost and create noise when they assert outcomes that do not matter to business behavior.

  • Test business outcomes and domain behavior first.
  • Prioritize tests for state transitions, input-to-output rules, defaults, and fallback behavior.
  • Do not test third-party/library internals.
  • Avoid mocks by default.
  • Use mocks only for unstable boundaries (network, filesystem, time, OS/process boundaries).
  • Assert externally meaningful behavior, not private implementation details.

Example 7: Test State Transitions and Outcomes

Brittle:
  assert transition_helper_called_once()

Behavior-focused:
  result = transition_order_state("draft", "publish")
  assert result == "published"
import { describe, expect, it } from "vitest";

describe("transitionOrderStateUnderTest", () => {
  it("bad: asserts an implementation detail", () => {
    const transitionHelperCallCount = 1;
    expect(transitionHelperCallCount).toBe(1);
  });
});

describe("transitionOrderState", () => {
  it("good: asserts observable state transition", () => {
    const nextState = transitionOrderState("draft", "publish");
    expect(nextState).toBe("published");
  });
});
#[test]
fn bad_asserts_implementation_detail_only() {
    let transition_helper_call_count = 1;
    assert_eq!(transition_helper_call_count, 1);
}

#[test]
fn good_transitions_draft_to_published_when_publish_is_requested() {
    let next_state = transition_order_state("draft", "publish");
    assert_eq!(next_state, "published");
}
def test_bad_asserts_implementation_detail_only() -> None:
    transition_helper_call_count = 1
    assert transition_helper_call_count == 1

def test_good_transition_order_state_moves_draft_to_published() -> None:
    next_state = transition_order_state("draft", "publish")
    assert next_state == "published"

Example 8: Mock Only Unstable Boundaries

Preferred:
  fake_clock = FixedClock("2025-01-01T00:00:00Z")
  assert discount_is_active(fake_clock)

Avoid:
  assert internal_helper_called("calculate_discount_window")
import { expect, it, vi } from "vitest";

it("bad: mocks an internal helper and asserts internals", () => {
  const calculateDiscountWindow = vi.fn().mockReturnValue(true);
  calculateDiscountWindow();
  expect(calculateDiscountWindow).toHaveBeenCalledTimes(1);
});

it("good: mocks only unstable network boundary and asserts behavior", async () => {
  const fetchExchangeRate = vi.fn().mockRejectedValue(new Error("timeout"));
  const gateway = createCurrencyGateway({ fetchExchangeRate });

  const rate = await gateway.getRateOrFallback("USD", "EUR");

  expect(rate).toBe(0.92);
});
#[test]
fn bad_asserts_internal_helper_behavior() {
    let internal_helper_call_count = 1;
    assert_eq!(internal_helper_call_count, 1);
}

#[test]
fn good_uses_cached_rate_when_live_lookup_fails() {
    let gateway = CurrencyGateway::new(FailingRateClient, CachedRateStore::with_rate(0.92));
    let rate = gateway.get_rate_or_fallback("USD", "EUR");
    assert_eq!(rate, 0.92);
}
def test_bad_asserts_internal_helper_behavior() -> None:
    internal_helper_call_count = 1
    assert internal_helper_call_count == 1

def test_good_uses_cached_rate_when_live_lookup_fails() -> None:
    gateway = CurrencyGateway(
        rate_client=FailingRateClient(),
        cache_store=CachedRateStore(rate=0.92),
    )

    rate = gateway.get_rate_or_fallback("USD", "EUR")

    assert rate == 0.92

Choosing Dependencies

The code we import carries the same maintenance cost as code we write. A dependency is a commitment to its API surface, its release cadence, its transitive dependencies, and its type design choices. Every dependency is also an attack surface — supply chain attacks target unmaintained, obscure, or compromised packages, so choosing well is a security concern, not just a quality one.

  • Prefer popular, actively maintained libraries backed by organizations or well-known open-source communities. Recent contributions, high download counts, and security audit history all signal that vulnerabilities are more likely to be caught early.
  • If two libraries solve the same problem and equally safe to depend on, prefer the one whose API returns well-typed domain objects over one that returns loosely typed containers (any, raw dicts, untyped JSON).
  • Value libraries whose internals reflect stronger type design. A Python library with a Rust core benefits from Rust's compiler guarantees at the boundary while remaining ergonomic in Python.
  • If the functionality is a well-known algorithm or data structure that fits in a few lines, re-implement it. The dependency's maintenance cost will exceed the code's, and every dependency you avoid is one fewer supply chain risk.
  • If you would need to wrap the library in adapter types to make it fit your domain model, weigh whether the library is saving you work or creating it.

Example 10: Prefer Libraries That Align With Your Type Design

Poor alignment:
  response = http_get(url)             # returns untyped dict
  name = response["user"]["name"]      # runtime key error if shape changes

Good alignment:
  response = http_get(url) -> User     # returns typed domain object
  name = response.name                 # compiler catches field typos
// Bad: library returns `any` — caller must cast or assert at every access.
async function getUserNameUnderModeled(userId: string): Promise<string> {
  // biome-ignore lint/suspicious/noExplicitAny: demonstrating a bad library API
  const response: any = await untypedHttpClient.get(`/users/${userId}`);
  return response.data.name;
}

// Good: library returns typed response — compiler catches field errors.
import { z } from "zod";

const UserSchema = z.object({
  name: z.string(),
  email: z.string(),
});

type User = z.infer<typeof UserSchema>;

async function getUserName(userId: string): Promise<string> {
  const response = await typedHttpClient.get(`/users/${userId}`, UserSchema);
  return response.name;
}
use serde::Deserialize;
use serde_json::Value;

// Bad: library returns serde_json::Value — caller must chain fallible accessors.
fn get_user_name_under_modeled(response: &Value) -> Option<&str> {
    response.get("user")?.get("name")?.as_str()
}

// Good: library deserializes into a typed struct — field access is compile-checked.
#[derive(Deserialize)]
struct User {
    name: String,
    email: String,
}

fn get_user_name(user: &User) -> &str {
    &user.name
}

let _ = get_user_name_under_modeled;
from typing import Any

# Bad: library returns untyped dict — field access is unchecked.
def get_user_name_under_modeled(response: dict[str, Any]) -> str:
    return response["user"]["name"]  # KeyError if shape changes

# Good: library returns typed model — type checker catches field errors.
from dataclasses import dataclass

@dataclass
class User:
    name: str
    email: str

def get_user_name(user: User) -> str:
    return user.name

Example 11: Re-implement When the Dependency Outweighs the Logic

Unnecessary dependency:
  import clamp from "math-utils-lib"
  result = clamp(value, 0, 100)

Better as local code:
  clamp(value, min, max) = max(min, min(max, value))
  result = clamp(value, 0, 100)
// Bad: importing a package for a one-liner adds supply-chain surface for no benefit.
// import { clamp } from "math-utils-lib";
// const clampedFromLib = clamp(value, 0, 100);

// Good: trivial, well-understood logic is cheaper to own than to import.
function clamp(value: number, min: number, max: number): number {
  return Math.max(min, Math.min(max, value));
}

const clamped = clamp(150, 0, 100);
void clamped;
// Bad: pulling in an external crate for something the standard library already provides.
// use num::clamp;
// let clamped_from_crate = clamp(150.0, 0.0, 100.0);

// Good: the standard library already has f64::clamp — no dependency needed.
let clamped = 150.0_f64.clamp(0.0, 100.0);
let _ = clamped;
# Bad: importing a utility library for a one-liner adds supply-chain surface for no benefit.
# from math_utils_lib import clamp
# clamped_from_lib = clamp(value, 0, 100)

# Good: trivial, well-understood logic is cheaper to own than to import.
def clamp(value: float, lo: float, hi: float) -> float:
    return max(lo, min(hi, value))

clamped = clamp(150, 0, 100)

For guidance on choosing linters and type checkers, see Choosing Linters and Type Checkers.

Exceptions

We can make exceptions when strict modeling creates disproportionate complexity, external contracts require looser typing, or performance/interoperability constraints apply.

When we take an exception, we should document:

  • Which rule is being bent
  • Why
  • Which safeguards are in place (validation, logging, tests)

Example 12: External Contract Requires Looser Typing

Rule being bent:
  "Finite value set -> union/enum instead of string"

Why:
  Partner webhook sends undocumented status values.

Safeguards:
  validate known values
  map unknown values to UnknownPartnerStatus
  log raw unknown values
  test known and unknown inputs
// Bad: assumes external input already matches strict known values.
type UnderModeledPartnerStatus = "accepted" | "rejected";

function parsePartnerStatus(rawPartnerStatus: UnderModeledPartnerStatus): UnderModeledPartnerStatus {
  return rawPartnerStatus;
}

// Good: accept string input, validate known values, and map unknown values explicitly.
type KnownPartnerStatus = "accepted" | "rejected";
type PartnerStatus = KnownPartnerStatus | "unknown_partner_status";

function mapPartnerStatus(rawPartnerStatus: string): PartnerStatus {
  if (rawPartnerStatus === "accepted" || rawPartnerStatus === "rejected") {
    return rawPartnerStatus;
  }

  console.warn("unknown partner status", { rawPartnerStatus });
  return "unknown_partner_status";
}
// Bad: panics on unexpected partner status values.
enum UnderModeledPartnerStatus {
    Accepted,
    Rejected,
}

fn parse_partner_status(raw_partner_status: &str) -> UnderModeledPartnerStatus {
    match raw_partner_status {
        "accepted" => UnderModeledPartnerStatus::Accepted,
        "rejected" => UnderModeledPartnerStatus::Rejected,
        _ => panic!("unsupported partner status: {raw_partner_status}"),
    }
}

// Good: capture unknown values explicitly and continue safely.
enum PartnerStatus {
    Accepted,
    Rejected,
    UnknownPartnerStatus,
}

fn map_partner_status(raw_partner_status: &str) -> PartnerStatus {
    match raw_partner_status {
        "accepted" => PartnerStatus::Accepted,
        "rejected" => PartnerStatus::Rejected,
        _ => {
            eprintln!("unknown partner status: {raw_partner_status}");
            PartnerStatus::UnknownPartnerStatus
        }
    }
}

let _ = parse_partner_status("accepted");
from typing import Literal

# Bad: assumes the partner only ever sends known values.
UnderModeledPartnerStatus = Literal["accepted", "rejected"]

def parse_partner_status(raw_partner_status: UnderModeledPartnerStatus) -> UnderModeledPartnerStatus:
    return raw_partner_status

# Good: accept raw string input and map unknown values explicitly.
PartnerStatus = Literal["accepted", "rejected", "unknown_partner_status"]

def map_partner_status(raw_partner_status: str) -> PartnerStatus:
    if raw_partner_status in {"accepted", "rejected"}:
        return raw_partner_status

    print(f"unknown partner status: {raw_partner_status}")
    return "unknown_partner_status"

平台分布

Codex

35.88%
按下载量换算32

Claude

27.8%
按下载量换算24

Cursor

18.69%
按下载量换算16

Gemini CLI

9.61%
按下载量换算8

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills