oc-harness-setup 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/.docs/unwired-routing.md +14 -9
  2. package/.gitignore +14 -1
  3. package/AGENTS.md +70 -106
  4. package/README.md +55 -24
  5. package/agents/build.md +10 -12
  6. package/agents/explore.md +14 -8
  7. package/agents/general.md +7 -9
  8. package/agents/orchestrator.md +38 -0
  9. package/agents/plan.md +10 -13
  10. package/agents/reviewer.md +9 -14
  11. package/agents/vault.md +44 -35
  12. package/bin/cli.js +32 -3
  13. package/commands/build.md +2 -8
  14. package/commands/checkpoint.md +3 -1
  15. package/commands/code-simplify.md +3 -9
  16. package/commands/gauntlet.md +7 -0
  17. package/commands/handoff.md +3 -1
  18. package/commands/keeper.md +3 -3
  19. package/commands/kill.md +11 -0
  20. package/commands/plan.md +2 -13
  21. package/commands/retro.md +15 -0
  22. package/commands/review.md +1 -1
  23. package/commands/ship.md +3 -27
  24. package/commands/spec.md +3 -11
  25. package/commands/test.md +2 -9
  26. package/commands/webperf.md +7 -0
  27. package/opencode.jsonc +23 -8
  28. package/package.json +5 -4
  29. package/reference/README.md +14 -14
  30. package/reference/auto-mandate.md +11 -0
  31. package/reference/backup-convention.md +9 -0
  32. package/reference/clean-mandate.md +13 -0
  33. package/reference/editor-parity.md +7 -0
  34. package/reference/gc-scripts.md +8 -0
  35. package/reference/intent-routing.md +14 -0
  36. package/reference/lifecycle.md +15 -0
  37. package/reference/model-keeper.md +30 -10
  38. package/reference/model-test.md +11 -6
  39. package/reference/models.md +25 -14
  40. package/reference/oc-source-map.md +162 -0
  41. package/reference/owner-pin.md +31 -0
  42. package/reference/roster.md +15 -0
  43. package/reference/session-scope.md +9 -0
  44. package/reference/session-state.md +13 -0
  45. package/reference/swarm.md +32 -0
  46. package/scripts/backup-config.ps1 +42 -0
  47. package/scripts/gc-branch.ps1 +196 -0
  48. package/scripts/gc-bump.ps1 +198 -0
  49. package/scripts/gc-clean.ps1 +648 -0
  50. package/scripts/gc-commit.ps1 +143 -0
  51. package/scripts/gc-merge.ps1 +272 -0
  52. package/scripts/gc-pr.ps1 +190 -0
  53. package/scripts/gc-push.ps1 +111 -0
  54. package/scripts/gc-read.ps1 +150 -0
  55. package/scripts/gc-rebase.ps1 +162 -0
  56. package/scripts/gc-release.ps1 +225 -0
  57. package/scripts/gc-stage.ps1 +103 -0
  58. package/scripts/gc-status.ps1 +127 -0
  59. package/scripts/gc-sync.ps1 +65 -0
  60. package/scripts/gc.core.ps1 +715 -0
  61. package/scripts/gc.smoke.ps1 +779 -0
  62. package/scripts/harness-doctor.ps1 +11 -9
  63. package/scripts/interrupt-session.ps1 +65 -0
  64. package/scripts/logbook/README.md +108 -0
  65. package/scripts/logbook/logbook.test.ts +440 -0
  66. package/scripts/logbook/logbook.ts +797 -0
  67. package/scripts/pirep/README.md +147 -0
  68. package/scripts/pirep/pirep.test.ts +735 -0
  69. package/scripts/pirep/pirep.ts +836 -0
  70. package/scripts/testflight/README.md +112 -0
  71. package/scripts/testflight/testflight.test.ts +512 -0
  72. package/scripts/testflight/testflight.ts +806 -0
  73. package/skills/_shared/SOURCES.md +7 -7
  74. package/skills/_shared/references/definition-of-done.md +2 -2
  75. package/skills/_shared/references/orchestration-patterns.md +1 -2
  76. package/skills/_shared/references/security-checklist.md +2 -2
  77. package/skills/api-and-interface-design/SKILL.md +7 -360
  78. package/skills/browser-testing-with-devtools/SKILL.md +303 -0
  79. package/skills/code-simplification/SKILL.md +7 -364
  80. package/skills/creative-writing/SKILL.md +1 -1
  81. package/skills/debugging-and-error-recovery/SKILL.md +8 -309
  82. package/skills/flight-deck/SKILL.md +17 -0
  83. package/skills/frontend-ui-engineering/SKILL.md +8 -320
  84. package/skills/gauntlet/SKILL.md +21 -0
  85. package/skills/git-ceremony/SKILL.md +16 -318
  86. package/skills/grilling/SKILL.md +10 -30
  87. package/skills/observability-and-instrumentation/SKILL.md +9 -229
  88. package/skills/performance-optimization/SKILL.md +8 -488
  89. package/skills/pilot-report/SKILL.md +18 -0
  90. package/skills/planning-and-task-breakdown/SKILL.md +8 -249
  91. package/skills/security-and-hardening/SKILL.md +9 -490
  92. package/skills/source-driven-development/SKILL.md +8 -208
  93. package/skills/spec-driven-development/SKILL.md +15 -234
  94. package/skills/test-driven-development/SKILL.md +8 -388
  95. package/skills/test-flight/SKILL.md +14 -0
  96. package/skills/writing-for-agents/SKILL-MECHANICS.md +3 -3
  97. package/skills/writing-for-agents/SKILL.md +7 -1
  98. package/agents/coder.md +0 -19
  99. package/agents/documenter.md +0 -28
  100. package/agents/keeper.md +0 -22
  101. package/agents/master.md +0 -70
  102. package/agents/researcher.md +0 -21
  103. package/agents/security-auditor.md +0 -20
  104. package/agents/test-engineer.md +0 -20
  105. package/agents/web-performance-auditor.md +0 -19
  106. package/commands/council.md +0 -24
  107. package/commands/doctor.md +0 -19
  108. package/commands/ponytail-audit.md +0 -7
  109. package/commands/ponytail-debt.md +0 -14
  110. package/commands/report.md +0 -13
  111. package/scripts/harness-report.ps1 +0 -695
  112. package/scripts/panic/panic.ts +0 -240
  113. package/skills/code-review-and-quality/SKILL.md +0 -396
  114. package/skills/incremental-implementation/SKILL.md +0 -249
  115. package/skills/swarm-orchestration/SKILL.md +0 -54
@@ -4,7 +4,7 @@ This directory is the local, self-contained skill layer. Upstream material was i
4
4
 
5
5
  | Source | Revision inspected (pinned) | Used for |
6
6
  |--------|------------------------------|----------|
7
- | `DietrichGebert/ponytail` (v4.9.0) | `356918eba965ee1eac64bd3a7f0dd02108350de5` | `code-simplification` (report-only review/audit modes); the lean ladder is integrated into `AGENTS.md` |
7
+ | `DietrichGebert/ponytail` (v4.9.0) | `356918eba965ee1eac64bd3a7f0dd02108350de5` | `code-simplification` (explicit behavior-preserving editing workflow) |
8
8
  | `addyosmani/agent-skills` | `6ca0cd7db39b41b1c37e26d335c507ee92382c6d` | Active local workflow skills listed below |
9
9
  | `mattpocock/skills` | `3cca18b368ae95cdbdebbff572ccafa662551015` | `grilling`, `writing-for-agents`, and `creative-writing` (modes from `writing-fragments` / `writing-beats` / `writing-shape`) |
10
10
 
@@ -15,12 +15,12 @@ Transformations applied:
15
15
  - Frontmatter normalized to OpenCode V2 (`name`, `description`, optional `metadata`). Low-frequency / collision-prone skills are marked `metadata.opencode.autoinvoke: false` (explicit-only).
16
16
  - All `../../references/...` links rewritten to `../_shared/references/...`.
17
17
  - Harness adaptations: `$ARGUMENTS` references are command-template aware; upstream scripts, adapters, plugins, hooks, and repo-specific policy files are not runtime dependencies.
18
- - Ponytail adaptations: no plugin hooks, mode tracker, MCP/server code, adapter manifests, config/env default-mode machinery, or benchmark scoreboard. The always-on ladder lives in `AGENTS.md`; only report-only complexity workflows are active here.
19
- - `swarm-orchestration` is local work, not upstream-derived; left unchanged. `git-ceremony` is likewise local/adapted work: it is the harness's own fixed git ritual, adopted without a recorded upstream and owned locally, not tracked to a pinned revision. Its worktree section absorbed the former standalone `worktree` skill on <DATE>.
20
- - Mattpocock adaptations: ported as model-invoked local skills; upstream `disable-model-invocation` mapped to the harness explicit-only marker `metadata: {"opencode/autoinvoke": false}`; `grilling` invoked directly as a model-invoked skill (its former `/grill` wrapper command was retired <DATE>); `CLAUDE.md` references normalized to `AGENTS.md`; generic sub-agent references mapped to harness helpers (`explore`, lead-spawned children). Upstream OpenAI agent adapters and plugin packaging are not adopted. The `SKILL-MECHANICS.md` sibling reference is retained as disclosed reference.
18
+ - Ponytail adaptations: no plugin hooks, mode tracker, server code, or benchmark scoreboard. Explicit simplification lives in `code-simplification`.
19
+ - Orchestration is owned by `~/.config/opencode/agents/orchestrator.md`; the former orchestration, incremental-build, and review entrypoints were folded into role prompts and removed.
20
+ - Mattpocock adaptations use OpenCode's explicit-only marker where appropriate; `CLAUDE.md` references are normalized to `AGENTS.md`. The `SKILL-MECHANICS.md` sibling remains the mechanics reference.
21
21
 
22
- Active Addy-derived IDs: `api-and-interface-design`, `code-review-and-quality`, `code-simplification`, `debugging-and-error-recovery`, `frontend-ui-engineering`, `incremental-implementation`, `observability-and-instrumentation`, `performance-optimization`, `planning-and-task-breakdown`, `security-and-hardening`, `source-driven-development`, `spec-driven-development`, and `test-driven-development`.
22
+ Active Addy-derived IDs: `api-and-interface-design`, `code-simplification`, `debugging-and-error-recovery`, `frontend-ui-engineering`, `observability-and-instrumentation`, `performance-optimization`, `planning-and-task-breakdown`, `security-and-hardening`, `source-driven-development`, `spec-driven-development`, and `test-driven-development`.
23
23
 
24
- Active Mattpocock-derived IDs: `grilling`, `writing-for-agents`, and `creative-writing`. Local/adapted without a pinned upstream: `git-ceremony` (absorbed the former `worktree` skill <DATE>).
24
+ Active Mattpocock-derived IDs: `grilling`, `writing-for-agents`, and `creative-writing`. Local/adapted without a pinned upstream: `git-ceremony`.
25
25
 
26
- Runtime boundary: the OpenCode config uses a wildcard skill deny followed by exact allows for the active local IDs. Compatibility skill directories are not part of the local layer and are not required for any command or agent.
26
+ Runtime boundary: descriptions advertise routing conditions; exact procedures load only when matched. Commands use exact IDs for explicit-only workflows.
@@ -1,6 +1,6 @@
1
1
  # Definition of Done
2
2
 
3
- A standing, project-wide bar that every change must clear before it counts as done. Unlike acceptance criteria, which vary per task and answer "did we build the right thing?", the Definition of Done is the same every time and answers "is this finished to our standard?". Use it as the final gate in `planning-and-task-breakdown`, `incremental-implementation`, and the ship review.
3
+ A standing, project-wide bar that every change must clear before it counts as done. Unlike acceptance criteria, which vary per task and answer "did we build the right thing?", the Definition of Done is the same every time and answers "is this finished to our standard?". Use it as the final gate in `planning-and-task-breakdown`, `test-driven-development`, and the ship review.
4
4
 
5
5
  ## Definition of Done vs. Acceptance Criteria
6
6
 
@@ -32,7 +32,7 @@ Apply this to every change before declaring it done.
32
32
  - [ ] Changes are scoped to the task; no unrelated refactors snuck in
33
33
  - [ ] Linting and formatting pass
34
34
 
35
- The depth behind these items lives in `code-review-and-quality` (the five-axis review) and `code-simplification` (reducing complexity without changing behavior).
35
+ The depth behind these items lives in `code-simplification` (reducing complexity without changing behavior).
36
36
 
37
37
  ### Integration
38
38
  - [ ] Change works with the rest of the system, not just in isolation
@@ -7,8 +7,7 @@ grandchildren — and the multi-step pipeline stays user-driven: the user (or
7
7
  a slash command) drives define → plan → build → verify → review → ship and
8
8
  keeps the human checkpoints between steps. For a single request, the
9
9
  `master` agent leads and dispatches helpers but does not implement
10
- project code. The detailed playbook is
11
- `~/.config/opencode/skills/swarm-orchestration/SKILL.md`.
10
+ project code.
12
11
 
13
12
  ## Runtime boundaries
14
13
 
@@ -158,7 +158,7 @@ Never discover dependency lifecycle scripts by first executing an ordinary insta
158
158
 
159
159
  1. Bootstrap with dependency scripts disabled, or with a documented default-deny policy plus fail-closed enforcement.
160
160
  2. Inspect the exact script source and package version before approval.
161
- 3. Record the narrowest native allow/deny policy at the installation boundary and commit it.
161
+ 3. Persist the narrowest native allow/deny policy at the installation boundary; commit it only when separately requested.
162
162
  4. Run a clean frozen/immutable install with that policy and verify the required packages still build.
163
163
 
164
164
  **Point-in-time snapshot:** Package-manager defaults and command names change quickly. Verify this matrix against the pinned client's current official documentation before relying on it.
@@ -168,7 +168,7 @@ Never discover dependency lifecycle scripts by first executing an ordinary insta
168
168
  | npm without verified granular approvals | Bootstrap with `npm ci --ignore-scripts`, or persist `ignore-scripts=true` when project-wide blocking is intended. Keep scripts disabled or deliberately upgrade before allowing any reviewed dependency script. |
169
169
  | npm 11.18.x (verified on 11.18.0) | Unreviewed dependency scripts run with a warning by default. Enforce `strict-allow-scripts=true` before a normal install, then use the workspace-unaware `npm install-scripts ls` from the installation boundary; keep approvals version-pinned and denials name-wide. |
170
170
  | npm 12.x (verified on 12.0.1) | Unreviewed dependency scripts are skipped by default; `strict-allow-scripts=true` makes their presence fail the install before execution. Use the same `npm install-scripts` review and approval flow. |
171
- | pnpm 11+ | Use `pnpm approve-builds` and commit `allowBuilds` decisions; `strictDepBuilds` defaults to `true`, so unreviewed builds fail. |
171
+ | pnpm 11+ | Use `pnpm approve-builds` and persist `allowBuilds` decisions; `strictDepBuilds` defaults to `true`, so unreviewed builds fail. Commit only when separately requested. |
172
172
  | pnpm 10.26–10.x | Configure `allowBuilds` explicitly, or use `pnpm approve-builds` with the legacy `onlyBuiltDependencies` / `ignoredBuiltDependencies` lists. Set `strictDepBuilds: true`; its v10 default is `false`. |
173
173
  | pnpm 10.1–10.25 | `pnpm approve-builds` records the legacy lists; enable `strictDepBuilds` where supported (10.3+). |
174
174
  | Older or unknown pnpm | Bootstrap with `pnpm install --frozen-lockfile --ignore-scripts`. Keep scripts disabled unless the pinned version documents an enforceable policy. |
@@ -1,367 +1,14 @@
1
1
  ---
2
2
  name: api-and-interface-design
3
- description: Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.
3
+ description: "Designs or changes public APIs, module boundaries, request/response contracts, events, schemas, or cross-component interfaces where compatibility and failure semantics matter."
4
4
  ---
5
5
 
6
6
  # API and Interface Design
7
7
 
8
- ## Overview
8
+ 1. Identify consumers, producer, trust boundary, lifecycle, and compatibility promise.
9
+ 2. Define inputs, outputs, invariants, validation, errors, idempotency, ordering, pagination, and cancellation only where relevant.
10
+ 3. Make invalid states difficult to express. Prefer small stable contracts and existing repository conventions over new abstractions.
11
+ 4. For a breaking change, describe migration, coexistence window, and rollback. Do not silently reinterpret an existing field.
12
+ 5. Verify with contract tests or the narrowest producer/consumer integration.
9
13
 
10
- Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. This applies to REST APIs, GraphQL schemas, module boundaries, component props, and any surface where one piece of code talks to another.
11
-
12
- ## When to Use
13
-
14
- - Designing new API endpoints
15
- - Defining module boundaries or contracts between teams
16
- - Creating component prop interfaces
17
- - Establishing database schema that informs API shape
18
- - Changing existing public interfaces
19
-
20
- ## Core Principles
21
-
22
- ### Hyrum's Law
23
-
24
- > With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract.
25
-
26
- This means: every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it. Design implications:
27
-
28
- - **Be intentional about what you expose.** Every observable behavior is a potential commitment.
29
- - **Don't leak implementation details.** If users can observe it, they will depend on it.
30
- - **Plan for retirement at design time.** Define a compatibility window, migration path, and removal evidence before changing a public contract.
31
- - **Tests are not enough.** Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.
32
-
33
- ### The One-Version Rule
34
-
35
- Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork.
36
-
37
- ### 1. Contract First
38
-
39
- Define the interface before implementing it. The contract is the spec — implementation follows.
40
-
41
- ```typescript
42
- // Define the contract first
43
- interface TaskAPI {
44
- // Creates a task and returns the created task with server-generated fields
45
- createTask(input: CreateTaskInput): Promise<Task>;
46
-
47
- // Returns paginated tasks matching filters
48
- listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;
49
-
50
- // Returns a single task or throws NotFoundError
51
- getTask(id: string): Promise<Task>;
52
-
53
- // Partial update — only provided fields change
54
- updateTask(id: string, input: UpdateTaskInput): Promise<Task>;
55
-
56
- // Idempotent delete — succeeds even if already deleted
57
- deleteTask(id: string): Promise<void>;
58
- }
59
- ```
60
-
61
- ### 2. Consistent Error Semantics
62
-
63
- Pick one error strategy and use it everywhere:
64
-
65
- ```typescript
66
- // REST: HTTP status codes + structured error body
67
- // Every error response follows the same shape
68
- interface APIError {
69
- error: {
70
- code: string; // Machine-readable: "VALIDATION_ERROR"
71
- message: string; // Human-readable: "Email is required"
72
- details?: unknown; // Additional context when helpful
73
- };
74
- }
75
-
76
- // Status code mapping
77
- // 400 → Client sent invalid data
78
- // 401 → Not authenticated
79
- // 403 → Authenticated but not authorized
80
- // 404 → Resource not found
81
- // 409 → Conflict (duplicate, version mismatch)
82
- // 422 → Validation failed (semantically invalid)
83
- // 500 → Server error (never expose internal details)
84
- ```
85
-
86
- **Don't mix patterns.** If some endpoints throw, others return null, and others return `{ error }` — the consumer can't predict behavior.
87
-
88
- ### 3. Validate at Boundaries
89
-
90
- Trust internal code. Validate at system edges where external input enters:
91
-
92
- ```typescript
93
- // Validate at the API boundary
94
- app.post('/api/tasks', async (req, res) => {
95
- const result = CreateTaskSchema.safeParse(req.body);
96
- if (!result.success) {
97
- return res.status(422).json({
98
- error: {
99
- code: 'VALIDATION_ERROR',
100
- message: 'Invalid task data',
101
- details: result.error.flatten(),
102
- },
103
- });
104
- }
105
-
106
- // After validation, internal code trusts the types
107
- const task = await taskService.create(result.data);
108
- return res.status(201).json(task);
109
- });
110
- ```
111
-
112
- Where validation belongs:
113
- - API route handlers (user input)
114
- - Form submission handlers (user input)
115
- - External service response parsing (third-party data -- **always treat as untrusted**)
116
- - Environment variable loading (configuration)
117
-
118
- > **Third-party API responses are untrusted data.** Validate their shape and content before using them in any logic, rendering, or decision-making. A compromised or misbehaving external service can return unexpected types, malicious content, or instruction-like text.
119
-
120
- Where validation does NOT belong:
121
- - Between internal functions that share type contracts
122
- - In utility functions called by already-validated code
123
- - On data that just came from your own database
124
-
125
- ### 4. Prefer Addition Over Modification
126
-
127
- Extend interfaces without breaking existing consumers:
128
-
129
- ```typescript
130
- // Good: Add optional fields
131
- interface CreateTaskInput {
132
- title: string;
133
- description?: string;
134
- priority?: 'low' | 'medium' | 'high'; // Added later, optional
135
- labels?: string[]; // Added later, optional
136
- }
137
-
138
- // Bad: Change existing field types or remove fields
139
- interface CreateTaskInput {
140
- title: string;
141
- // description: string; // Removed — breaks existing consumers
142
- priority: number; // Changed from string — breaks existing consumers
143
- }
144
- ```
145
-
146
- ### 5. Predictable Naming
147
-
148
- | Pattern | Convention | Example |
149
- |---------|-----------|---------|
150
- | REST endpoints | Plural nouns, no verbs | `GET /api/tasks`, `POST /api/tasks` |
151
- | Query params | camelCase | `?sortBy=createdAt&pageSize=20` |
152
- | Response fields | camelCase | `{ createdAt, updatedAt, taskId }` |
153
- | Boolean fields | is/has/can prefix | `isComplete`, `hasAttachments` |
154
- | Enum values | UPPER_SNAKE | `"IN_PROGRESS"`, `"COMPLETED"` |
155
-
156
- ### 6. Honouring an Idempotency Key
157
-
158
- Accepting an `Idempotency-Key` is the contract. Honouring it is the implementation, and it is where the money is lost — a key the server accepts but handles carelessly is worse than no key at all, because the client now believes retrying is safe.
159
-
160
- **Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents:
161
-
162
- ```typescript
163
- crypto.randomUUID() // ✗ new key per attempt — every retry is a new charge
164
- `${userId}:${amount}` // ✗ two legitimate $50 charges collapse into one
165
- `${orderId}:${Date.now()}` // ✗ a timestamp is randomUUID() wearing a hat
166
-
167
- req.headers['idempotency-key'] // ✓ client generates once, reuses on retry
168
- `charge:v1:${orderId}` // ✓ derived from an immutable identifier
169
- ```
170
-
171
- The key comes from the client or the initiating event — never from the layer doing the retrying.
172
-
173
- **Claim atomically. A check followed by an act is a race:**
174
-
175
- ```typescript
176
- // ✗ TOCTOU: two concurrent retries both read "not seen", both charge
177
- if (!(await db.exists(key))) {
178
- await chargeCard(amount);
179
- await db.insert(key);
180
- }
181
-
182
- // ✓ let the unique constraint pick the winner
183
- try {
184
- await db.insert({ key, state: 'in_progress', requestHash });
185
- } catch (e) {
186
- if (isUniqueViolation(e)) return replayOrReject(key);
187
- throw;
188
- }
189
- const result = await chargeCard(amount);
190
- await db.update({ key, state: 'succeeded', response: result });
191
- ```
192
-
193
- The unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this.
194
-
195
- **Guard the payload.** Same key with a different body is a client bug, and must fail loudly rather than serving the first response to a second request:
196
-
197
- ```typescript
198
- if (existing.requestHash !== hash(req.body)) {
199
- return res.status(422).json({ error: 'idempotency key reused with a different payload' });
200
- }
201
- ```
202
-
203
- **Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms:
204
-
205
- | Strategy | Response | Use when |
206
- |---|---|---|
207
- | Reject | `409 Conflict` | Client can retry later; simplest and safest |
208
- | Wait | Block for the result, bounded | Caller needs it synchronously |
209
- | Return pending | `202` + status URL | Long-running effects |
210
-
211
- Never let the second caller through because the first "seems stuck". A stalled attempt whose fate is unknown is exactly when duplicating costs most.
212
-
213
- **Every call has three outcomes, not two: success, failure, and _unknown_.** A timeout tells you nothing about whether the effect applied. Record the intent *before* calling out, so a crash between the call and the response leaves evidence something must resolve later — rather than a silently retried charge.
214
-
215
- **Set retention from the longest retry chain**, not from disk cost. Keys must outlive every path that can re-deliver the same intent, including a dead-letter queue replayed a week later and any provider dispute window. A 24-hour key TTL behind a 7-day DLQ is a duplicate waiting to happen.
216
-
217
- ## REST API Patterns
218
-
219
- ### Resource Design
220
-
221
- ```
222
- GET /api/tasks → List tasks (with query params for filtering)
223
- POST /api/tasks → Create a task
224
- GET /api/tasks/:id → Get a single task
225
- PATCH /api/tasks/:id → Update a task (partial)
226
- DELETE /api/tasks/:id → Delete a task
227
-
228
- GET /api/tasks/:id/comments → List comments for a task (sub-resource)
229
- POST /api/tasks/:id/comments → Add a comment to a task
230
- ```
231
-
232
- ### Pagination
233
-
234
- Paginate list endpoints:
235
-
236
- ```typescript
237
- // Request
238
- GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc
239
-
240
- // Response
241
- {
242
- "data": [...],
243
- "pagination": {
244
- "page": 1,
245
- "pageSize": 20,
246
- "totalItems": 142,
247
- "totalPages": 8
248
- }
249
- }
250
- ```
251
-
252
- ### Filtering
253
-
254
- Use query parameters for filters:
255
-
256
- ```
257
- GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01
258
- ```
259
-
260
- ### Partial Updates (PATCH)
261
-
262
- Accept partial objects — only update what's provided:
263
-
264
- ```typescript
265
- // Only title changes, everything else preserved
266
- PATCH /api/tasks/123
267
- { "title": "Updated title" }
268
- ```
269
-
270
- ## TypeScript Interface Patterns
271
-
272
- ### Use Discriminated Unions for Variants
273
-
274
- ```typescript
275
- // Good: Each variant is explicit
276
- type TaskStatus =
277
- | { type: 'pending' }
278
- | { type: 'in_progress'; assignee: string; startedAt: Date }
279
- | { type: 'completed'; completedAt: Date; completedBy: string }
280
- | { type: 'cancelled'; reason: string; cancelledAt: Date };
281
-
282
- // Consumer gets type narrowing
283
- function getStatusLabel(status: TaskStatus): string {
284
- switch (status.type) {
285
- case 'pending': return 'Pending';
286
- case 'in_progress': return `In progress (${status.assignee})`;
287
- case 'completed': return `Done on ${status.completedAt}`;
288
- case 'cancelled': return `Cancelled: ${status.reason}`;
289
- }
290
- }
291
- ```
292
-
293
- ### Input/Output Separation
294
-
295
- ```typescript
296
- // Input: what the caller provides
297
- interface CreateTaskInput {
298
- title: string;
299
- description?: string;
300
- }
301
-
302
- // Output: what the system returns (includes server-generated fields)
303
- interface Task {
304
- id: string;
305
- title: string;
306
- description: string | null;
307
- createdAt: Date;
308
- updatedAt: Date;
309
- createdBy: string;
310
- }
311
- ```
312
-
313
- ### Use Branded Types for IDs
314
-
315
- ```typescript
316
- type TaskId = string & { readonly __brand: 'TaskId' };
317
- type UserId = string & { readonly __brand: 'UserId' };
318
-
319
- // Prevents accidentally passing a UserId where a TaskId is expected
320
- function getTask(id: TaskId): Promise<Task> { ... }
321
- ```
322
-
323
- ## Common Rationalizations
324
-
325
- | Rationalization | Reality |
326
- |---|---|
327
- | "We'll document the API later" | The types ARE the documentation. Define them first. |
328
- | "We don't need pagination for now" | You will the moment someone has 100+ items. Add it from the start. |
329
- | "PATCH is complicated, let's just use PUT" | PUT requires the full object every time. PATCH is what clients actually want. |
330
- | "We'll version the API when we need to" | Breaking changes without versioning break consumers. Design for extension from the start. |
331
- | "Nobody uses that undocumented behavior" | Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment. |
332
- | "We can just maintain two versions" | Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule. |
333
- | "Internal APIs don't need contracts" | Internal consumers are still consumers. Contracts prevent coupling and enable parallel work. |
334
- | "Accepting the Idempotency-Key header is enough" | The header is the contract; storing the key against the result is the implementation. A key you accept but don't honour tells the client retrying is safe when it isn't. |
335
- | "Our queue guarantees exactly-once delivery" | No queue does across a consumer crash — the broker's ack and your side effect are not in one transaction. Design for at-least-once with idempotent processing. |
336
- | "Duplicate requests are rare" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. |
337
-
338
- ## Red Flags
339
-
340
- - Endpoints that return different shapes depending on conditions
341
- - Inconsistent error formats across endpoints
342
- - Validation scattered throughout internal code instead of at boundaries
343
- - Breaking changes to existing fields (type changes, removals)
344
- - List endpoints without pagination
345
- - Verbs in REST URLs (`/api/createTask`, `/api/getUsers`)
346
- - Third-party API responses used without validation or sanitization
347
- - A `SELECT` for an idempotency key followed by an `INSERT` — that's a race, not a guard
348
- - An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt
349
- - The same key accepted with a different request body, silently returning the first response
350
- - A key retention window shorter than the longest path that can re-deliver the request
351
-
352
- ## Verification
353
-
354
- After designing an API:
355
-
356
- - [ ] Every endpoint has typed input and output schemas
357
- - [ ] Error responses follow a single consistent format
358
- - [ ] Validation happens at system boundaries only
359
- - [ ] List endpoints support pagination
360
- - [ ] New fields are additive and optional (backward compatible)
361
- - [ ] Naming follows consistent conventions across all endpoints
362
- - [ ] API documentation or types are committed alongside the implementation
363
- - [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry
364
- - [ ] The key is claimed in one atomic operation, guarded by a unique constraint
365
- - [ ] A reused key with a different payload fails loudly rather than replaying the wrong response
366
- - [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out
367
- - [ ] Key retention outlives the longest retry path, including dead-letter replay
14
+ Return the contract, examples for success and failure, compatibility impact, verification, and unresolved decisions. Keep transport-specific detail behind the contract and avoid speculative versioning or extensibility.