@oleksandr.rudnychenko/sync_loop 0.2.5 → 0.3.2

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 (54) hide show
  1. package/README.md +25 -4
  2. package/bin/cli.js +3 -128
  3. package/bin/cli.ts +171 -0
  4. package/dist/bin/cli.d.ts +15 -0
  5. package/dist/bin/cli.js +137 -0
  6. package/dist/bin/cli.js.map +1 -0
  7. package/dist/src/init.d.ts +24 -0
  8. package/dist/src/init.js +410 -0
  9. package/dist/src/init.js.map +1 -0
  10. package/dist/src/server.d.ts +13 -0
  11. package/dist/src/server.js +265 -0
  12. package/dist/src/server.js.map +1 -0
  13. package/dist/src/template/.agent-loop/README.md +75 -0
  14. package/dist/src/template/.agent-loop/feedback.md +395 -0
  15. package/dist/src/template/.agent-loop/glossary.md +113 -0
  16. package/dist/src/template/.agent-loop/patterns/api-standards.md +132 -0
  17. package/dist/src/template/.agent-loop/patterns/code-patterns.md +300 -0
  18. package/dist/src/template/.agent-loop/patterns/refactoring-workflow.md +114 -0
  19. package/dist/src/template/.agent-loop/patterns/testing-guide.md +258 -0
  20. package/dist/src/template/.agent-loop/patterns.md +256 -0
  21. package/dist/src/template/.agent-loop/reasoning-kernel.md +521 -0
  22. package/dist/src/template/.agent-loop/validate-env.md +332 -0
  23. package/dist/src/template/.agent-loop/validate-n.md +321 -0
  24. package/dist/src/template/AGENTS.md +157 -0
  25. package/dist/src/template/README.md +144 -0
  26. package/dist/src/template/bootstrap-prompt.md +37 -0
  27. package/dist/src/template/protocol-summary.md +54 -0
  28. package/dist/src/template/wiring/agents-claude.md +203 -0
  29. package/dist/src/template/wiring/agents-github.md +211 -0
  30. package/dist/src/template/wiring/api-standards.md +15 -0
  31. package/dist/src/template/wiring/code-patterns.md +15 -0
  32. package/dist/src/template/wiring/feedback.md +18 -0
  33. package/dist/src/template/wiring/glossary.md +11 -0
  34. package/dist/src/template/wiring/patterns.md +18 -0
  35. package/dist/src/template/wiring/reasoning-kernel.md +18 -0
  36. package/dist/src/template/wiring/refactoring-workflow.md +15 -0
  37. package/dist/src/template/wiring/testing-guide.md +15 -0
  38. package/dist/src/template/wiring/validate-env.md +17 -0
  39. package/dist/src/template/wiring/validate-n.md +17 -0
  40. package/package.json +48 -34
  41. package/src/template/wiring/agents-claude.md +203 -0
  42. package/src/template/wiring/agents-github.md +211 -0
  43. package/src/template/wiring/api-standards.md +15 -0
  44. package/src/template/wiring/code-patterns.md +15 -0
  45. package/src/template/wiring/feedback.md +18 -0
  46. package/src/template/wiring/glossary.md +11 -0
  47. package/src/template/wiring/patterns.md +18 -0
  48. package/src/template/wiring/reasoning-kernel.md +18 -0
  49. package/src/template/wiring/refactoring-workflow.md +15 -0
  50. package/src/template/wiring/testing-guide.md +15 -0
  51. package/src/template/wiring/validate-env.md +17 -0
  52. package/src/template/wiring/validate-n.md +17 -0
  53. package/src/init.js +0 -569
  54. package/src/server.js +0 -292
@@ -0,0 +1,395 @@
1
+ # Feedback Loop (Failure Diagnosis & Patch Protocol)
2
+
3
+ Behavioral patches and learning from failures. Invoked by [reasoning-kernel.md](reasoning-kernel.md) when validation fails.
4
+ Referenced from [patterns.md](patterns.md). Writes learned fixes to patterns.md tables (quick) and [patterns/](patterns/) specs (deep).
5
+
6
+ **Use when:**
7
+ - A validation gate fails (types, tests, layers) → diagnose + patch + retry
8
+ - `validate-env.md` or `validate-n.md` returns FAIL
9
+ - User provides explicit score or correction on agent output
10
+ - Same error recurs 2+ times (escalation trigger)
11
+ - A task completes successfully (learning phase → persist pattern)
12
+ - Refactoring changes imports/docs and tests must re-verify
13
+
14
+ ---
15
+
16
+ ## Failure Types
17
+
18
+ | Type | Detection Signal | Required Response |
19
+ |------|------------------|-------------------|
20
+ | **Gate Failure** | Stage 1 or 2 returns FAIL | Patch root cause, rerun same gate |
21
+ | **Shape Mismatch** | Signature/data contract breaks | Align producer/consumer contracts |
22
+ | **Boundary Drift** | Unintended API/export changes | Restore or document intentional change |
23
+ | **User Misalignment** | User indicates wrong behavior/scope | Re-scope and patch to requested intent |
24
+ | **Low Coverage** | Coverage report below threshold | Add tests, retry |
25
+ | **Bad Naming** | Files with `v1`, `new`, `old` suffixes | Rename to canonical form |
26
+ | **Doc Change** | Documentation/import updates | Run tests to verify examples |
27
+ | **Infinite Loop** | Same error 3+ times | Branch prune first, then escalate |
28
+
29
+ ---
30
+
31
+ ## Micro-Loop Protocol
32
+
33
+ Surface-level fixes that are resolved **within CHALLENGE-TEST** without consuming the macro retry budget.
34
+ Does NOT route through the patch contract below — self-contained.
35
+
36
+ **Micro Signals:**
37
+
38
+ | Signal | Fix | Budget Impact |
39
+ |--------|-----|---------------|
40
+ | Missing return type on new code | Add annotation based on body analysis | None |
41
+ | `print()` / `breakpoint()` left in | Remove or convert to logging | None |
42
+ | Unused import after refactor | Remove import line | None |
43
+ | Formatting / whitespace issue | Auto-format | None |
44
+
45
+ **Rules:**
46
+ - Max **2 micro-fixes per gate** before escalating to macro
47
+ - Same micro-fix needed **3×** → reclassify as macro (systemic issue)
48
+ - Micro-fixes do NOT generate a patch contract — they are applied directly
49
+
50
+ **Calibration** (from Verification Protocol):
51
+ - Fix is **"Supported"** (evidence directly in error message) → Micro
52
+ - Fix is **"Assumed"** (needs root cause diagnosis) → Macro
53
+
54
+ ---
55
+
56
+ ## Feedback Input Formats
57
+
58
+ ### From User
59
+
60
+ ```
61
+ FEEDBACK ON LAST STEP
62
+
63
+ Score (0-5): [rating]
64
+ Misalignment: [what went wrong]
65
+ Good: [what worked]
66
+ New constraint: [rule to enforce]
67
+ ```
68
+
69
+ ### From Gate Failure
70
+
71
+ ```
72
+ GATE FAILURE
73
+
74
+ Gate: [type_check | tests | layer_rules | complexity | debug]
75
+ Error: [specific error message]
76
+ File: [affected file]
77
+ Line: [line number]
78
+ ```
79
+
80
+ ### From Refactoring/Documentation Changes
81
+
82
+ ```
83
+ REFACTORING APPLIED
84
+
85
+ Changes:
86
+ ├─► Files moved: [list]
87
+ ├─► Imports updated: [count]
88
+ ├─► Documentation updated: [files]
89
+ └─► Status: [incomplete]
90
+
91
+ Required Next Steps:
92
+ 1. Run type checker
93
+ 2. Run test suite
94
+ 3. Verify documentation examples
95
+ 4. Check for orphaned imports
96
+
97
+ Reason: Files/imports changed → MUST verify no breakage.
98
+ ```
99
+
100
+ ---
101
+
102
+ ## Patch Contract
103
+
104
+ When feedback is received, output explicit behavioral changes:
105
+
106
+ ```
107
+ FEEDBACK PATCH
108
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
109
+ Failure: [what failed]
110
+ Root cause: [why it failed — not the symptom]
111
+ Affected scope: [files/modules impacted]
112
+ Minimal correction: [smallest fix that resolves root cause]
113
+ Safety checks: [what to verify after patch]
114
+ Retry target gate: [which gate to re-run]
115
+ Behavioral change: [one sentence: what changes next turn]
116
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
117
+ ```
118
+
119
+ Patch must satisfy:
120
+ - minimal surface area
121
+ - preserved public contracts (unless approved)
122
+ - explicit retry target
123
+
124
+ ---
125
+
126
+ ## Learning Mechanism
127
+
128
+ After each successful cycle, persist the lesson into the **Learned Patterns** section of [patterns.md](patterns.md).
129
+ Three target tables exist — route each lesson to the correct one:
130
+
131
+ ### 1. Log Common Errors → patterns.md §Common Errors
132
+
133
+ Add to the **Common Errors** table in `patterns.md`:
134
+
135
+ ```markdown
136
+ | Symptom | Why It Happens | Prevention Heuristic |
137
+ |---------|----------------|----------------------|
138
+ | Missing return type | Signature drift | Add return types immediately on creation |
139
+ | Fixture not found | conftest.py not in path | Check test fixture scope |
140
+ ```
141
+
142
+ ### 2. Log Auto-Fixes → patterns.md §Auto-Fixes
143
+
144
+ Add to the **Auto-Fixes** table in `patterns.md`:
145
+
146
+ ```markdown
147
+ | Trigger | Root Cause | Minimal Safe Fix | Auto-Apply |
148
+ |---------|------------|------------------|------------|
149
+ | Missing return type | `def get_name():` → no annotation | Add `-> str:` based on body | ✅ |
150
+ | Unused import | Import left after refactor | Remove unused import line | ✅ |
151
+ ```
152
+
153
+ ### 3. Extract Heuristics → patterns.md §Heuristics
154
+
155
+ Add to the **Heuristics** table in `patterns.md`:
156
+
157
+ ```markdown
158
+ | Do More | Do Less |
159
+ |---------|---------|
160
+ | Check return types before type check | Assume function has correct type |
161
+ | Verify neighbor compatibility first | Change interfaces without checking |
162
+ ```
163
+
164
+ ### Pattern Update Protocol (Quick Fixes → patterns.md tables)
165
+
166
+ ```
167
+ On successful fix:
168
+ 1. Identify pattern category (error, auto-fix, heuristic)
169
+ 2. Check if pattern already exists in patterns.md
170
+ 3. If new → append to appropriate table
171
+ 4. If existing → update confidence/weight
172
+ ```
173
+
174
+ ---
175
+
176
+ ## Persisting to Spec Files (patterns/)
177
+
178
+ Quick-fix rows land in the patterns.md tables (above). **Deeper patterns** — new code examples,
179
+ expanded approaches, new domain rules — must be persisted into the dedicated spec files under `patterns/`.
180
+
181
+ ### When to Write to a Spec (vs. Index-Only)
182
+
183
+ | Signal | Action | Target |
184
+ |--------|--------|--------|
185
+ | One-liner fix (import path, type annotation) | Row in patterns.md table only | `patterns.md §Learned Patterns` |
186
+ | New code example or convention (>5 lines) | Add section to existing spec | `patterns/{spec}.md` |
187
+ | New pattern ID created (P#, D#, R#) | Add entry in patterns.md + section in spec | Both |
188
+ | Existing spec section outdated by code change | Update spec section in-place | `patterns/{spec}.md` |
189
+ | Pattern grows complex enough to need its own spec | Create new spec file | `patterns/{new-spec}.md` |
190
+
191
+ ### Routing: Which Spec File Gets the Update
192
+
193
+ ```
194
+ Classify the pattern → route to target file:
195
+
196
+ Core code (ports, modules, tasks, routes, DI, config, types, errors)
197
+ → patterns/code-patterns.md [P1–P11]
198
+
199
+ Testing fixtures, mocks, factories, parametrize, naming
200
+ → patterns/testing-guide.md [R2]
201
+
202
+ File moves, import updates, refactor checklist
203
+ → patterns/refactoring-workflow.md [R1]
204
+
205
+ API docs, boundary contracts, schema generation
206
+ → patterns/api-standards.md [R3]
207
+ ```
208
+
209
+ ### Spec File Template (for new files)
210
+
211
+ When creating a **new** spec file in `patterns/`:
212
+
213
+ ```markdown
214
+ # {Pattern Name}
215
+
216
+ {One-line description of what this spec covers}.
217
+ Referenced from [patterns.md](../patterns.md).
218
+
219
+ ---
220
+
221
+ ## {Section 1}
222
+
223
+ {Explanation + code example}
224
+
225
+ ---
226
+
227
+ ## {Section N}
228
+ ```
229
+
230
+ **Required conventions** (must match existing specs):
231
+ 1. **H1 title** — matches the pattern name in patterns.md
232
+ 2. **Backlink** — `Referenced from [patterns.md](../patterns.md).` on line 2-3
233
+ 3. **`---` separators** between sections
234
+ 4. **Code blocks** with language tags for all examples
235
+ 5. Format: runnable examples > abstract descriptions
236
+
237
+ ### Dual-Write Flow (Index + Spec)
238
+
239
+ When a pattern is substantial enough for a spec file:
240
+
241
+ ```
242
+ ┌──────────────────────────────────┐
243
+ │ LEARN phase │
244
+ │ (after successful fix) │
245
+ └───────────────┬──────────────────┘
246
+
247
+ Is it a quick fix?
248
+ (one-liner, import path,
249
+ type annotation)
250
+
251
+ ┌──────┴──────┐
252
+ │ YES │ NO
253
+ ▼ ▼
254
+ ┌──────────────┐ ┌──────────────────────────────────┐
255
+ │ patterns.md │ │ 1. Add/update patterns/{spec}.md │
256
+ │ table row │ │ (code, explanation, examples) │
257
+ │ only │ │ │
258
+ └──────────────┘ │ 2. Update patterns.md index: │
259
+ │ - "Use when" triggers │
260
+ │ - Spec table link │
261
+ │ - Source file references │
262
+ │ │
263
+ │ 3. Cross-ref from glossary.md │
264
+ │ if new domain terms introduced │
265
+ └──────────────────────────────────┘
266
+ ```
267
+
268
+ ---
269
+
270
+ ## Infinite Loop Detection
271
+
272
+ Track error occurrences per cycle:
273
+
274
+ ```
275
+ error_counts = {}
276
+
277
+ for each gate failure:
278
+ key = f"{gate}:{file}:{error_signature}"
279
+ error_counts[key] += 1
280
+
281
+ if error_counts[key] >= 3:
282
+ → BRANCH PRUNE (see §Branch Pruning Protocol above)
283
+ → If already pruned this approach: ESCALATE
284
+ ```
285
+
286
+ The default action on repeated failure is now **prune first, escalate second**.
287
+
288
+ ---
289
+
290
+ ## Escalation Protocol
291
+
292
+ When feedback loop cannot resolve:
293
+
294
+ ```
295
+ ESCALATION REQUIRED
296
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
297
+ Issue: [description]
298
+ Attempted fixes: [list of attempts]
299
+ Reason for escalation: [infinite loop | architecture blocker | unclear requirement]
300
+
301
+ Recommended action:
302
+ - [specific action needed]
303
+ - [alternative approaches if any]
304
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
305
+ ```
306
+
307
+ Escalate when:
308
+ 1. Retry budget exhausted (iteration > 5)
309
+ 2. Same gate fails repeatedly without meaningful delta
310
+ 3. Fix requires destructive or unapproved contract change
311
+
312
+ ---
313
+
314
+ ## State Artifacts
315
+
316
+ Learned patterns are persisted in [patterns.md](patterns.md) and route to [patterns/](patterns/) specs.
317
+ Session summaries go to `docs/reports/`.
318
+
319
+ ```
320
+ .agent-loop/
321
+ ├── patterns.md # INDEX — pattern registry + learned fixes + pruning records
322
+ │ ├── Pattern Registry
323
+ │ │ ├── Core Code (P1–P11) → patterns/code-patterns.md
324
+ │ │ └── Process (R1–R3) → patterns/refactoring-workflow.md,
325
+ │ │ patterns/testing-guide.md,
326
+ │ │ patterns/api-standards.md
327
+ │ ├── Architecture Baseline
328
+ │ ├── Artifact Placement
329
+ │ └── Learned Patterns ← FEEDBACK WRITES HERE
330
+ │ ├── Auto-Fixes table
331
+ │ ├── Heuristics table
332
+ │ ├── Common Errors table
333
+ │ └── Pruning Records table ← BRANCH PRUNING WRITES HERE
334
+
335
+ ├── patterns/ # SPECS — detailed approaches & examples
336
+ │ ├── code-patterns.md # P1–P11 with examples
337
+ │ ├── testing-guide.md # R2 test patterns
338
+ │ ├── refactoring-workflow.md # R1 4-phase checklist
339
+ │ └── api-standards.md # R3 API/boundary standards
340
+
341
+ ├── glossary.md # Domain terminology (cross-refs → D#/P#)
342
+ ├── feedback.md # THIS FILE — behavioral patches + micro-loop + branch pruning
343
+ ├── reasoning-kernel.md # Core 7-stage loop + context clearage + transitions
344
+ ├── validate-env.md # Stage 1: NFR validation (micro/macro annotated)
345
+ └── validate-n.md # Stage 2: neighbor validation
346
+ ```
347
+
348
+ ---
349
+
350
+ ## Integration with Agent Loop
351
+
352
+ ```
353
+ ┌─────────────────────────────────────────────────────────────┐
354
+ │ FEEDBACK INTEGRATION │
355
+ ├─────────────────────────────────────────────────────────────┤
356
+ │ │
357
+ │ reasoning-kernel.md │
358
+ │ │ │
359
+ │ ▼ │
360
+ │ CHALLENGE-TEST │
361
+ │ │ │
362
+ │ validate-env.md ─┬─► PASS ─┐ │
363
+ │ └─► FAIL ─┤ │
364
+ │ validate-n.md ───┬─► PASS ─┤ │
365
+ │ └─► FAIL ─┤ │
366
+ │ ▼ │
367
+ │ feedback.md (THIS) │
368
+ │ │ │
369
+ │ Diagnose error │
370
+ │ │ │
371
+ │ Apply patch │
372
+ │ │ │
373
+ │ Retry action │
374
+ │ │ │
375
+ │ ┌─► PASS → learn → persist: │
376
+ │ │ ├─ quick fix → patterns.md table │
377
+ │ │ └─ deep pattern → patterns/{spec}.md │
378
+ │ └─► FAIL (3x) → escalate │
379
+ │ │
380
+ └─────────────────────────────────────────────────────────────┘
381
+ ```
382
+
383
+ ---
384
+
385
+ ## Related Documents
386
+
387
+ | Document | Purpose |
388
+ |----------|---------|
389
+ | [patterns.md](patterns.md) | Pattern registry — learned fixes written here |
390
+ | [reasoning-kernel.md](reasoning-kernel.md) | 7-stage loop that invokes feedback on FAIL |
391
+ | [validate-env.md](validate-env.md) | Stage 1 NFRs — gate failures feed into this file |
392
+ | [validate-n.md](validate-n.md) | Stage 2 neighbors — shape breaks feed into this file |
393
+ | [glossary.md](glossary.md) | Domain terms — naming feedback references glossary |
394
+ | [patterns/testing-guide.md](patterns/testing-guide.md) | R2: test patterns for coverage feedback |
395
+ | [patterns/refactoring-workflow.md](patterns/refactoring-workflow.md) | R1: refactoring checklist for doc-change feedback |
@@ -0,0 +1,113 @@
1
+ # Domain Glossary
2
+
3
+ Canonical terminology for the project codebase. All code, comments, docs, and agent reasoning must use these terms.
4
+ Referenced from [patterns.md](patterns.md). Cross-references use `[→ ID]` pattern IDs from the registry.
5
+
6
+ **Use when:**
7
+ - Naming a new variable, field, class, or parameter
8
+ - Writing comments, docstrings, or documentation
9
+ - Interpreting domain concepts in user requests or specs
10
+ - Resolving ambiguity between similar terms
11
+ - Checking deprecated aliases before using a term in new code
12
+
13
+ ---
14
+
15
+ ## Architecture Terms
16
+
17
+ {Fill in during bootstrap with project-specific layer terms.}
18
+
19
+ | Term | Canonical Symbol | Definition |
20
+ |------|------------------|------------|
21
+ | **service** | `*Service` [→ P2, P10] | Business orchestration unit — contains domain logic and data access. No transport concerns. |
22
+ | **route** | `*_router` / `*_controller` [→ P5] | Transport boundary — handles requests, delegates to services. No business logic. |
23
+ | **adapter** | `*Adapter` [→ P1] | Concrete implementation of an infrastructure port/interface. |
24
+ | **config** | `Settings` / `Config` [→ P11] | Centralized configuration — single env source with startup validation. |
25
+
26
+ {Add project-specific architecture terms here.}
27
+
28
+ ---
29
+
30
+ ## Domain Objects
31
+
32
+ {Fill in during bootstrap with actual domain models.}
33
+
34
+ | Term | Canonical Symbol | Model / Location | Description |
35
+ |------|------------------|------------------|-------------|
36
+ | {entity} | `{ClassName}` | `{models/file.py}` | {what it represents} |
37
+
38
+ ---
39
+
40
+ ## Agent Loop Lifecycle Terms
41
+
42
+ | Term | Meaning |
43
+ |------|---------|
44
+ | **SENSE** | State detection and requirement extraction |
45
+ | **GKP** | Generated Knowledge Pack — context retrieval + compression |
46
+ | **DECIDE+ACT** | Mode selection and immediate implementation |
47
+ | **CHALLENGE-TEST** | Validation loop with retry-driven patching |
48
+ | **UPDATE** | State transition persistence |
49
+ | **LEARN** | Persisting reusable corrections and heuristics |
50
+ | **REPORT** | Writing non-trivial session outcomes |
51
+
52
+ ---
53
+
54
+ ## Naming Rules
55
+
56
+ 1. **One concept → one canonical term** — never use synonyms in code
57
+ 2. **Prefer explicit nouns** over abbreviations (`service` not `svc`)
58
+ 3. **Keep boundary model names stable** once published to consumers
59
+ 4. **Record deprecated aliases** before removal (see table below)
60
+ 5. **Suffix conventions** (adapt to project):
61
+ - `*Service` for business logic
62
+ - `*Router` / `*Controller` for transport handlers
63
+ - `*Adapter` for infrastructure implementations
64
+ - `*Port` / `*Interface` for infrastructure abstractions
65
+
66
+ ---
67
+
68
+ ## Deprecated Alias Table
69
+
70
+ | Deprecated | Canonical | Notes |
71
+ |------------|-----------|-------|
72
+ | `svc` | `service` | Abbreviated form |
73
+ | `handler` | `service` | Avoid ambiguity with route handlers |
74
+
75
+ {Add project-specific deprecated aliases here.}
76
+
77
+ ---
78
+
79
+ ## Data Flow Diagram
80
+
81
+ {Fill in during bootstrap with actual project data flow.}
82
+
83
+ ```
84
+ ┌──────────────────────────────┐
85
+ │ USER INPUT │
86
+ ├──────────────────────────────┤
87
+ │ Request → Transport Layer │
88
+ └─────────────┬────────────────┘
89
+
90
+
91
+ ┌──────────────────────────────┐
92
+ │ SERVICE LAYER │
93
+ ├──────────────────────────────┤
94
+ │ Business Logic → Data Access│
95
+ └─────────────┬────────────────┘
96
+
97
+
98
+ ┌──────────────────────────────┐
99
+ │ OUTPUT │
100
+ ├──────────────────────────────┤
101
+ │ Response → Side Effects │
102
+ └──────────────────────────────┘
103
+ ```
104
+
105
+ ---
106
+
107
+ ## Related Documents
108
+
109
+ | Document | Purpose |
110
+ |----------|---------|
111
+ | [reasoning-kernel.md](reasoning-kernel.md) | Where lifecycle terms are executed |
112
+ | [patterns.md](patterns.md) | Where pattern IDs are defined and routed |
113
+ | [../AGENTS.md](../AGENTS.md) | Main entrypoint with full architecture reference |
@@ -0,0 +1,132 @@
1
+ # API Standards (R3)
2
+
3
+ Standards for consistent boundary contracts: HTTP routes, request/response models, error envelopes, and documentation.
4
+ Referenced from [../patterns.md](../patterns.md).
5
+
6
+ ---
7
+
8
+ ## Requirements
9
+
10
+ 1. **Typed Models**: Every route must define explicit request and response models. No raw `dict` or untyped `JSONResponse` for success cases.
11
+
12
+ 2. **Docstrings**: Every route handler must have a docstring with summary and description.
13
+
14
+ 3. **Tags & Metadata**: Group routes with semantic tags. Provide `summary` / `description` in path operations.
15
+
16
+ 4. **Spec Generation**: After modifying routes, regenerate API documentation (OpenAPI spec, Swagger, or equivalent).
17
+
18
+ ---
19
+
20
+ ## Workflow for New Routes
21
+
22
+ ```
23
+ 1. Define Request/Response models in the module's models file
24
+ 2. Implement the route handler using those models
25
+ 3. Register the router in the app entrypoint with appropriate tags
26
+ 4. Run spec generation script
27
+ 5. Verify generated docs match expectations
28
+ ```
29
+
30
+ ### Example Route
31
+
32
+ ```python
33
+ # models.py — typed boundary contracts
34
+ @dataclass
35
+ class CreateEntityRequest:
36
+ name: str
37
+ entity_type: str
38
+ metadata: dict[str, Any] = field(default_factory=dict)
39
+
40
+ @dataclass
41
+ class EntityResponse:
42
+ id: str
43
+ name: str
44
+ entity_type: str
45
+ status: str
46
+ created_at: str
47
+
48
+ # routes.py — thin transport layer
49
+ @router.post("/entities", response_model=EntityResponse)
50
+ def create_entity(
51
+ data: CreateEntityRequest,
52
+ service: EntityService = Depends(get_service),
53
+ ) -> EntityResponse:
54
+ """Create a new entity for processing.
55
+
56
+ Validates input, delegates to service, returns created entity.
57
+ """
58
+ result = service.create(data)
59
+ return EntityResponse(
60
+ id=result.id,
61
+ name=result.name,
62
+ entity_type=result.entity_type,
63
+ status=result.status,
64
+ created_at=result.created_at.isoformat(),
65
+ )
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Error Envelope
71
+
72
+ All error responses must follow a consistent structure:
73
+
74
+ ```python
75
+ # Standard error response
76
+ @dataclass
77
+ class ErrorResponse:
78
+ error: str # Machine-readable error code
79
+ message: str # Human-readable description
80
+ details: dict = field(default_factory=dict) # Optional context
81
+
82
+ # Usage at route boundary
83
+ @router.get("/entities/{entity_id}")
84
+ def get_entity(entity_id: str, service = Depends(get_service)):
85
+ try:
86
+ return service.get(entity_id)
87
+ except NotFoundError as exc:
88
+ raise HTTPException(status_code=404, detail=str(exc))
89
+ except ValidationError as exc:
90
+ raise HTTPException(status_code=400, detail=str(exc))
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Documentation Rules
96
+
97
+ | Rule | Detail |
98
+ |------|--------|
99
+ | Document each endpoint intent | What does it do, who calls it |
100
+ | Define validation constraints | Required fields, ranges, formats |
101
+ | Include success + error examples | Show typical 200, 400, 404, 500 |
102
+ | Keep schema docs in sync | Regenerate after every route change |
103
+
104
+ ---
105
+
106
+ ## Change Safety
107
+
108
+ | Change Type | Requirements |
109
+ |-------------|-------------|
110
+ | **Additive** (new field, new endpoint) | Must be backward-compatible; new fields optional with defaults |
111
+ | **Modification** (rename field, change type) | Requires migration notes + caller updates + NEIGHBOR validation |
112
+ | **Removal** (delete field, remove endpoint) | Requires deprecation period, caller audit, explicit approval |
113
+
114
+ ---
115
+
116
+ ## Versioning Strategy
117
+
118
+ - Prefer additive changes over breaking changes
119
+ - When breaking changes are unavoidable:
120
+ 1. Document the change in migration notes
121
+ 2. Update all known consumers
122
+ 3. Run NEIGHBOR validation to check boundary contracts
123
+ 4. Consider a version prefix if multiple consumers exist
124
+
125
+ ---
126
+
127
+ ## Related Documents
128
+
129
+ | Document | Purpose |
130
+ |----------|---------|
131
+ | [../validate-n.md](../validate-n.md) | Contract compatibility checks (NEIGHBOR) |
132
+ | [code-patterns.md](code-patterns.md) | P5 (Transport Route), P6 (Typed Models) |