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-readable title, HTTP/CLI status, detailed detail, contextual instance, deterministic machine code, parameter-specific invalid_params, actionable suggested_action, and boolean retryable metadata.
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 of isAsync: boolean).
- Nominal branding for all domain identifiers. Never pass raw unbranded
string or number types 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): never utility 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_more and next_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
ProblemDetailsError containing standard fields (type, title, status, detail, instance, code, retryable, invalid_params, suggested_action). Raw throw new Error("msg") in public APIs is prohibited.
- Clean
.d.ts hover 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 = true and error = "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) where AccountId and UserId can 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 be undefined or 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> --json
Domain References
- Playbook Suite Overview: Central index for ergonomic contract governance.
- Microsoft TypeScript Playbook: Compiler-team standards, branded types,
.d.ts hygiene, 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.
1---2name: api-ergonomics-and-contract-governor3description: 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.4license: MIT5metadata:6 source: https://skillmd.com/skills/immamdouhaboammar/api-ergonomics-and-contract-governor7 version: "0.1.0"8 parent: anti-slop-engineering9---1011# Skill: The API Ergonomics & Contract Governor (Microsoft TypeScript & Stripe DX)1213> Design APIs where the easiest way to use them is also the correct, safe, and performant way.1415## Why This Skill Is Needed & Target State1617AI 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.1819The 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).2021---2223## Activation and Boundaries2425| Situation | Behavior |26| --- | --- |27| Designing a new public SDK, client library, or internal service boundary | Enforce Pit-of-Success defaults, 3-tier progressive disclosure, and branded types |28| Defining domain entities, request options, or status state machines | Model using Discriminated Unions; eliminate boolean flags and impossible states |29| Authoring CLI tools, commands, or developer toolkits | Enforce zero-config default execution, hierarchical subcommand discovery, and RFC 9457 error output |30| Modeling API errors, failure payloads, or exception classes | Implement RFC 9457 Problem Details with machine codes, retryability hints, and remediation actions |31| Auditing existing libraries or reviewing API PRs | Run adversarial ergonomics checks (Boolean trap audit, stringly-typed ID audit, option explosion audit) |32| Local loop optimizations, private helper refactors, or formatting | Do not activate; use Anti-Slop Engineering BUILD/FIX gates |3334---3536## The Four Absolute Pillars37381. **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.392. **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`).403. **Progressive Disclosure:** Structure APIs in three distinct cognitive tiers:41 - *Tier 1 (One-Liner):* High-level, zero-friction entry-point solving the 80% use case in a single call.42 - *Tier 2 (Configured Options):* Explicit, type-safe options bag overriding defaults for specific operational requirements.43 - *Tier 3 (Escape Hatch & Advanced Engine):* Direct access to underlying protocol, raw request client, custom transport adapters, and streaming pipelines without leaky abstractions.444. **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-readable `title`, HTTP/CLI `status`, detailed `detail`, contextual `instance`, deterministic machine `code`, parameter-specific `invalid_params`, actionable `suggested_action`, and boolean `retryable` metadata.4546---4748## Invariant Rules49501. **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 of `isAsync: boolean`).512. **Nominal branding for all domain identifiers.** Never pass raw unbranded `string` or `number` types 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.523. **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.534. **Exhaustive pattern matching enforcement.** All consumers handling discriminated unions must enforce compile-time exhaustiveness via a dedicated `assertNever(x: never): never` utility or compiler-checked switch statements.545. **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.556. **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.567. **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.578. **Cursor-based pagination with bounded page sizes.** Collection-returning methods must default to cursor pagination (returning `has_more` and `next_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.589. **Standardized RFC 9457 error contracts.** Custom error classes must inherit from a canonical `ProblemDetailsError` containing standard fields (`type`, `title`, `status`, `detail`, `instance`, `code`, `retryable`, `invalid_params`, `suggested_action`). Raw `throw new Error("msg")` in public APIs is prohibited.5910. **Clean `.d.ts` hover 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.6061---6263## Execution Router6465| Task Shape | Primary Workflow | Reference Contract |66| --- | --- | --- |67| Authoring a new public SDK or client library | [Architect SDK](usecases/architect-sdk.md) | [Progressive Disclosure](references/progressive-disclosure-patterns.md) |68| Designing a developer-facing CLI tool | [Design CLI](usecases/design-cli.md) | [Pit of Success Defaults](references/pit-of-success-defaults.md) |69| Refactoring an internal module boundary | [Refactor Module Contract](usecases/refactor-module-contract.md) | [Illegal States Unrepresentable](references/illegal-states-unrepresentable.md) |70| Auditing API ergonomics or conducting PR review | [Audit API Ergonomics](usecases/audit-api-ergonomics.md) | [RFC 9457 Problem Details](references/rfc9457-problem-details-contract.md) |71| Validating an API contract record | [Record Contract](references/api-contract-record-contract.md) | `scripts/api_contract_guard.py` |7273---7475## Mandatory Pre-Execution Interrogation Matrix7677Before emitting or approving an SDK, CLI, or module boundary, evaluate against this matrix:7879- **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?80- **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?81- **The Option Bag Density:** Does the function take more than 5 required parameters? If yes, refactor into an options object with sensible defaults.82- **The State Machine Integrity:** Can an entity simultaneously have `success = true` and `error = "Timeout"`? Can a cancelled job have an active worker ID? If yes, collapse into a discriminated union.83- **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?8485---8687## Prohibited Anti-Patterns (Instant Rejection List)88891. **The Boolean Trap:** `function updateUser(id: string, true, false, true)` — consecutive or positional boolean flags that obfuscate caller intent.902. **Stringly-Typed Identifiers:** `function transfer(from: string, to: string)` where `AccountId` and `UserId` can be accidentally reversed without compiler errors.913. **Option Explosion Soup:** Forcing callers to provide 10 separate fields just to initialize a basic client or execute a default read.924. **Throwing Bare Errors:** `throw new Error("Invalid request")` lacking machine-readable error codes, RFC 9457 problem details, or documentation links.935. **Ambiguous Return Tuples/Objects:** Returning `{ data?: T; error?: E }` where both can be `undefined` or both can be present simultaneously.946. **Unbounded Collections:** Returning raw unbounded arrays from service endpoints without cursor pagination and hard ceilings.957. **Hanging Default Network Calls:** Creating `fetch()` or HTTP clients without an explicit timeout mechanism.9697---9899## Required Output & Review Workflow100101Structure all contract implementations, designs, and reviews through this 3-phase discipline:1021031. **Ergonomics & Contract Pre-Mortem:** Identify the top 3 developer pain points, boolean traps, state contradiction risks, or error ambiguities in the proposed boundary.1042. **Hardened Contract Implementation:** Emit clean, production-grade TypeScript/CLI code with branded types, discriminated unions, safe defaults, and RFC 9457 errors from line one.1053. **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.106107When a durable architectural record is warranted, save a JSON assessment following the [API Contract Record Contract](references/api-contract-record-contract.md) and audit it with:108```bash109npx anti-slop-engineering contract audit <record.json> --json110# or: python3 scripts/api_contract_guard.py audit <record.json> --json111```112113---114115## Domain References116117- **[Playbook Suite Overview](playbooks/README.md)**: Central index for ergonomic contract governance.118- **[Microsoft TypeScript Playbook](playbooks/microsoft-typescript-playbook.md)**: Compiler-team standards, branded types, `.d.ts` hygiene, and autocomplete optimization.119- **[Stripe DX Playbook](playbooks/stripe-dx-playbook.md)**: Idempotency keys, resource structures, cursor pagination, and predictable error handling.120- **[API Booby-Trap Catalog](playbooks/references/api-booby-traps.md)**: Forensic analysis of boolean traps, stringly types, and leaky abstractions.121- **[Pit of Success Defaults](references/pit-of-success-defaults.md)**: Zero-config execution, safe timeouts, and automatic jittered retries.122- **[Illegal States Unrepresentable](references/illegal-states-unrepresentable.md)**: Discriminated unions, nominal brands, and exhaustive pattern matching.123- **[Progressive Disclosure Patterns](references/progressive-disclosure-patterns.md)**: 3-tier API architectures from one-liners to power builders.124- **[RFC 9457 Problem Details Contract](references/rfc9457-problem-details-contract.md)**: Machine-readable error schema, remediation actions, and HTTP/CLI mapping.125- **[API Contract Record Contract](references/api-contract-record-contract.md)**: Schema for persistent API contract assessment records.126127---128129## Failure Taxonomy130131| Failure Mode | Observable Signal | Remediation |132| --- | --- | --- |133| Boolean trap | `fn(id, true, false)` with positional booleans | Refactor to named option object with discriminated union literals |134| Transposed ID bug | Passing `orgId` into `userId` parameter | Wrap raw strings in nominal Branded Types |135| State contradiction | Object containing both `data` and `error` or incompatible fields | Model states as a tagged Discriminated Union |136| Cognitive overload | Requiring 10 parameters to execute a basic operation | Introduce 1-liner progressive disclosure facade with safe defaults |137| Opaque error handling | Callers scraping string messages with regex | Implement RFC 9457 Problem Details with machine codes |138| Network hang | Client stalls indefinitely during upstream network degradation | Bind `AbortSignal.timeout(10_000)` by default |139140---141142## Delegated Skills143144- `anti-slop-engineering`: Follow BUILD/FIX gates and clean-room engineering standards once the contract is established.145- `paranoid-principal-architect`: Enforce 10M scale, zero-trust boundary parsing, and data-layer authorization.146- `safe-evolution-and-rollout-choreographer`: Verify additive schema evolution and N-1/N+1 wire compatibility when updating existing contracts.147148---149150## Completion and Limits151152The 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.