api-forge
Use to derive the API contract for a feature — an OpenAPI 3.1 document at docs/features/{slug}/contracts/openapi.yaml plus a drift/sync report (api-sync-report.md with an explicit Verdict: PASS | PASS (with deferrals) | FAIL and a 5-point drift checklist), the right contract artifact per surface (events.md for async, cli.md for CLI, public-api.md for library/SDK), and — on the HTTP path, first run only — a baseline .claude/rules/openapi.md so later code follows the same API conventions. Triggers on "api for {slug}", "openapi for {slug}", "API contract for {slug}", "lock the interface for {slug}", "events for {slug}", "/sdlc:api-forge {slug}", "контракт API для {slug}", "OpenAPI для {slug}", "опиши ендпоінти". The contract is never hand-written: it is a derived function of data-model.md (typed fields + constraints), sad.md §6 sequence diagrams (error branches, async actors), and PRD.md acceptance criteria. Hard gate: docs/features/{slug}/PRD.md. data-model.md is recommended but optional — without it the skill runs in scenario B (PRD + sequences only) and fills unresolved_origins in the sync report. Renamed from define-api in v3.3.0; the legacy name is kept as a deprecation wrapper.
- License 许可
- MIT
- 最近更新
- 2026-11-12
- Stars
- ★ 15
- Forks
- 13
01 前言 Front Matter
- name
- api-forge
- stage
- 10
- triggers
- [ "/sdlc:api-forge" ]
- description
- Use to derive the API contract for a feature — an OpenAPI 3.1 document at docs/features/{slug}/contracts/openapi.yaml plus a drift/sync report (api-sync-report.md with an explicit Verdict: PASS | PASS (with deferrals) | FAIL and a 5-point drift checklist), the right contract artifact per surface (events.md for async, cli.md for CLI, public-api.md for library/SDK), and — on the HTTP path, first run only — a baseline .claude/rules/openapi.md so later code follows the same API conventions. Triggers on "api for {slug}", "openapi for {slug}", "API contract for {slug}", "lock the interface for {slug}", "events for {slug}", "/sdlc:api-forge {slug}", "контракт API для {slug}", "OpenAPI для {slug}", "опиши ендпоінти". The contract is never hand-written: it is a derived function of data-model.md (typed fields + constraints), sad.md §6 sequence diagrams (error branches, async actors), and PRD.md acceptance criteria. Hard gate: docs/features/{slug}/PRD.md. data-model.md is recommended but optional — without it the skill runs in scenario B (PRD + sequences only) and fills unresolved_origins in the sync report. Renamed from define-api in v3.3.0; the legacy name is kept as a deprecation wrapper.
02 资源文件 6
- 参考文档references/drift-check.md12.0 KB
- 参考文档templates/cli.md2.7 KB
- 参考文档templates/events.md2.4 KB
- 参考文档templates/openapi.yaml5.5 KB
- 参考文档templates/public-api.md2.9 KB
- 参考文档templates/rules-openapi-baseline.md2.7 KB
03 SKILL.md 正文
Skill: api-forge
Projects the upstream artifacts into one interface contract. By default that's an HTTP/OpenAPI contract; this skill is interface-kind aware — and the kind comes from the surface(s) architecture-design declared in sad.md frontmatter target_surfaces, read here, not re-derived (→ ../_shared/surfaces.md). For a non-HTTP project it produces the matching contract form:
- HTTP / REST (default) →
contracts/openapi.yaml(OpenAPI 3.1) +api-sync-report.md. - gRPC / RPC → a
.proto(or the repo's IDL) with the same derive-and-drift discipline. - CLI →
contracts/cli.md— the command/flag/exit-code surface derived from the AC. - Library / SDK →
contracts/public-api.md— the public signatures/types the feature exposes. - Event-only / worker → just
contracts/events.md(no request/response surface). - No external interface (pure internal logic) → skip with a one-line note in the report; go straight to
break-tasks.
Whatever the form, the contract is derived from data-model.md + the sad.md §6 sequences + the PRD's AC, never typed by hand — generation that diverges from the model or the sequences is the bug this skill exists to catch. The rest of this file details the HTTP path (the common case); the same derive → drift-check → reconcile loop applies to the other forms with the form-appropriate artifact.
This skill keeps only its own machinery. Depth (events doc only when async; one resource vs full surface) follows the size matrix → ../_shared/size-matrix.md.
Owner
Backend Lead (drives the interface). The PM confirms each endpoint maps to a real user story; a frontend / consumer engineer is the first reader — the contract is locked before they start integration.
Inputs
<slug>— same feature slug used by every earlier stage.- Gate (hard-refuse if missing):
docs/features/<slug>/PRD.md. It is the source of user stories and acceptance criteria; without it the endpoint list would be invented. If absent → STOP and point: «run/sdlc:write-prd <slug>first». - Recommended (presence determines scenario A vs B):
docs/features/<slug>/data-model.md— strongest source of typed fields and constraints. Presence triggers scenario A (typed contract). Absence triggers scenario B (PRD/sequence-derived contract withunresolved_originsblock).docs/features/<slug>/sad.md§6 — the MermaidsequenceDiagramblocks. Theiralt/elsebranches become errorresponses; an async participant (<message-bus>/<external-system>) on a mutating flow marks its endpointIdempotency-Key-required and seedsevents.md. Absent → note the gap and still generate.
- Optional (auto-detected, enrich when present):
docs/features/<slug>/adr/*.md— architecture decisions that override defaults (versioning, error format, auth scheme).docs/features/<slug>/CONTEXT.md— glossary terms become schema names verbatim.- Existing
contracts/openapi.yaml— if present, diff and update in place, never overwrite whole-cloth. docs/features/<slug>/.size— depth hint. Absent → default to M (full surface).
If any recommended/optional input is missing, the skill still generates a usable contract. The api-sync-report.md flags which enrichment was skipped and why it would have helped.
Scenarios A vs B
The skill detects scenario from inputs and tells the user which one it is running.
Scenario A — data-model.md exists (preferred)
Contract is derived from the model. Every field has an origin in a typed entity. Constraints (maxLength, pattern, enum) trace back to DDL (varchar(N), CHECK, ENUM type). Error codes derive from constraints (UNIQUE (a, b) → <entity>.duplicate_<field>). unresolved_origins is empty.
Drift check verifies field-by-field alignment. Drift in scenario A means model and contract disagree on form — human resolves which artifact is right. Only scenario A can reach a plain PASS verdict.
Scenario B — data-model.md missing (fallback)
Contract is inferred from PRD §4 acceptance criteria + sequence diagrams + SAD §6 namespacing. Types are less precise (string without maxLength, no enum patterns yet). Error codes derive from alt-blocks in sequences, not from constraints.
unresolved_origins lists every field whose origin is "inferred from PRD/sequence, needs confirmation when data-model.md arrives". This is not an error — it is declared incompleteness, visible to the team. Because something is always parked, a scenario-B report reads PASS (with deferrals) at best, never plain PASS.
Reconcile (--reconcile flag)
When data-model.md arrives after a scenario-B run, re-run with --reconcile. It:
- Re-reads all inputs.
- Switches scenario B → A.
- Tightens types:
stringbecomesstring+maxLengthwhere DDL exists. - Promotes low-confidence origins to high.
- Empties
unresolved_origins. - Surfaces any field that had an inferred origin but now disagrees with the model — that is real drift, not stale incompleteness.
info.version is never bumped silently; the user bumps semver explicitly with a CHANGELOG line.
Defaults
Fixed minimum, not invented per feature; an adr/*.md overrides any of them and the report records "deviation by ADR-NNNN". The same defaults are written once into the repo as .claude/rules/openapi.md (protocol step 2, from ./templates/rules-openapi-baseline.md) so that the handlers, clients and tests written later follow the contract's conventions, not only the contract itself.
| Topic | Default | Rationale |
|---|---|---|
| OpenAPI version | 3.1.0 |
JSON Schema 2020-12 reused by JSON validators; native webhooks; nullable via type: [string, null]. |
| Error response shape | {code, message, details?} snake_case |
Homogeneous FE handling; code gives machine rule "retry vs change request". |
Error code namespacing |
<module>.<error_name> |
lesson.duplicate_slug, lesson.module_not_found — domain-readable, neutral convention. |
| Pagination for list endpoints | Cursor (UUID v7), not offset | Stable pages under concurrent writes; stable context for AI consumer. |
| URL versioning | /api/v1/... |
Simpler than header versioning; cacheable; version is visible in the path. |
| Authentication | BearerAuth global |
Global default; public endpoints declare explicit security: []. |
| Schema reuse | $ref mandatory; inline schemas forbidden |
Single source of truth per type — less drift between endpoints. |
| Forbidden | nullable: true (3.0 style), real PII in example, additionalProperties: true on response shapes, ?v=2 query versioning, offset pagination |
Well-known anti-patterns. |
Protocol
-
Gate + interface kind + read.
test -f docs/features/<slug>/PRD.md→ fail = refuse with the pointer above. Determine the interface kind — readsad.mdfrontmattertarget_surfacesFIRST (architecture-design already declared it; the surface picks the contract form per../_shared/surfaces.md:backend-service→ OpenAPI / gRPC / events per its sub-kind;cli→contracts/cli.md;worker→contracts/events.md;library-sdk→contracts/public-api.md; a UI surface —web-frontend/mobile-app/desktop-app— consumes the backend contract, it does not author one). Fall back to deriving the kind fromdocs/architecture-map.md+ the PRD's capabilities only if the SAD or the field is absent (a greenfield run wherearchitecture-designwas skipped). HTTP/REST → the OpenAPI path below (default); gRPC/CLI/library/event-only → produce the matching contract form with this same derive→drift→reconcile loop; no external interface (pure internal logic) → skip tobreak-taskswith a one-line note in the report. Then detect scenario (A ifdata-model.mdexists, B otherwise). Surface a one-line "found / missing" note for sad.md and data-model.md. -
Rules bootstrap (HTTP path only). If
.claude/rules/openapi.mdis absent in the repo root, copy./templates/rules-openapi-baseline.md→.claude/rules/openapi.mdand tell the user «I wrote a baseline API rules file; edit it if your team disagrees with any default.» Reporting this bootstrap is mandatory (same mechanism asgenerate-data-model→.claude/rules/migrations.md). If the file already exists, read it — a team edit there overrides the Defaults table below the same way an ADR does, and the report records the deviation. Skip this step for CLI / library / event-only surfaces. -
Copy the template.
./templates/openapi.yaml→docs/features/<slug>/contracts/openapi.yaml. If async flows exist, also./templates/events.md→contracts/events.md. If CLI surface,./templates/cli.md→contracts/cli.md. If library-sdk surface,./templates/public-api.md→contracts/public-api.md. Fillinfo.descriptionfrom PRD §1 (why this API exists). -
Derive endpoints + schemas. One endpoint (or more) per PRD §4 user story. In scenario A, every request/response field traces to a
data-model.mdentity column — copy its constraints across (maxLength/pattern/enumfrom the model's bounded types). In scenario B, schemas are derived from PRD field names + sequence message names;unresolved_originsis populated. Never invent a field with no origin in any input — ask the user where it comes from.$refevery shared schema; no inline duplication. Lists paginate by cursor (?after=&before=&limit=), wrapped in{items, has_next, has_prev, next_cursor}. -
Derive error responses from the sequences. Each endpoint covered by a §6 flow: turn every
alt … else … endbranch into aresponsesentry. The error body is the unified envelope{code, message, details?};codefollows the neutral conventionmodule.error_name(snake_case, e.g.lesson.not_owned,lesson.invalid_state). Map status by class (4xx client / 5xx server). This closes the PRD's usual blind spot — PRD lists the happy path + a couple of errors; the sequences enumerate the authorization and concurrent-state branches the PRD omits. -
Async + idempotency. A mutating endpoint whose §6 flow shows a retry note or an async actor is marked
Idempotency-Key-required (state the TTL). For each async message, fill anevents.mdentry: event namemodule.action.vN, payload schema, producer, consumers, retry / dead-letter behaviour. -
Examples + placeholder data. Every operation carries a request example + a success example + an error example, using placeholder values only (
<...>@example.test,+380 00 000 00 00,Test User) — never real PII. -
Inline DRIFT CHECK (bidirectional) + write the report. Compare the generated contract against the read artifacts and write
docs/features/<slug>/contracts/api-sync-report.md— see./references/drift-check.md. It opens with a**Verdict:**line (PASS|PASS (with deferrals)|FAIL, rules in the reference), then holds a field-origins table (one row peroperation.field:path | origin | confidence), the 5-point drift checklist,unresolved_origins, and aDeferralslist. Each point is marked ✓, ✓ (deferred: one line) or ✗ (one-line diagnostic). The check runs both directions:- forward (contract derived correctly) — points 1–3, core: endpoint↔model, error-code↔repo, validation↔constraint.
- back-feed (coverage cross-check) — points 4–5, supporting: 4 every
data-model.mdentity is surfaced by ≥1 operation or marked intentionally internal, every PRD §5 AC maps to ≥1 operation/response, every operation maps to a §4 user story + ≥1 AC; 5 OpenAPI↔sequence — everysad.md§6alt-branch has a response, and any error/authorization response the contract needs but no §6 flow shows is a sequence gap. A gap here is not an api bug — it's a hole upstream: surface it and offer Fix-the-source-first, which re-openswrite-prd(add the missing AC) orcomplete-sequence-diagrams(draw the missing branch) before the contract is finalized. A core finding failing (or ≥3 flags total) pauses the run — resolve each via the 4-state actions: Accept-as-is / Fix-the-contract / Save-as-OQ / Fix-the-source-first. Never silently edit the sources — surface the mismatch and let the human pick the right artifact (the contract, the PRD's AC, or the sequence). Then set the verdict from what is left: all 5 ✓ and nothing parked →PASS; core 1–3 ✓ but something consciously parked (scenario B, a deferred supporting point, a Save-as-OQ, a sequence gap) →PASS (with deferrals); a core point still ✗, ≥3 open flags, or a field with no origin →FAIL. The report is written on every run, FAIL included — a FAIL that lives only in the chat is lost by the next/clear.
-
Lint + write + commit. Suggest
spectral lint contracts/openapi.yaml(add it to the project's check target if not yet wired). Write the files, propose commitapi: <slug> contract. Then emit the stage-handoff block per../_shared/handoff.md— What I did (incl. the verdict and whether.claude/rules/openapi.mdwas bootstrapped) + Review (contracts/openapi.yaml,api-sync-report.md, +events.mdif async, +cli.mdif CLI, +public-api.mdif library) + Run next: onPASS/PASS (with deferrals)→/clear, then/sdlc:break-tasks <slug>; onFAIL→ the fix-the-source command the report names (/sdlc:write-prd,/sdlc:complete-sequence-diagramsor/sdlc:generate-data-model <slug>), then/sdlc:api-forge <slug> --reconcile. AFAILnever hands off tobreak-tasks.
Reconcile mode
/sdlc:api-forge <slug> --reconcile. Re-derives after an upstream artifact changed (typically data-model.md arrived or was tightened after a thinner first pass). It re-reads inputs, tightens loose types where the model now has a constraint, refreshes the field-origins confidence column, and — the load-bearing part — surfaces any field that had an inferred origin but now disagrees with the model. That disagreement is real drift, not stale incompleteness.
Definition of Done
docs/features/<slug>/contracts/openapi.yamlwritten: OpenAPI 3.1,BearerAuthglobal with public endpoints declaring explicitsecurity: [], every error response the{code, message, details?}envelope, every operation with examples, all shared types via$ref.api-sync-report.mdwritten alongside:**Verdict:**line first, field-origins table, the 5-point drift checklist (1–3 core, 4–5 supporting), scenario recorded, every core finding ✓ or explicitly resolved,unresolved_originsempty (A) or listed (B),Deferralslisted with a next step (or "none").- Verdict is
PASSorPASS (with deferrals). AFAILreport is a valid artifact but the stage is not done — the report names what to fix and the run is repeated with--reconcile. - On the HTTP path,
.claude/rules/openapi.mdexists in the repo root (bootstrapped from the baseline on first run and reported, or already there and read). - Every endpoint maps to a PRD §4 user story; every field traces to a
data-model.mdcolumn (scenario A) or has an explicit inferred origin noted (scenario B); every errorcodeexists in the repo's error definitions. contracts/events.mdpresent iff the feature has async flows; each event has a payload schema, producer, consumers, retry / DLQ note.contracts/cli.mdpresent iff the surface iscli;contracts/public-api.mdpresent iff the surface islibrary-sdk.
Conflicts — human in the loop
| Conflict | Skill action |
|---|---|
Field in data-model.md with no story in PRD covering it |
Add it to the schema with a # unused-in-prd note in the report; ask the user. |
| A §6 sequence references a flow that maps to no endpoint | Flag # orphan-sequence in the report; ask (forgotten endpoint? internal job?). |
PRD §5 constraint contradicts a data-model.md constraint |
Take the stricter value; flag both; the human resolves which artifact is wrong. |
Existing openapi.yaml has a field absent from every source |
Keep it with a # manual-addition note; flag in the report. |
A field disappeared from data-model.md |
Keep it in the YAML with a # stale note; surface it — the human removes from the contract or restores in the model. |
If ≥3 flags appear in one run, pause, list them, and ask whether to continue or fix the sources first.
Anti-patterns
- Contract written by hand, then the model/sequences bent to fit it. The arrow is one-way: model + sequences + PRD → contract.
- Skipping the drift check because "it was just generated, of course it matches". Generation can match the PRD-as-read while diverging from the model or the sequences — different files, different authors. A clean 5/5 ✓ is cheap; a silent ✗ in prod is not.
- Writing
PASSover an open finding. A core ✗ that was not resolved through the 4-state actions is aFAIL; a parked item without aDeferralsentry is a hidden deferral. The verdict is derived from the checklist, never typed from a feeling. - Bootstrapping
.claude/rules/openapi.mdand forgetting to tell the user. Report it when it happens — the user owns that file from then on. - Error responses from the PRD only. PRD lists happy + a couple of errors; the §6 sequences hold the authorization and concurrent-state branches. Skipping them leaves blind spots.
- Inventing a field with no origin in any input, or silently dropping one that left
data-model.md(keep it with a# stalenote and surface it — the human decides). - Stack-specific schema or error names. Schemas use the domain language from
data-model.md; error codes are the neutralmodule.error_nameconvention — not a Go/TS/Python idiom and not tied to any driver's error type. - Free-text errors (
{"error": "failed"}),?v=2query versioning,nullable: true(3.0 style — usetype: [string, null]), offset pagination, or real PII in examples. - Re-deriving the interface kind when
architecture-designalready declared it.target_surfacesinsad.mdis the primary signal — read it; the architecture-map derivation is the fallback only when the SAD/field is absent. Silently re-inferring HTTP-vs-events on every run is the double-derivation this skill's surface-awareness removes. - Hiding scenario B as if it were complete. Scenario B is a valid state, not a half-baked one.
unresolved_originsmust be visible. Pretending the contract is fully typed when it isn't sets the team up for silent drift when the model arrives.
Sources of best practices
- Microsoft REST API Guidelines — https://github.com/microsoft/api-guidelines. Error shape with machine-readable
code, URL versioning,BearerAuthdefault. - Google AIP (API Improvement Proposals) — https://google.aip.dev/. Resource-oriented paths, snake_case field names, domain-namespaced error codes.
- Zalando RESTful API Guidelines — https://opensource.zalando.com/restful-api-guidelines/. Cursor pagination via next-link, JSON-only responses, snake_case JSON.
- OpenAPI 3.1 specification — https://spec.openapis.org/oas/v3.1.0. Full JSON Schema 2020-12 compatibility.
References & templates
../_shared/surfaces.md— the declaredtarget_surfaces(read fromsad.md) pick the contract form; this skill reads, never re-derives.../_shared/size-matrix.md— MVP (one resource, events only if async) vs Full surface depth.../_shared/handoff.md— stage-handoff block format../references/drift-check.md— report shape: verdict rules, field-origins table, 5-point drift checklist, deferrals, reconcile semantics, conflict table../templates/rules-openapi-baseline.md— baseline.claude/rules/openapi.mdcopied at step 2 when missing (HTTP path)../templates/openapi.yaml— OpenAPI 3.1 scaffold:BearerAuth, cursor page wrapper,{code, message, details?}Error schema../templates/events.md— async event-contract scaffold (producer / consumers / payload / retry / DLQ)../templates/cli.md— CLI surface contract scaffold (commands / flags / exit codes)../templates/public-api.md— library/SDK public-API contract scaffold (public signatures / types).
04 同仓库更多 Skills
release
Run the whole local release pipeline in order, stopping at each human gate. Triggers on "run the release", "prepare a release", "/release", "зроби реліз", "підготуй реліз". Drives the four stages back to back — bump-version → curate-changelog → release-notes → check-docs-drift — pausing after each so the human reviews the diff before the next stage. Prepares everything in the working tree; never tags, commits, or pushes. The tag push (which fires CI) stays the human's action.
release-notes
Draft partner-facing release notes from the same commits as the changelog. Triggers on "draft release notes", "release notes for the next version", "/release-notes", "нотатки релізу", "release notes партнеру". Same input as curate-changelog, different audience and tone: a short, benefit-first narrative for a user or partner — "what's new for you" — not a categorized engineer's list. Keeps only changes a user actually notices; drops internal refactors and tooling. Prints the notes to the chat to seed a GitHub Release description or a partner announcement. Writes no file.
curate-changelog
Curate the [Unreleased] section of docs/CHANGELOG.md from git history. Triggers on "curate the changelog", "update the changelog", "/curate-changelog", "онови changelog", "курування журналу". Reads git log since the last tag, FILTERS out what a reader never feels (test/ci/chore/merge), GROUPS commits about one feature into one bullet, and REWRITES technical subjects into plain language under the six Keep a Changelog categories (Added/Changed/Deprecated/ Removed/Fixed/Security). The result must have FEWER lines than the raw log — that is the proof of curation, not a dump. Leaves the edit in the working tree; never commits or pushes.
codify-rule
Turn a repeated mistake into a durable, path-scoped rule in .claude/rules/. Triggers on "codify this rule", "make a rule so this doesn't happen again", "/codify-rule", "закодифікуй правило", "петля помилка-правило". Use only when the same mistake showed up TWICE (twice = a pattern, once = noise). Names the wrong shape and the right shape with one short example of each, scopes the rule to the paths that matter, and leaves the edit in the working tree so the next agent on this repo inherits the fix. Edits only .claude/rules/; never commits or pushes.
check-docs-drift
Find and fix where docs/api.md fell behind the code. Triggers on "check for doc drift", "is the API doc up to date", "/check-docs-drift", "перевір дрейф документації", "docs drift". Runs the deterministic scripts/check-docs-drift.py (parses the public NoteBook methods with ast, compares to what docs/api.md documents — NO LLM finds the gap), reports the drift, and PROPOSES the doc edit that closes it. The gap is found by parsing; the agent writes the missing documentation in the doc's existing style. Edits only docs/; never commits or pushes.
bump-version
Decide and apply the next semver for a release. Triggers on "bump the version", "what version is next", "/bump-version", "простав версію", "яка наступна версія". Reads the next number from the deterministic scripts/next-version.sh (NEVER guesses it), explains in plain language WHICH part moved and why (e.g. "MINOR, because a feat landed: filter notes by tag"), edits the version line in pyproject.toml, and proposes the matching `git tag vX.Y.Z`. The number is decided by a rule; the agent explains and applies — the human confirms the tag. Never pushes a tag itself.