agentleFS
imMamdouhaboammarimMamdouhaboammar/anti-slop-engineering/skills/api-ergonomics-and-contract-governor/SKILL.md

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.

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
  1. Very specific:

    Nominal branding for all domain identifiers: Never pass raw unbranded string or number types for entity IDs across public module boundaries.

    line 50
  2. Very specific:

    Exhaustive pattern matching enforcement: All consumers handling discriminated unions must enforce compile-time exhaustiveness via a …

    line 52
  3. Very specific:

    Built-in timeout and cancellation discipline: Every network-bound method must accept an optional AbortSignal, defaulting to a safe built-in …

    line 54
  4. Very specific:

    Clean .d.ts hover readability: Do not author type gymnastics that evaluate to massive, unreadable union expansions in IDE tooltips.

    line 58
  5. Distinctive:

    Before emitting or approving an SDK, CLI, or module boundary, evaluate against this matrix:

    line 76
  6. Distinctive:

    The Failure Blast Radius: If a developer makes a mistake, does it fail at compile time?

    line 79
  7. Distinctive:

    The Error Transparency: When a network or domain call fails, can the consumer's automated remediation handler parse the exact machine code …

    line 82
  8. Distinctive:

    When a durable architectural record is warranted, save a JSON assessment following the API Contract Record Contract and audit it with:

    line 106

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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

SituationBehavior
Designing a new public SDK, client library, or internal service boundaryEnforce Pit-of-Success defaults, 3-tier progressive disclosure, and branded types
Defining domain entities, request options, or status state machinesModel using Discriminated Unions; eliminate boolean flags and impossible states
Authoring CLI tools, commands, or developer toolkitsEnforce zero-config default execution, hierarchical subcommand discovery, and RFC 9457 error output
Modeling API errors, failure payloads, or exception classesImplement RFC 9457 Problem Details with machine codes, retryability hints, and remediation actions
Auditing existing libraries or reviewing API PRsRun adversarial ergonomics checks (Boolean trap audit, stringly-typed ID audit, option explosion audit)
Local loop optimizations, private helper refactors, or formattingDo not activate; use Anti-Slop Engineering BUILD/FIX gates

The Four Absolute Pillars

  1. 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.
  2. 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).
  3. 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.
  4. 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

  1. 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).
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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 ShapePrimary WorkflowReference Contract
Authoring a new public SDK or client libraryArchitect SDKProgressive Disclosure
Designing a developer-facing CLI toolDesign CLIPit of Success Defaults
Refactoring an internal module boundaryRefactor Module ContractIllegal States Unrepresentable
Auditing API ergonomics or conducting PR reviewAudit API ErgonomicsRFC 9457 Problem Details
Validating an API contract recordRecord Contractscripts/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)

  1. The Boolean Trap: function updateUser(id: string, true, false, true) — consecutive or positional boolean flags that obfuscate caller intent.
  2. Stringly-Typed Identifiers: function transfer(from: string, to: string) where AccountId and UserId can be accidentally reversed without compiler errors.
  3. Option Explosion Soup: Forcing callers to provide 10 separate fields just to initialize a basic client or execute a default read.
  4. Throwing Bare Errors: throw new Error("Invalid request") lacking machine-readable error codes, RFC 9457 problem details, or documentation links.
  5. Ambiguous Return Tuples/Objects: Returning { data?: T; error?: E } where both can be undefined or both can be present simultaneously.
  6. Unbounded Collections: Returning raw unbounded arrays from service endpoints without cursor pagination and hard ceilings.
  7. 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:

  1. Ergonomics & Contract Pre-Mortem: Identify the top 3 developer pain points, boolean traps, state contradiction risks, or error ambiguities in the proposed boundary.
  2. Hardened Contract Implementation: Emit clean, production-grade TypeScript/CLI code with branded types, discriminated unions, safe defaults, and RFC 9457 errors from line one.
  3. 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 ModeObservable SignalRemediation
Boolean trapfn(id, true, false) with positional booleansRefactor to named option object with discriminated union literals
Transposed ID bugPassing orgId into userId parameterWrap raw strings in nominal Branded Types
State contradictionObject containing both data and error or incompatible fieldsModel states as a tagged Discriminated Union
Cognitive overloadRequiring 10 parameters to execute a basic operationIntroduce 1-liner progressive disclosure facade with safe defaults
Opaque error handlingCallers scraping string messages with regexImplement RFC 9457 Problem Details with machine codes
Network hangClient stalls indefinitely during upstream network degradationBind 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.