@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.
@@ -0,0 +1,521 @@
1
+ # Reasoning Kernel
2
+
3
+ Core reasoning loop executed **every turn** before any action.
4
+ Referenced from [patterns.md](patterns.md) and [AGENTS.md](../AGENTS.md).
5
+
6
+ **Use when:**
7
+ - Starting any task (this loop runs **every turn**, not optionally)
8
+ - Deciding which operational mode to apply
9
+ - Choosing which patterns to consult before acting
10
+ - Validating changes before confirming completion
11
+ - Understanding the full agent lifecycle from sense → learn
12
+
13
+ ---
14
+
15
+ ## Primary Loop
16
+
17
+ ```
18
+ ┌──────────────────────────────────────────────────────────────────────┐
19
+ │ │
20
+ │ ┌─────────┐ ┌─────────┐ │
21
+ │ │ 1 SENSE │◄───►│ 2 GKP │ ◄── inner loop: gather + compress │
22
+ │ └────┬────┘ └────┬────┘ until context is sufficient │
23
+ │ └───────┬───────┘ │
24
+ │ ▼ │
25
+ │ ┌──────────────┐ │
26
+ │ │ 3 DECIDE+ACT │ ← select mode, plan action, execute │
27
+ │ └──────┬───────┘ │
28
+ │ ▼ │
29
+ │ ┌───────────────────────┐ │
30
+ │ │ 4 CHALLENGE-TEST │ ◄── inner loop: validate + fix │
31
+ │ │ ├ validate-env.md │ until all gates pass or max 5 │
32
+ │ │ └ validate-n.md │ │
33
+ │ └──────────┬────────────┘ │
34
+ │ ▼ │
35
+ │ ┌──────────┐ │
36
+ │ │ 5 UPDATE │ ← commit state transitions │
37
+ │ └─────┬────┘ │
38
+ │ ▼ │
39
+ │ ┌──────────┐ │
40
+ │ │ 6 LEARN │ ← persist to patterns.md / patterns/ specs │
41
+ │ └────┬─────┘ │
42
+ │ ▼ │
43
+ │ ┌──────────┐ │
44
+ │ │ 7 REPORT │ ← store session log to docs/reports/ │
45
+ │ └──────────┘ (skip if trivial) │
46
+ │ │
47
+ └──────────────────────────────────────────────────────────────────────┘
48
+ ```
49
+
50
+ **Two inner loops exist:**
51
+ 1. **SENSE ↔ GKP** — cycle until relevant context is gathered and compressed
52
+ 2. **CHALLENGE-TEST → fix → retry** — cycle until gates pass (max 5 iterations)
53
+
54
+ ---
55
+
56
+ ## Transition Map
57
+
58
+ Explicit named edges define when to move between stages:
59
+
60
+ | From | To | Condition |
61
+ |------|----|-----------|
62
+ | SENSE | GKP | Context gaps remain |
63
+ | GKP | SENSE | New gaps discovered from reading |
64
+ | GKP | DECIDE+ACT | Context sufficient |
65
+ | DECIDE+ACT | CHALLENGE-TEST | Action executed |
66
+ | CHALLENGE-TEST | CHALLENGE-TEST | Micro-fix applied (no budget consumed) |
67
+ | CHALLENGE-TEST | FEEDBACK | Macro failure detected |
68
+ | FEEDBACK | SENSE | Correction vector generated |
69
+ | CHALLENGE-TEST | UPDATE | All gates pass |
70
+ | UPDATE | CHALLENGE-TEST | New issue discovered during update |
71
+ | UPDATE | LEARN | State committed cleanly |
72
+ | LEARN | REPORT | Patterns persisted |
73
+ | LEARN | DECIDE | Branch pruned — re-entering with lesson |
74
+ | REPORT | SENSE | Checkpoint clearage, ready for next task |
75
+ | REPORT | — | Session complete |
76
+
77
+ **Rule:** Never skip a stage or invent an edge not in this table. If stuck, escalate.
78
+
79
+ ---
80
+
81
+ ## Integrated Validation (CHALLENGE-TEST → fix → retry)
82
+
83
+ The CHALLENGE-TEST stage runs both validation prompts **in a loop** until all gates pass
84
+ or the iteration budget (5 macro iterations) is exhausted.
85
+
86
+ **Before routing any failure**, classify it:
87
+
88
+ ### Failure Classification
89
+
90
+ | Signal | Class | Action |
91
+ |--------|-------|--------|
92
+ | Type error on new code only | **Micro** | Fix in-place, no budget consumed |
93
+ | `print()` / `breakpoint()` left in | **Micro** | Remove, no budget consumed |
94
+ | Unused import after refactor | **Micro** | Remove, no budget consumed |
95
+ | Formatting / whitespace issue | **Micro** | Auto-format, no budget consumed |
96
+ | Test failure | **Macro** | → feedback.md, consumes 1 of 5 iterations |
97
+ | Layer violation | **Macro** | → feedback.md, consumes 1 of 5 iterations |
98
+ | Shape mismatch across modules | **Macro** | → feedback.md, consumes 1 of 5 iterations |
99
+ | Same micro-fix needed 3x | **→ Macro** | Upgrade: systemic issue |
100
+
101
+ **Calibration rule:** If fix is "supported" (evidence in error message) → Micro. If fix is "assumed" (needs diagnosis) → Macro.
102
+
103
+ **Micro budget:** Max 2 micro-fixes per gate before escalating to macro.
104
+ **Macro budget:** 5 total iterations (existing).
105
+
106
+ ```
107
+ CHALLENGE-TEST:
108
+
109
+ ├─► validate-env.md (Stage 1: NFRs)
110
+ │ └─► FAIL? → classify:
111
+ │ ├─ Micro → fix in-place, retry (no budget cost)
112
+ │ └─ Macro → feedback.md → patch → re-enter loop (-1 budget)
113
+
114
+ └─► validate-n.md (Stage 2: Neighbors)
115
+ └─► FAIL? → classify:
116
+ ├─ Micro → fix in-place, retry (no budget cost)
117
+ └─ Macro → feedback.md → patch → re-enter loop (-1 budget)
118
+
119
+ ALL PASS? ─► proceed to UPDATE
120
+ BUDGET EXHAUSTED? ─► Branch Pruning (see §Context Clearage Protocol)
121
+ ```
122
+
123
+ **Each macro iteration is 3-step:**
124
+ 1. **Check** — run gate (types, tests, layers, shapes)
125
+ 2. **Feedback** — on failure, diagnose via [feedback.md](feedback.md) and generate patch
126
+ 3. **Retry** — apply patch, re-enter the same gate check
127
+
128
+ **Micro-fixes are self-contained** — they do NOT route through feedback.md.
129
+
130
+ ---
131
+
132
+ ## Stage Details
133
+
134
+ ### 1. SENSE (+ context loop with GKP)
135
+
136
+ Extract current state and detect issues. **Cycle with GKP** until sufficient context is gathered.
137
+
138
+ ```
139
+ SENSE:
140
+ - Challenges: [what needs to be solved]
141
+ - Success criteria: [what must pass]
142
+ - Failure modes: [what could break]
143
+ - Detected issues: [code smells, type errors, test failures, layer breaks]
144
+ - Current mode: [Stabilize | Expand | Split]
145
+ - Context gaps: [what else do I need to read?]
146
+ ```
147
+
148
+ **SENSE ↔ GKP Inner Loop:**
149
+
150
+ ```
151
+ ┌─────────────────────────────────────────────────────────┐
152
+ │ SENSE │
153
+ │ Scan task, detect issues, identify context gaps │
154
+ │ │ │
155
+ │ Gaps remain? │
156
+ │ │ YES │ NO │
157
+ │ ▼ ▼ │
158
+ │ GKP: lookup patterns, Proceed to DECIDE+ACT │
159
+ │ read specs, compress with compressed context │
160
+ │ │ │
161
+ │ New gaps from reading? │
162
+ │ │ YES → back to SENSE │
163
+ │ │ NO → context sufficient │
164
+ └─────────────────────────────────────────────────────────┘
165
+ ```
166
+
167
+ **Compression:** After each GKP pass, compress gathered context into a tight summary.
168
+ Don't carry raw file contents forward — extract only relevant constraints, patterns, and risks.
169
+
170
+ ### 2. GKP (Generated Knowledge Pack)
171
+
172
+ Generate task-relevant context before any action.
173
+ **Route into [patterns.md](patterns.md) → then into the matching [patterns/](patterns/) spec.**
174
+
175
+ ```
176
+ GKP:
177
+ - DOMAIN: [project stack and runtime — filled during bootstrap]
178
+ - PATTERNS: [route from patterns.md to applicable spec — see lookup below]
179
+ - CONSTRAINTS:
180
+ • [layer architecture rules — from patterns.md]
181
+ • [typing requirements — from validate-env.md]
182
+ • [boundary contracts — from validate-n.md]
183
+ - RISKS:
184
+ • [what could break from this action]
185
+ • [cross-layer imports break modularity]
186
+ • [missing types cause runtime errors]
187
+ - KNOWN FIXES: [check patterns.md §Auto-Fixes table]
188
+ - DECISION CUES:
189
+ • Keywords: [domain-specific terms from glossary.md]
190
+ • Gates: [type_check_pass, tests_pass, layer_rules_pass]
191
+ • Blockers: [destructive_change, infinite_loop, architecture_violation]
192
+ ```
193
+
194
+ **Pattern Lookup & Routing (6 steps):**
195
+
196
+ ```
197
+ 1. READ patterns.md → scan "Use when" triggers for matching pattern IDs
198
+ 2. ROUTE to the spec file:
199
+ ┌──────────────────────────────────────────────────────────┐
200
+ │ P1–P11 (code) → patterns/code-patterns.md │
201
+ │ R1 (refactoring) → patterns/refactoring-workflow.md │
202
+ │ R2 (testing) → patterns/testing-guide.md │
203
+ │ R3 (API standards) → patterns/api-standards.md │
204
+ └──────────────────────────────────────────────────────────┘
205
+ 3. READ the spec section for implementation examples
206
+ 4. CHECK patterns.md §Common Errors for known pitfalls
207
+ 5. CHECK patterns.md §Auto-Fixes for applicable transforms
208
+ 6. COMPRESS: extract only the constraints + examples relevant to this task
209
+ ```
210
+
211
+ **Domain terms:** If any term is ambiguous, consult [glossary.md](glossary.md).
212
+
213
+ ---
214
+
215
+ ## Context Scope (Per-Stage Loading)
216
+
217
+ At each stage, load only the context relevant to that stage. Unload what isn't needed.
218
+
219
+ | Stage | Load | Skip | Budget Focus |
220
+ |-------|------|------|--------------|
221
+ | SENSE | workspace state, task description | patterns/, glossary | — |
222
+ | GKP | patterns.md → relevant spec | validate-*.md, feedback.md | Evidence 40–60% |
223
+ | DECIDE+ACT | GKP output (compressed) | raw pattern files | Instructions 10–20% |
224
+ | CHALLENGE-TEST | validate-env.md, validate-n.md | patterns/*.md | Verification 5–10% |
225
+ | FEEDBACK | feedback.md, failing file | everything else | Evidence 40–60% |
226
+ | LEARN | patterns.md, relevant spec | validate-*.md | Examples 0–30% |
227
+ | REPORT | session state only | all .agent-loop/ files | — |
228
+
229
+ **Budget Controller** (context allocation guideline):
230
+
231
+ | Component | Allocation |
232
+ |-----------|------------|
233
+ | Instructions & constraints | 10–20% |
234
+ | Evidence / references | 40–60% |
235
+ | Examples / demos | 0–30% |
236
+ | Verification checklist | 5–10% |
237
+
238
+ **Key rule:** After GKP compression, do NOT re-read the source files. Work from the compressed context.
239
+
240
+ ---
241
+
242
+ ### 3. DECIDE + ACT
243
+
244
+ Select operational mode **and** plan the concrete action in a single step.
245
+
246
+ **Mode Selection:**
247
+
248
+ | Mode | Trigger | Behavior |
249
+ |------|---------|----------|
250
+ | **INTACT-STABILIZE** | All gates pass, code working | Harden: add tests, improve types, document |
251
+ | **BROKEN-EXPAND** | Issues detected | Fix: apply minimal patches, expand outward |
252
+ | **OVERDENSE-SPLIT** | Complexity too high | Decompose: split files, extract modules |
253
+
254
+ **Selection Logic:**
255
+
256
+ ```python
257
+ def select_mode(state):
258
+ if state.all_gates_pass and state.complexity < THRESHOLD:
259
+ return Mode.INTACT_STABILIZE
260
+ elif state.has_issues:
261
+ return Mode.BROKEN_EXPAND
262
+ elif state.complexity >= THRESHOLD or state.file_size > MAX_LINES:
263
+ return Mode.OVERDENSE_SPLIT
264
+ ```
265
+
266
+ **Action Plan** (produced alongside mode):
267
+
268
+ ```
269
+ ACTION PLAN:
270
+ - Core: [main logic change — what files, what functions]
271
+ - Shell: [interface/boundary change — new params, new exports]
272
+ - Neighbor: [affected modules — who calls this, who breaks]
273
+ - Pattern: [which pattern ID(s) apply — e.g., P1+P10, R1]
274
+ - Risk: [what could go wrong — rollback strategy]
275
+ ```
276
+
277
+ The agent executes the plan immediately after producing it.
278
+ Do **not** output a plan and wait — DECIDE and ACT are one phase.
279
+
280
+ ### 4. CHALLENGE-TEST
281
+
282
+ See [Integrated Validation](#integrated-validation-challenge-test--fix--retry) above.
283
+ Run gates in a loop until all pass or budget (5 iterations) is exhausted.
284
+
285
+ ### 5. UPDATE
286
+
287
+ Commit state transitions after all gates pass:
288
+
289
+ ```
290
+ UPDATE:
291
+ - Files changed: [list]
292
+ - State before → after: [what shifted]
293
+ - Reports generated: [stored in docs/reports/ if applicable]
294
+ - Patterns affected: [any new or modified pattern IDs]
295
+ ```
296
+
297
+ If UPDATE reveals that the change introduced a new issue not caught by gates
298
+ (e.g., a documentation reference is now stale), **cycle back** to CHALLENGE-TEST
299
+ for one more validation pass.
300
+
301
+ ### 6. LEARN
302
+
303
+ Persist lessons from this cycle. Route to the correct target per [feedback.md §Persisting to Spec Files](feedback.md):
304
+
305
+ ```
306
+ LEARN:
307
+ - Quick fix? → Add row to patterns.md table (Auto-Fixes, Common Errors, Heuristics)
308
+ - Deep pattern? → Add/update section in patterns/{spec}.md + update patterns.md index
309
+ - New term? → Add to glossary.md with [→ ID] cross-reference
310
+ - Heuristic? → One-line do-more/do-less for next cycle
311
+ ```
312
+
313
+ ### 7. REPORT (Session Log)
314
+
315
+ After completing a non-trivial task, persist a session summary to `docs/reports/`.
316
+
317
+ **When to write a report:**
318
+
319
+ | Condition | Report Required | Format |
320
+ |-----------|----------------|--------|
321
+ | Multi-file refactoring | Yes | Full report |
322
+ | New feature / module added | Yes | Full report |
323
+ | Bug fix with root cause analysis | Yes | Abbreviated (scope + fix + verification) |
324
+ | Architecture or pattern change | Yes | Full report + patterns.md update |
325
+ | Single-file cosmetic fix | No | — |
326
+ | Documentation-only update | No | — |
327
+
328
+ **Report structure:**
329
+
330
+ ```markdown
331
+ # {Short Description}
332
+
333
+ **Date:** YYYY-MM-DD
334
+ **Status:** Complete
335
+
336
+ ## 1. Summary
337
+ {What was done and why — 1–3 sentences}
338
+
339
+ ## 2. Scope
340
+ {Modules/files affected, pattern IDs referenced}
341
+
342
+ ## 3. Changes
343
+ {Itemized list of what changed: code, config, docs, patterns}
344
+
345
+ ## 4. Verification
346
+ - [ ] Type check pass
347
+ - [ ] Tests pass
348
+ - [ ] Layer rules: no cross-layer violations
349
+ {Gate results: PASS/FAIL + iteration count}
350
+
351
+ ## 5. Artifacts
352
+ {Links to: diffs, logs, diagrams in docs/reports/artifacts/}
353
+
354
+ ## 6. Learned Patterns
355
+ {What was persisted to patterns.md / patterns/ specs / glossary}
356
+ ```
357
+
358
+ **File placement:**
359
+ - Report: `docs/reports/YYYY-MM-DD-{short-description}.md`
360
+ - Supporting artifacts: `docs/reports/artifacts/`
361
+ - Naming: date-prefixed, lowercase-kebab-case, no `_v1`/`_new` suffixes
362
+
363
+ ---
364
+
365
+ ## Context Clearage Protocol
366
+
367
+ Explicit lifecycle management for accumulated context. Prevents stale data from degrading reasoning quality in long sessions.
368
+
369
+ ### Strategy 1: State Collapse (on success)
370
+
371
+ **Trigger:** LEARN stage completes successfully → entering REPORT.
372
+
373
+ **Process** (RCG-based — Referential Context Graph):
374
+
375
+ ```
376
+ 1. EXTRACT — Identify entities, facts, rules from current session
377
+ 2. RELATE — Establish edges between nodes (defines, supports, conflicts)
378
+ 3. ANCHOR — Mark task root + outcome as entry points
379
+ 4. PRUNE — Remove disconnected or stale nodes
380
+ 5. VALIDATE — Check for conflicts or missing links
381
+ ```
382
+
383
+ **Compression:** Use **Abstractive** strategy — synthesize a session summary with attribution.
384
+
385
+ **Output:** Checkpoint Summary (see template below) → discard raw history → restart SENSE with only the summary as input.
386
+
387
+ ### Strategy 2: Branch Pruning (on repeated failure)
388
+
389
+ **Trigger:** Same error 3× OR macro retry budget exhausted without resolution.
390
+
391
+ **Process:**
392
+ 1. Identify the failed approach ("rotten branch")
393
+ 2. Revert file changes from that branch (not unrelated passing changes)
394
+ 3. Record lesson: `"Approach: [X] | Failure: [Y] | Constraint: do NOT retry X"`
395
+ 4. Restart at DECIDE with lesson injected as hard constraint
396
+
397
+ **Compression:** Use **Extractive** strategy — keep failure evidence sentences faithfully.
398
+
399
+ **Guard:** If the same branch has already been pruned once → escalate instead of pruning again.
400
+
401
+ **Detail:** See [feedback.md §Branch Pruning Protocol](feedback.md).
402
+
403
+ ### Strategy 3: Scoped Loading (per-stage)
404
+
405
+ See [§Context Scope table](#context-scope-per-stage-loading) above. At each stage, only load the files listed in the "Load" column and skip everything in the "Skip" column.
406
+
407
+ ### Checkpoint Summary Template
408
+
409
+ Produced by State Collapse at the end of each successful cycle:
410
+
411
+ ```
412
+ CHECKPOINT SUMMARY
413
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
414
+ Task: [original task description]
415
+ Status: [complete | partial | blocked]
416
+ Changes: [files modified/created — bullet list]
417
+ Gates: [PASS (iteration N) | FAIL (escalated)]
418
+ Lessons: [patterns persisted, if any]
419
+ Next: [ready for new task | continue with {remaining work}]
420
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
421
+ ```
422
+
423
+ This summary becomes the **sole input** to the next SENSE stage after clearage.
424
+
425
+ ---
426
+
427
+ ## Output Schema
428
+
429
+ When executing a step, output this exact structure:
430
+
431
+ ```
432
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
433
+ SENSE (1-3 lines)
434
+ [current state, detected issues, context gaps]
435
+
436
+ MODE
437
+ [INTACT-STABILIZE | BROKEN-EXPAND | OVERDENSE-SPLIT]
438
+
439
+ GKP
440
+ - Patterns: [IDs consulted, spec files read]
441
+ - Constraints: [list key constraints]
442
+ - Risks: [list key risks]
443
+
444
+ ACTION (DECIDE+ACT)
445
+ - Core: [main logic change]
446
+ - Shell: [interface/boundary change]
447
+ - Neighbor: [affected modules]
448
+ - Pattern: [which IDs apply]
449
+
450
+ CHALLENGE-TEST (iteration N/5)
451
+ [PASS | FAIL] — [reason/gate violated]
452
+ [If FAIL: patch applied, retrying...]
453
+
454
+ UPDATE
455
+ [what changed, state transitions]
456
+ (If new issues found → one more CHALLENGE-TEST pass)
457
+
458
+ LEARN
459
+ [quick fix → patterns.md table | deep → patterns/{spec}.md]
460
+ [one-line do-more/do-less heuristic]
461
+
462
+ REPORT (if non-trivial)
463
+ [docs/reports/YYYY-MM-DD-{slug}.md created — or "skipped (trivial)"]
464
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
465
+ ```
466
+
467
+ ---
468
+
469
+ ## Internal Critic (Pre-Action Check)
470
+
471
+ Before finalizing any action, validate:
472
+
473
+ ```
474
+ CRITIC CHECK:
475
+ - Legality: Any cross-layer violation? [YES → revise]
476
+ - Viability: Will this break existing functionality? [YES → revise]
477
+ - Overload: Is complexity increasing without decomposition? [YES → split first]
478
+ - Regression: Could this reintroduce a fixed issue? [YES → add guard]
479
+
480
+ If any fail → revise action once, then output revised version.
481
+ Do not output critic reasoning; only output final decision.
482
+ ```
483
+
484
+ ---
485
+
486
+ ## Guardrails (Never Violate)
487
+
488
+ - Never modify test files to make tests pass — fix the source code
489
+ - Never remove type hints to fix type errors — add correct types
490
+ - Never change public API without explicit approval
491
+ - Never import across incompatible layers (e.g., infra importing domain)
492
+ - Never merge/absorb across incompatible boundaries without decomposing first
493
+
494
+ **If uncertain about impact:** Treat as risky, prefer isolated fix.
495
+
496
+ ---
497
+
498
+ ## Termination Conditions
499
+
500
+ | Condition | Action |
501
+ |-----------|--------|
502
+ | All gates pass | SUCCESS — complete |
503
+ | Max iterations (5) | TIMEOUT — report partial |
504
+ | Same error 3+ times | BRANCH PRUNE — revert, inject lesson, re-enter DECIDE (see §Context Clearage) |
505
+ | Branch already pruned | ESCALATE — same approach failed twice, stop and report |
506
+ | Destructive change needed | BLOCKED — require confirmation |
507
+ | Architecture violation | HARD STOP — cannot proceed |
508
+
509
+ ---
510
+
511
+ ## Related Documents
512
+
513
+ | Document | Purpose |
514
+ |----------|---------|
515
+ | [patterns.md](patterns.md) | Pattern registry — GKP reads from here, LEARN writes here |
516
+ | [patterns/](patterns/) | Detailed specs — GKP routes into these for implementation examples |
517
+ | [glossary.md](glossary.md) | Domain terminology — resolves ambiguous terms in SENSE/GKP |
518
+ | [feedback.md](feedback.md) | Behavioral patches — invoked by CHALLENGE-TEST on FAIL |
519
+ | [validate-env.md](validate-env.md) | Stage 1 NFRs — run in CHALLENGE-TEST loop |
520
+ | [validate-n.md](validate-n.md) | Stage 2 neighbors — run in CHALLENGE-TEST loop |
521
+ | [AGENTS.md](../AGENTS.md) | Main entrypoint — references this file |