api-ergonomics-and-contract-governor
Skill4 starsChanged 31 days agoMITView on GitHub
Enforces Microsoft TypeScript compiler-team ergonomic rigor and Stripe world-class API design standards for SDKs, CLIs, and internal modules. Use when designing public SDKs, library interfaces, CLI commands, or internal module boundaries; enforcing pit-of-success defaults, discriminated unions, branded nominal types, progressive disclosure, and RFC 9457 problem details — even if they don't explicitly say "api governor". Do NOT use for trivial internal variable renames, local loop optimizations, or simple non-contract utility functions.
In this repository47 other files it gives its agents.
- AGENTS.mdAGENTS.md
- anti-slop-engineeringSkill
- anti-slop-engineeringSkill
- apple-craft-and-frame-budgetSkill
- apple-craft-and-interaction-physicsSkill
- asset-provenance-guardSkill
- backprop-guardSkill
- chaos-and-degradation-choreographerSkill
- chromatic-drift-guardSkill
- cognitive-load-and-attention-governorSkill
- comment-budget-guardSkill
- context-window-and-token-economics-architectSkill
- cryptographic-agility-and-secret-lifecycle-gateSkill
- decision-guardSkill
- demock-guardSkill
- design-system-drift-guardSkill
- deterministic-simulation-and-property-testingSkill
- distributed-consensus-and-concurrency-gateSkill
- finops-and-unit-economics-governorSkill
- future-scale-gateSkill
- grumpy-senior-staff-engineerSkill
- honeypot-trap-guardSkill
- house-tell-guardSkill
- install-anti-slopSkill
- llm-eval-and-prompt-injection-fortressSkill
- mandela-guardSkill
- mechanical-sympathy-and-perf-gateSkill
- mechanical-sympathy-profilerSkill
- motion-runtime-guardSkill
- observability-and-slo-architectSkill
- observability-and-slo-gateSkill
- paranoid-principal-architectSkill
- pr-boundary-guardSkill
- privacy-and-data-lineage-gateSkill
- re0-handoff-guardSkill
- reduction-guardSkill
- repo-memory-and-invariant-stewardSkill
- root-fix-gateSkill
- safe-evolution-and-rollout-choreographerSkill
- scientific-fault-isolationSkill
- styleseed-guardSkill
- supply-chain-and-sbom-sentinelSkill
- tagore-guardSkill
- type-level-and-ast-slop-gateSkill
- ui-and-copy-disciplineSkill
- verification-oracle-architectSkill
- zero-downtime-migration-gateSkill
The file
We split this skill into the rules it gives an agent
8 rules. About 0 are common, 4 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 50
Nominal branding for all domain identifiers: Never pass raw unbranded string or number types for entity IDs across public module boundaries.
- Very specific: line 52
Exhaustive pattern matching enforcement: All consumers handling discriminated unions must enforce compile-time exhaustiveness via a …
- Very specific: line 54
Built-in timeout and cancellation discipline: Every network-bound method must accept an optional AbortSignal, defaulting to a safe built-in …
- Very specific: line 58
Clean
.d.tshover readability: Do not author type gymnastics that evaluate to massive, unreadable union expansions in IDE tooltips. - Distinctive: line 76
Before emitting or approving an SDK, CLI, or module boundary, evaluate against this matrix:
- Distinctive: line 79
The Failure Blast Radius: If a developer makes a mistake, does it fail at compile time?
- Distinctive: line 82
The Error Transparency: When a network or domain call fails, can the consumer's automated remediation handler parse the exact machine code …
- Distinctive: line 106
When a durable architectural record is warranted, save a JSON assessment following the API Contract Record Contract and audit it with:
≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Skill: The API Ergonomics & Contract Governor (Microsoft TypeScript & Stripe DX)
Design APIs where the easiest way to use them is also the correct, safe, and performant way.
Why This Skill Is Needed & Target State
AI agents and hurried developers frequently produce clunky, brittle, and leaky interfaces: boolean traps (foo(true, false, true)), stringly-typed IDs (userId: string passed to orgId), exploding option bags requiring 10 mandatory parameters for simple operations, and ad-hoc string error throwing (throw new Error("failed")) lacking machine-actionable codes.
The target state is architectural contract governance: every SDK, CLI, and internal module exhibits Microsoft TypeScript compiler-team ergonomic rigor (zero any, branded nominal types, discriminated unions rendering illegal states unrepresentable, clean .d.ts hovers) and Stripe world-class developer experience (pit-of-success defaults, progressive disclosure from 1-line facades to advanced pipelines, and standardized RFC 9457 problem details).
Activation and Boundaries
| Situation | Behavior |
| Designing a new public SDK, client library, or internal service boundary | Enforce Pit-of-Success defaults, 3-tier progressive disclosure, and branded types |
| Defining domain entities, request options, or status state machines | Model using Discriminated Unions; eliminate boolean flags and impossible states |
| Authoring CLI tools, commands, or developer toolkits | Enforce zero-config default execution, hierarchical subcommand discovery, and RFC 9457 error output |
| Modeling API errors, failure payloads, or exception classes | Implement RFC 9457 Problem Details with machine codes, retryability hints, and remediation actions |
| Auditing existing libraries or reviewing API PRs | Run adversarial ergonomics checks (Boolean trap audit, stringly-typed ID audit, option explosion audit) |
| Local loop optimizations, private helper refactors, or formatting | Do not activate; use Anti-Slop Engineering BUILD/FIX gates |
The Four Absolute Pillars
- Pit of Success Defaults: Every function, client, and CLI command must succeed with maximum safety and optimal performance out of the box without requiring callers to specify configuration bags. Safe timeouts (10s default via
AbortSignal.timeout), automatic idempotent retries with exponential backoff and full jitter, TLS verification, and bounded pagination limits are pre-configured. Callers pass only what is unique to their intent. - Illegal States Unrepresentable (Compile-Time Impossibility): Eliminate boolean flags and loose primitive combinations that permit contradictory states (such as
{ status: "success", errorCode: "INVALID" }). Utilize Discriminated Unions with tag discriminators, Nominal Branded Types (CustomerId,InvoiceId) to prevent parameter transposition, and exact exhaustiveness checking (assertNever). - Progressive Disclosure: Structure APIs in three distinct cognitive tiers:
- Tier 1 (One-Liner): High-level, zero-friction entry-point solving the 80% use case in a single call.
- Tier 2 (Configured Options): Explicit, type-safe options bag overriding defaults for specific operational requirements.
- Tier 3 (Escape Hatch & Advanced Engine): Direct access to underlying protocol, raw request client, custom transport adapters, and streaming pipelines without leaky abstractions.
- RFC 9457 Problem Details: Standardize all programmatic and network errors on the IETF RFC 9457 (RFC 7807) specification. Every error exposes a stable URI
type, human-readabletitle, HTTP/CLIstatus, detaileddetail, contextualinstance, deterministic machinecode, parameter-specificinvalid_params, actionablesuggested_action, and booleanretryablemetadata.
Invariant Rules
- No boolean parameter traps. Functions taking two or more boolean arguments are prohibited. Replace boolean flags with named union literals or discriminated option records (e.g.
mode: "sync" | "async"instead ofisAsync: boolean). - Nominal branding for all domain identifiers. Never pass raw unbranded
stringornumbertypes for entity IDs across public module boundaries. Enforce branded types (e.g.type AccountId = string & { readonly __brand: unique symbol }) to prevent passing a user ID where an account ID is expected. - Discriminated unions for multi-state entities. State machines, lifecycle statuses, and polymorphic payloads must use a common discriminator key (
status,kind,type). Never combine optional fields across incompatible states. - Exhaustive pattern matching enforcement. All consumers handling discriminated unions must enforce compile-time exhaustiveness via a dedicated
assertNever(x: never): neverutility or compiler-checked switch statements. - Progressive disclosure in namespaces and classes. High-level client instances must not pollute root autocompletion with 150 internal transport methods. Group methods by domain resource (e.g.
client.customers.create()), leaving advanced transport customization to builder or client options. - Built-in timeout and cancellation discipline. Every network-bound method must accept an optional
AbortSignal, defaulting to a safe built-in timeout (e.g.AbortSignal.timeout(10_000)). Hanging network calls by default are considered critical bugs. - Safe-by-default retryability with idempotency. Network clients must automatically generate or accept deterministic idempotency keys for state-mutating requests, coupled with automated retries for transient errors (HTTP 408, 429, 502, 503, 504) using exponential backoff with full jitter.
- Cursor-based pagination with bounded page sizes. Collection-returning methods must default to cursor pagination (returning
has_moreandnext_cursor), with a safe default limit (e.g. 20) and a hard-coded maximum ceiling (e.g. 100). Never allow unbounded fetch-all operations on public APIs. - Standardized RFC 9457 error contracts. Custom error classes must inherit from a canonical
ProblemDetailsErrorcontaining standard fields (type,title,status,detail,instance,code,retryable,invalid_params,suggested_action). Rawthrow new Error("msg")in public APIs is prohibited. - Clean
.d.tshover readability. Do not author type gymnastics that evaluate to massive, unreadable union expansions in IDE tooltips. Use clean interface aliases, exported types, and nominal brands to maintain high developer comprehension.
Execution Router
| Task Shape | Primary Workflow | Reference Contract |
| Authoring a new public SDK or client library | Architect SDK | Progressive Disclosure |
| Designing a developer-facing CLI tool | Design CLI | Pit of Success Defaults |
| Refactoring an internal module boundary | Refactor Module Contract | Illegal States Unrepresentable |
| Auditing API ergonomics or conducting PR review | Audit API Ergonomics | RFC 9457 Problem Details |
| Validating an API contract record | Record Contract | scripts/api_contract_guard.py |
Mandatory Pre-Execution Interrogation Matrix
Before emitting or approving an SDK, CLI, or module boundary, evaluate against this matrix:
- The Caller Experience: Can a first-time developer write a working call in under 10 seconds from IDE autocomplete alone? Does the 80% use case require importing more than 1 symbol?
- The Failure Blast Radius: If a developer makes a mistake, does it fail at compile time? Or does it fail silently at runtime after 3 hours of execution?
- The Option Bag Density: Does the function take more than 5 required parameters? If yes, refactor into an options object with sensible defaults.
- The State Machine Integrity: Can an entity simultaneously have
success = trueanderror = "Timeout"? Can a cancelled job have an active worker ID? If yes, collapse into a discriminated union. - The Error Transparency: When a network or domain call fails, can the consumer's automated remediation handler parse the exact machine code and parameter path without regex-matching error message strings?
Prohibited Anti-Patterns (Instant Rejection List)
- The Boolean Trap:
function updateUser(id: string, true, false, true)— consecutive or positional boolean flags that obfuscate caller intent. - Stringly-Typed Identifiers:
function transfer(from: string, to: string)whereAccountIdandUserIdcan be accidentally reversed without compiler errors. - Option Explosion Soup: Forcing callers to provide 10 separate fields just to initialize a basic client or execute a default read.
- Throwing Bare Errors:
throw new Error("Invalid request")lacking machine-readable error codes, RFC 9457 problem details, or documentation links. - Ambiguous Return Tuples/Objects: Returning
{ data?: T; error?: E }where both can beundefinedor both can be present simultaneously. - Unbounded Collections: Returning raw unbounded arrays from service endpoints without cursor pagination and hard ceilings.
- Hanging Default Network Calls: Creating
fetch()or HTTP clients without an explicit timeout mechanism.
Required Output & Review Workflow
Structure all contract implementations, designs, and reviews through this 3-phase discipline:
- Ergonomics & Contract Pre-Mortem: Identify the top 3 developer pain points, boolean traps, state contradiction risks, or error ambiguities in the proposed boundary.
- Hardened Contract Implementation: Emit clean, production-grade TypeScript/CLI code with branded types, discriminated unions, safe defaults, and RFC 9457 errors from line one.
- Type & DX Verification: Supply or execute compile-time and runtime tests: type assertions proving illegal states fail compilation, exhaustiveness tests, and automated error-handling verification.
When a durable architectural record is warranted, save a JSON assessment following the API Contract Record Contract and audit it with:
npx anti-slop-engineering contract audit <record.json> --json
# or: python3 scripts/api_contract_guard.py audit <record.json> --jsonDomain References
- Playbook Suite Overview: Central index for ergonomic contract governance.
- Microsoft TypeScript Playbook: Compiler-team standards, branded types,
.d.tshygiene, and autocomplete optimization. - Stripe DX Playbook: Idempotency keys, resource structures, cursor pagination, and predictable error handling.
- API Booby-Trap Catalog: Forensic analysis of boolean traps, stringly types, and leaky abstractions.
- Pit of Success Defaults: Zero-config execution, safe timeouts, and automatic jittered retries.
- Illegal States Unrepresentable: Discriminated unions, nominal brands, and exhaustive pattern matching.
- Progressive Disclosure Patterns: 3-tier API architectures from one-liners to power builders.
- RFC 9457 Problem Details Contract: Machine-readable error schema, remediation actions, and HTTP/CLI mapping.
- API Contract Record Contract: Schema for persistent API contract assessment records.
Failure Taxonomy
| Failure Mode | Observable Signal | Remediation |
| Boolean trap | fn(id, true, false) with positional booleans | Refactor to named option object with discriminated union literals |
| Transposed ID bug | Passing orgId into userId parameter | Wrap raw strings in nominal Branded Types |
| State contradiction | Object containing both data and error or incompatible fields | Model states as a tagged Discriminated Union |
| Cognitive overload | Requiring 10 parameters to execute a basic operation | Introduce 1-liner progressive disclosure facade with safe defaults |
| Opaque error handling | Callers scraping string messages with regex | Implement RFC 9457 Problem Details with machine codes |
| Network hang | Client stalls indefinitely during upstream network degradation | Bind AbortSignal.timeout(10_000) by default |
Delegated Skills
anti-slop-engineering: Follow BUILD/FIX gates and clean-room engineering standards once the contract is established.paranoid-principal-architect: Enforce 10M scale, zero-trust boundary parsing, and data-layer authorization.safe-evolution-and-rollout-choreographer: Verify additive schema evolution and N-1/N+1 wire compatibility when updating existing contracts.
Completion and Limits
The task is complete when the API contract compiles with zero any, renders illegal states unrepresentable via discriminated unions and branded types, offers safe-by-default progressive disclosure from 1-line operations to advanced engines, and surfaces all errors through RFC 9457 problem details with verified machine codes. An ergonomics audit may validly output refuse or pause if a contract forces boolean traps, option explosion, or untyped error handling.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

