@oleksandr.rudnychenko/sync_loop 0.2.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.
package/src/server.js ADDED
@@ -0,0 +1,208 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod";
4
+ import { readFileSync } from "node:fs";
5
+ import { join, dirname } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { init } from "./init.js";
8
+
9
+ const __dirname = dirname(fileURLToPath(import.meta.url));
10
+ const TEMPLATE_DIR = join(__dirname, "..", "template");
11
+
12
+ function readTemplate(relativePath) {
13
+ return readFileSync(join(TEMPLATE_DIR, relativePath), "utf-8");
14
+ }
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Doc registry — each entry maps to a template file
18
+ // ---------------------------------------------------------------------------
19
+ const DOCS = {
20
+ "overview": {
21
+ path: ".agent-loop/README.md",
22
+ name: "Protocol Overview",
23
+ description: "SyncLoop file index and framework overview",
24
+ },
25
+ "agents-md": {
26
+ path: "AGENTS.md",
27
+ name: "AGENTS.md Template",
28
+ description: "Root entrypoint template for AI agents — project identity, protocol, guardrails",
29
+ },
30
+ "protocol-summary": {
31
+ path: "protocol-summary.md",
32
+ name: "Protocol Summary",
33
+ description: "Condensed 7-stage reasoning loop overview (~50 lines)",
34
+ },
35
+ "reasoning-kernel": {
36
+ path: ".agent-loop/reasoning-kernel.md",
37
+ name: "Reasoning Kernel",
38
+ description: "Core 7-stage loop, transition map, context clearage, micro/macro classification",
39
+ },
40
+ "feedback": {
41
+ path: ".agent-loop/feedback.md",
42
+ name: "Feedback Loop",
43
+ description: "Failure diagnosis, patch protocol, micro-loop, branch pruning, learning persistence",
44
+ },
45
+ "validate-env": {
46
+ path: ".agent-loop/validate-env.md",
47
+ name: "Validate Environment (Stage 1)",
48
+ description: "NFR gates: type safety, tests, layer integrity, complexity, debug hygiene",
49
+ },
50
+ "validate-n": {
51
+ path: ".agent-loop/validate-n.md",
52
+ name: "Validate Neighbors (Stage 2)",
53
+ description: "Shape compatibility, boundary integrity, bridge contracts",
54
+ },
55
+ "patterns": {
56
+ path: ".agent-loop/patterns.md",
57
+ name: "Pattern Registry",
58
+ description: "Pattern routing index, architecture baseline, learned patterns, pruning records",
59
+ },
60
+ "glossary": {
61
+ path: ".agent-loop/glossary.md",
62
+ name: "Domain Glossary",
63
+ description: "Canonical terminology, naming rules, deprecated aliases",
64
+ },
65
+ "code-patterns": {
66
+ path: ".agent-loop/patterns/code-patterns.md",
67
+ name: "Code Patterns (P1–P11)",
68
+ description: "Port/adapter, domain modules, tasks, routes, DI, config, types, error handling",
69
+ },
70
+ "testing-guide": {
71
+ path: ".agent-loop/patterns/testing-guide.md",
72
+ name: "Testing Guide (R2)",
73
+ description: "Test pyramid, fixtures, factories, mocks, parametrized tests, naming",
74
+ },
75
+ "refactoring-workflow": {
76
+ path: ".agent-loop/patterns/refactoring-workflow.md",
77
+ name: "Refactoring Workflow (R1)",
78
+ description: "4-phase checklist for safe file moves and module restructuring",
79
+ },
80
+ "api-standards": {
81
+ path: ".agent-loop/patterns/api-standards.md",
82
+ name: "API Standards (R3)",
83
+ description: "Boundary contracts, typed models, error envelopes, versioning strategy",
84
+ },
85
+ };
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // Server
89
+ // ---------------------------------------------------------------------------
90
+ const server = new McpServer({
91
+ name: "syncloop",
92
+ version: "0.1.0",
93
+ });
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // Resources — each protocol doc exposed as a readable resource
97
+ // ---------------------------------------------------------------------------
98
+ for (const [id, doc] of Object.entries(DOCS)) {
99
+ server.resource(
100
+ doc.name,
101
+ `syncloop://docs/${id}`,
102
+ async (uri) => ({
103
+ contents: [{
104
+ uri: uri.href,
105
+ mimeType: "text/markdown",
106
+ text: readTemplate(doc.path),
107
+ }],
108
+ }),
109
+ );
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Tools
114
+ // ---------------------------------------------------------------------------
115
+
116
+ const StackSchema = z.object({
117
+ name: z.string().describe("Stack/layer name (e.g. 'backend', 'frontend', 'auth-service', 'worker')"),
118
+ languages: z.array(z.string()).describe("Programming languages used (e.g. ['TypeScript', 'Python'])"),
119
+ frameworks: z.array(z.string()).describe("Frameworks used (e.g. ['Next.js', 'Tailwind'] or ['FastAPI', 'SQLAlchemy'])"),
120
+ testRunner: z.string().optional().describe("Test runner command (e.g. 'jest', 'pytest', 'vitest')"),
121
+ typeChecker: z.string().optional().describe("Type checker command (e.g. 'tsc --noEmit', 'mypy', 'pyright')"),
122
+ linter: z.string().optional().describe("Lint/format command (e.g. 'eslint .', 'ruff check')"),
123
+ packageManager: z.string().optional().describe("Package manager (e.g. 'npm', 'pnpm', 'poetry')"),
124
+ path: z.string().optional().describe("Root directory of this stack relative to project root (e.g. 'apps/web', 'services/auth'). Omit for monolith."),
125
+ });
126
+
127
+ server.tool(
128
+ "init",
129
+ "Scaffold SyncLoop protocol files into a project. Before calling this tool, the agent MUST ask the user to confirm the SyncLoop target platform (`copilot`, `cursor`, `claude`, or `all`) unless the user already explicitly provided it. Then scan the codebase to detect all stacks (frontend, backend, services, etc.) and pass them as the stacks array. After scaffolding, the agent MUST scan again and update the generated files with actual project data.",
130
+ {
131
+ projectPath: z.string().describe("Absolute path to the project root directory"),
132
+ target: z.enum(["copilot", "cursor", "claude", "all"]).describe(
133
+ "SyncLoop target platform (must be user-confirmed before tool call): copilot (.github/instructions/), cursor (.cursor/rules/), claude (.claude/rules/ + CLAUDE.md), or all",
134
+ ),
135
+ stacks: z.array(StackSchema).min(1).describe(
136
+ "Project stacks — one entry per layer/service. Fullstack app: [{name:'backend',...},{name:'frontend',...}]. Monolith: [{name:'app',...}]. Microservices: one per service.",
137
+ ),
138
+ },
139
+ async ({ projectPath, target, stacks }) => {
140
+ try {
141
+ const results = init(projectPath, target, stacks);
142
+ const bootstrapPrompt = readTemplate("bootstrap-prompt.md");
143
+
144
+ const stackSummary = stacks.map(s => [
145
+ `\n### ${s.name}${s.path ? ` (${s.path})` : ""}`,
146
+ `- Languages: ${s.languages.join(", ")}`,
147
+ `- Frameworks: ${s.frameworks.join(", ")}`,
148
+ s.testRunner ? `- Test runner: ${s.testRunner}` : null,
149
+ s.typeChecker ? `- Type checker: ${s.typeChecker}` : null,
150
+ s.linter ? `- Linter: ${s.linter}` : null,
151
+ s.packageManager ? `- Package manager: ${s.packageManager}` : null,
152
+ ].filter(Boolean).join("\n")).join("\n");
153
+
154
+ return {
155
+ content: [
156
+ { type: "text", text: `SyncLoop initialized for ${target}:\n\n${results.join("\n")}` },
157
+ { type: "text", text: `\n---\n\n## Detected stacks\n${stackSummary}` },
158
+ { type: "text", text: `\n---\n\n**IMPORTANT: Now scan the codebase and wire the generated SyncLoop files to this project.**\n\n${bootstrapPrompt}` },
159
+ ],
160
+ };
161
+ } catch (err) {
162
+ return {
163
+ content: [{ type: "text", text: `Error initializing SyncLoop: ${err.message}` }],
164
+ isError: true,
165
+ };
166
+ }
167
+ },
168
+ );
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // Prompts
172
+ // ---------------------------------------------------------------------------
173
+
174
+ server.prompt(
175
+ "bootstrap",
176
+ "Bootstrap prompt — wire SyncLoop protocol to an existing project by scanning its codebase",
177
+ async () => ({
178
+ description: "Scan the project codebase and wire SyncLoop protocol references to real project structure",
179
+ messages: [{
180
+ role: "user",
181
+ content: {
182
+ type: "text",
183
+ text: readTemplate("bootstrap-prompt.md"),
184
+ },
185
+ }],
186
+ }),
187
+ );
188
+
189
+ server.prompt(
190
+ "protocol",
191
+ "SyncLoop reasoning protocol summary — inject as system context for any AI coding task",
192
+ async () => ({
193
+ description: "The SyncLoop 7-stage reasoning protocol for self-correcting agent behavior",
194
+ messages: [{
195
+ role: "user",
196
+ content: {
197
+ type: "text",
198
+ text: readTemplate("protocol-summary.md"),
199
+ },
200
+ }],
201
+ }),
202
+ );
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Connect transport
206
+ // ---------------------------------------------------------------------------
207
+ const transport = new StdioServerTransport();
208
+ await server.connect(transport);
@@ -0,0 +1,75 @@
1
+ # Agent Loop Prompts
2
+
3
+ Modular prompts for AI coding agents to run a reusable, self-correcting delivery loop.
4
+
5
+ Project bootstrap workflow and setup prompt are documented in [../README.md](../README.md).
6
+
7
+ ## Overview
8
+
9
+ The framework uses a **7-stage protocol** with **2-stage validation**, **feedback integration**, and **session persistence**:
10
+
11
+ ```
12
+ ┌─────────┐ ┌─────────┐
13
+ │ 1 SENSE │◄───►│ 2 GKP │ ◄── inner loop: gather + compress
14
+ └────┬────┘ └────┬────┘
15
+ └───────┬───────┘
16
+
17
+ ┌──────────────┐
18
+ │ 3 DECIDE+ACT │ ← select mode, plan, execute
19
+ └──────┬───────┘
20
+
21
+ ┌───────────────────────┐
22
+ │ 4 CHALLENGE-TEST │ ◄── inner loop: validate + fix (max 5)
23
+ │ ├ Stage 1: ENV │ ← NFRs (types, tests, layers)
24
+ │ └ Stage 2: NEIGHBOR │ ← Shapes, boundaries, bridges
25
+ └──────────┬────────────┘
26
+ │ On FAIL → FEEDBACK → patch → retry
27
+
28
+ ┌──────────┐
29
+ │ 5 UPDATE │ ← commit state transitions
30
+ └─────┬────┘
31
+
32
+ ┌──────────┐
33
+ │ 6 LEARN │ ← persist to patterns.md / patterns/ specs
34
+ └────┬─────┘
35
+
36
+ ┌──────────┐
37
+ │ 7 REPORT │ ← store session log to docs/reports/
38
+ └──────────┘ (skip if trivial)
39
+ ```
40
+
41
+ ## Prompt Files
42
+
43
+ | File | Purpose | When to Use |
44
+ |------|---------|-------------|
45
+ | [reasoning-kernel.md](reasoning-kernel.md) | Core 7-stage loop with integrated validation | Every turn — master orchestrator |
46
+ | [patterns.md](patterns.md) | Pattern registry + learned fixes | GKP phase (read), LEARN phase (write) |
47
+ | [patterns/](patterns/) | Detailed implementation specs | GKP routes here for examples |
48
+ | [glossary.md](glossary.md) | Canonical domain terminology | Naming, resolving ambiguous terms |
49
+ | [validate-env.md](validate-env.md) | Stage 1: NFRs (types, tests, layers, complexity) | CHALLENGE-TEST Stage 1 |
50
+ | [validate-n.md](validate-n.md) | Stage 2: Neighbors (shapes, boundaries, bridges) | CHALLENGE-TEST Stage 2 |
51
+ | [feedback.md](feedback.md) | Behavioral patches, learning, spec persistence | On validation failure; LEARN phase routing |
52
+
53
+ ## Pattern Specs (patterns/)
54
+
55
+ | Spec File | Pattern IDs | Content |
56
+ |-----------|-------------|---------|
57
+ | [code-patterns.md](patterns/code-patterns.md) | P1–P11 | Ports, modules, tasks, routes, DI, config, types, errors |
58
+ | [testing-guide.md](patterns/testing-guide.md) | R2 | Test patterns, fixtures, mocks, naming, 3-layer strategy |
59
+ | [refactoring-workflow.md](patterns/refactoring-workflow.md) | R1 | 4-phase refactoring checklist |
60
+ | [api-standards.md](patterns/api-standards.md) | R3 | Boundary contract standards, endpoint workflow |
61
+
62
+ ## Validation Structure
63
+
64
+ Each gate follows: **CHECK → FEEDBACK (if failed) → RETRY**
65
+
66
+ | Stage | File | Scope |
67
+ |-------|------|-------|
68
+ | Stage 1: ENV | [validate-env.md](validate-env.md) | Non-functional requirements |
69
+ | Stage 2: NEIGHBOR | [validate-n.md](validate-n.md) | Compatibility and integration surfaces |
70
+ | Failure flow | [feedback.md](feedback.md) | Diagnosis, patching, escalation |
71
+
72
+ ## Entrypoint
73
+
74
+ The root entrypoint is [AGENTS.md](../AGENTS.md).
75
+ It provides architecture rules, operational modes, and routing into this folder.
@@ -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 |