loopforge 2.11.0 → 3.0.0

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 (166) hide show
  1. package/README.md +145 -128
  2. package/dist/canonical-event-writer.d.ts +20 -0
  3. package/dist/canonical-event-writer.d.ts.map +1 -0
  4. package/dist/canonical-event-writer.js +131 -0
  5. package/dist/canonical-event-writer.js.map +1 -0
  6. package/dist/canonical-state.d.ts +20 -16
  7. package/dist/canonical-state.d.ts.map +1 -1
  8. package/dist/canonical-state.js +170 -61
  9. package/dist/canonical-state.js.map +1 -1
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +11 -10
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cognitive-governance.d.ts +48 -0
  14. package/dist/cognitive-governance.d.ts.map +1 -0
  15. package/dist/cognitive-governance.js +226 -0
  16. package/dist/cognitive-governance.js.map +1 -0
  17. package/dist/compiler-subgoals.d.ts +7 -0
  18. package/dist/compiler-subgoals.d.ts.map +1 -0
  19. package/dist/compiler-subgoals.js +93 -0
  20. package/dist/compiler-subgoals.js.map +1 -0
  21. package/dist/derive-id.d.ts +12 -0
  22. package/dist/derive-id.d.ts.map +1 -0
  23. package/dist/derive-id.js +31 -0
  24. package/dist/derive-id.js.map +1 -0
  25. package/dist/evidence-provider.d.ts +23 -21
  26. package/dist/evidence-provider.d.ts.map +1 -1
  27. package/dist/evidence-provider.js +34 -74
  28. package/dist/evidence-provider.js.map +1 -1
  29. package/dist/generate-schema.js +90 -2
  30. package/dist/generate-schema.js.map +1 -1
  31. package/dist/index.d.ts +22 -19
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +15 -16
  34. package/dist/index.js.map +1 -1
  35. package/dist/loop-compiler.d.ts +1 -1
  36. package/dist/loop-compiler.d.ts.map +1 -1
  37. package/dist/loop-compiler.js +250 -337
  38. package/dist/loop-compiler.js.map +1 -1
  39. package/dist/loop-extras-parser.d.ts +2 -2
  40. package/dist/loop-extras-parser.d.ts.map +1 -1
  41. package/dist/loop-extras-parser.js +2 -2
  42. package/dist/loop-extras-parser.js.map +1 -1
  43. package/dist/loop-store.d.ts +20 -58
  44. package/dist/loop-store.d.ts.map +1 -1
  45. package/dist/loop-store.js +232 -309
  46. package/dist/loop-store.js.map +1 -1
  47. package/dist/mcp/server.d.ts +3 -3
  48. package/dist/mcp/server.d.ts.map +1 -1
  49. package/dist/mcp/server.js +83 -13
  50. package/dist/mcp/server.js.map +1 -1
  51. package/dist/mcp/session-projection.d.ts +5 -0
  52. package/dist/mcp/session-projection.d.ts.map +1 -0
  53. package/dist/mcp/session-projection.js +18 -0
  54. package/dist/mcp/session-projection.js.map +1 -0
  55. package/dist/mcp/session-queue.d.ts +3 -0
  56. package/dist/mcp/session-queue.d.ts.map +1 -0
  57. package/dist/mcp/session-queue.js +18 -0
  58. package/dist/mcp/session-queue.js.map +1 -0
  59. package/dist/mcp/session-types.d.ts +72 -0
  60. package/dist/mcp/session-types.d.ts.map +1 -0
  61. package/dist/mcp/session-types.js +2 -0
  62. package/dist/mcp/session-types.js.map +1 -0
  63. package/dist/mcp/session.d.ts +49 -93
  64. package/dist/mcp/session.d.ts.map +1 -1
  65. package/dist/mcp/session.js +544 -245
  66. package/dist/mcp/session.js.map +1 -1
  67. package/dist/mcp/tools.d.ts +26 -1
  68. package/dist/mcp/tools.d.ts.map +1 -1
  69. package/dist/mcp/tools.js +399 -274
  70. package/dist/mcp/tools.js.map +1 -1
  71. package/dist/policy-metrics.d.ts +17 -1
  72. package/dist/policy-metrics.d.ts.map +1 -1
  73. package/dist/policy-metrics.js +164 -1
  74. package/dist/policy-metrics.js.map +1 -1
  75. package/dist/policy.d.ts +34 -18
  76. package/dist/policy.d.ts.map +1 -1
  77. package/dist/policy.js +113 -18
  78. package/dist/policy.js.map +1 -1
  79. package/dist/prompt-assembler.d.ts +5 -3
  80. package/dist/prompt-assembler.d.ts.map +1 -1
  81. package/dist/prompt-assembler.js +126 -77
  82. package/dist/prompt-assembler.js.map +1 -1
  83. package/dist/prompt-policy.d.ts +8 -1
  84. package/dist/prompt-policy.d.ts.map +1 -1
  85. package/dist/prompt-policy.js +26 -8
  86. package/dist/prompt-policy.js.map +1 -1
  87. package/dist/protocol.d.ts +232 -192
  88. package/dist/protocol.d.ts.map +1 -1
  89. package/dist/protocol.js +15 -100
  90. package/dist/protocol.js.map +1 -1
  91. package/dist/replay.d.ts +11 -3
  92. package/dist/replay.d.ts.map +1 -1
  93. package/dist/replay.js +51 -14
  94. package/dist/replay.js.map +1 -1
  95. package/dist/round-commit-store.d.ts +12 -0
  96. package/dist/round-commit-store.d.ts.map +1 -0
  97. package/dist/round-commit-store.js +13 -0
  98. package/dist/round-commit-store.js.map +1 -0
  99. package/dist/round-coordinator.d.ts +25 -18
  100. package/dist/round-coordinator.d.ts.map +1 -1
  101. package/dist/round-coordinator.js +83 -71
  102. package/dist/round-coordinator.js.map +1 -1
  103. package/dist/round-driver.d.ts +14 -10
  104. package/dist/round-driver.d.ts.map +1 -1
  105. package/dist/round-driver.js +9 -13
  106. package/dist/round-driver.js.map +1 -1
  107. package/dist/round-gate.d.ts +31 -0
  108. package/dist/round-gate.d.ts.map +1 -0
  109. package/dist/round-gate.js +259 -0
  110. package/dist/round-gate.js.map +1 -0
  111. package/dist/round-recovery.d.ts +17 -0
  112. package/dist/round-recovery.d.ts.map +1 -0
  113. package/dist/round-recovery.js +117 -0
  114. package/dist/round-recovery.js.map +1 -0
  115. package/dist/round-report.d.ts +16 -0
  116. package/dist/round-report.d.ts.map +1 -0
  117. package/dist/round-report.js +401 -0
  118. package/dist/round-report.js.map +1 -0
  119. package/dist/round-transaction.d.ts +19 -12
  120. package/dist/round-transaction.d.ts.map +1 -1
  121. package/dist/round-transaction.js +102 -88
  122. package/dist/round-transaction.js.map +1 -1
  123. package/dist/runtime-services.d.ts +59 -0
  124. package/dist/runtime-services.d.ts.map +1 -0
  125. package/dist/runtime-services.js +460 -0
  126. package/dist/runtime-services.js.map +1 -0
  127. package/dist/storage.d.ts +3 -9
  128. package/dist/storage.d.ts.map +1 -1
  129. package/dist/storage.js +6 -17
  130. package/dist/storage.js.map +1 -1
  131. package/dist/token-utils.d.ts +9 -8
  132. package/dist/token-utils.d.ts.map +1 -1
  133. package/dist/token-utils.js +50 -10
  134. package/dist/token-utils.js.map +1 -1
  135. package/dist/vault-format.d.ts +4 -0
  136. package/dist/vault-format.d.ts.map +1 -0
  137. package/dist/vault-format.js +4 -0
  138. package/dist/vault-format.js.map +1 -0
  139. package/dist/vault-types.d.ts +24 -0
  140. package/dist/vault-types.d.ts.map +1 -0
  141. package/dist/vault-types.js +2 -0
  142. package/dist/vault-types.js.map +1 -0
  143. package/loop_policy.json +10 -12
  144. package/loopforge-policy.json +340 -0
  145. package/package.json +12 -6
  146. package/skills/perception/SKILL.md +199 -164
  147. package/dist/backends/interface.d.ts +0 -39
  148. package/dist/backends/interface.d.ts.map +0 -1
  149. package/dist/backends/interface.js +0 -6
  150. package/dist/backends/interface.js.map +0 -1
  151. package/dist/enforcement-gate.d.ts +0 -71
  152. package/dist/enforcement-gate.d.ts.map +0 -1
  153. package/dist/enforcement-gate.js +0 -744
  154. package/dist/enforcement-gate.js.map +0 -1
  155. package/dist/engine.d.ts +0 -59
  156. package/dist/engine.d.ts.map +0 -1
  157. package/dist/engine.js +0 -596
  158. package/dist/engine.js.map +0 -1
  159. package/dist/self-eval.d.ts +0 -23
  160. package/dist/self-eval.d.ts.map +0 -1
  161. package/dist/self-eval.js +0 -181
  162. package/dist/self-eval.js.map +0 -1
  163. package/dist/verification-gate.d.ts +0 -56
  164. package/dist/verification-gate.d.ts.map +0 -1
  165. package/dist/verification-gate.js +0 -563
  166. package/dist/verification-gate.js.map +0 -1
package/README.md CHANGED
@@ -1,71 +1,13 @@
1
- # LoopForge
1
+ # LoopForge package
2
2
 
3
- **A context window is not memory. Memory needs a runtime.**
3
+ LoopForge is a cognitive state runtime for AI coding agents. It keeps a long
4
+ task's objective, constraints, evidence, decisions and recovery state stable
5
+ across many Agent-driven rounds.
4
6
 
5
- > **v2.11.0** — `npm install -g loopforge`. Node.js ≥ 18. Zero runtime dependencies.
6
- > [中文文档](../README.zh-CN.md)
7
-
8
- ---
9
-
10
- ## The real problems with long-horizon tasks
11
-
12
- Any AI coding agent, given a long enough task, hits three walls. Not because the model isn't smart enough. Not because the context window isn't large enough. These are **architectural** problems.
13
-
14
- ### Problem 1: The summary cascade
15
-
16
- Context fills up → compress. Fills up again → compress again. The third compression is a summary of a summary of a summary. Every cycle evaporates information — critical constraints get silently deleted because the summarizer judged them "no longer relevant." Researchers found that after 3–4 summary cycles, constraint violation rates spike from 0% to 59%. The agent doesn't know what it forgot, because the forgetting itself was compressed away.
17
-
18
- ### Problem 2: Self-correction doesn't work
19
-
20
- Models cannot reliably improve themselves through introspection — they talk themselves out of correct answers. Effective recovery requires an **external verifier** — an independent observer that doesn't share the agent's context, doesn't participate in its reasoning, and only looks at inputs and outputs.
21
-
22
- ### Problem 3: Compound error (p^N)
23
-
24
- If each step succeeds with probability p, N sequential steps succeed with probability p^N. Frontier agents nail nearly 100% of tasks under 4 minutes but crater to under 10% on tasks over 4 hours. Small errors at each step become the correct input for the next step.
25
-
26
- **These three problems amplify each other. The summary cascade loses information → lost information becomes errors → the agent can't self-correct because those errors look reasonable within its own context.**
27
-
28
- ---
29
-
30
- ## What LoopForge does about it
31
-
32
- LoopForge doesn't compete on context window size. It runs **outside** the agent and provides three things:
33
-
34
- ### 1. Breaks the summary cascade: Vault → compile, not summary → summary
35
-
36
- Each round's self-evaluation is written to a **typed vault** (JSON documents). The next round's prompt is not generated from the previous prompt's summary — it's **recompiled from the vault**. Milestones aren't summaries of summaries; they're recomputed from raw vault entries. Constraints and criteria carry stable IDs (`c-XXXXXXXX`, `cr-XXXXXXXX`) for exact matching — no Jaccard guesswork.
37
-
38
- ```
39
- ❌ Traditional: prompt → summary → next prompt → re-summarize → … (information evaporates each cycle)
40
- ✅ LoopForge: prompt → vault entry → next prompt (recompiled from vault, zero evaporation)
41
- ```
42
-
43
- ### 2. External judgment: the perspective the agent cannot provide for itself
44
-
45
- The verification gate cross-checks every agent claim against independent evidence — Git snapshots, test runner output, explicit verification commands. The enforcement gate detects what the agent cannot self-diagnose:
46
-
47
- - R1: You claimed success but criteria remain unmet → **you're deceiving yourself**
48
- - R3: You claimed success with no verifiable evidence → **your claim is empty**
49
- - R4: You've been stuck for 3 rounds → **you're stalled and you don't know it**
50
- - R5: Your progress is exactly zero → **you're going through the motions**
51
- - R7: You said you'd do X but did Y → **your intent and actions are disconnected**
52
-
53
- **The agent cannot self-detect these. The agent is the system that produced those narratives. External judgment is necessary.**
54
-
55
- ### 3. Walk back from dead ends
56
-
57
- Progress stall or flatline → roll back to the last clean round instead of terminating. A diagnosis of why the path failed is injected. The backtrack prompt includes concrete workspace restore commands — `git checkout -- . && git clean -fd` with affected file lists. The verification gate checks that the workspace was actually restored before the next submission. Valid discoveries from skipped rounds are preserved.
58
-
59
- ---
60
-
61
- ## What LoopForge is not
62
-
63
- - ❌ **Not a memory system** — the state file is a derived view. The vault is truth. No RAG, no vector DB.
64
- - ❌ **Not a context compressor** — doesn't compress prompts, doesn't do smart summarization. Recompiles from vault, not from the previous prompt.
65
- - ❌ **Not a constraint tracker** — constraints are one signal the verification gate monitors. The core value is external judgment.
66
- - ❌ **Not a replacement for the agent** — the agent still reads code, edits files, runs tools, and decides how to reason. LoopForge owns the **round boundary**.
67
-
68
- ---
7
+ The Agent remains the executor: it reads code, edits files, runs tools and
8
+ decides how to reason. LoopForge is the external round boundary that checks
9
+ claims, commits canonical facts and rebuilds the next prompt. It is not a model,
10
+ scheduler, unattended worker or second planning system.
69
11
 
70
12
  ## Install
71
13
 
@@ -75,79 +17,154 @@ loopforge init --client claude
75
17
  claude mcp add loopforge -- npx loopforge mcp
76
18
  ```
77
19
 
78
- Works with Claude Code, Codex CLI, or any MCP-compatible client.
79
-
80
- The MCP server path (`loopforge mcp`) is the primary integration. It provides
81
- the full cognitive infrastructure: verification gate, enforcement gate,
82
- backtrack, evidence collection, and crash recovery. The engine is also
83
- available as a library for custom integrations.
84
-
85
- ---
86
-
87
- ## Architecture
88
-
20
+ For Codex use `loopforge init --client codex` and register the same MCP command.
21
+ The generic initializer prints an MCP configuration fragment. The package
22
+ requires Node.js 18 or newer and has zero runtime dependencies.
23
+
24
+ ## How a loop works
25
+
26
+ 1. The Agent calls `loopforge_start` with one objective and its hard constraints.
27
+ 2. LoopForge compiles a prompt from canonical state.
28
+ 3. The Agent executes that prompt and submits a structured `RoundReport`.
29
+ 4. Runtime evidence is checked, the round boundary is enforced, and the result is accepted, rejected, backtracked or stopped.
30
+ 5. If work remains, the next prompt is compiled again from committed facts.
31
+
32
+ The report deliberately separates `outcome` (`success`, `partial`, `failed` or
33
+ `blocked`) from `continuation` (`continue` or `stop`). This prevents a local
34
+ round result from being mistaken for completion of the whole objective. The old
35
+ `status` report and free-form evaluation text are not accepted at the public
36
+ boundary.
37
+
38
+ ```json
39
+ {
40
+ "format": "loopforge.round-report",
41
+ "outcome": "partial",
42
+ "continuation": "continue",
43
+ "summary": "Implemented the parser and ran focused tests.",
44
+ "violations": [],
45
+ "agentIntent": "Add parser regression coverage next",
46
+ "evidence": {"files": ["src/parser.ts"], "checks": [], "claims": [], "provenance": {}},
47
+ "discoveries": {"wrongAssumptions": [], "emergedWork": [], "facts": [], "newConstraints": []},
48
+ "subGoalEvents": {"completed": [], "blocked": [], "canceled": []}
49
+ }
89
50
  ```
90
- ┌─────────────────────────────────────────────────────┐
91
- │ Agent executes round │
92
- │ Reads code · Edits files · Runs tools · Reasons │
93
- └──────────────────────┬──────────────────────────────┘
94
- │ Agent submits SelfEvaluation
95
- ▼
96
- ┌─────────────────────────────────────────────────────┐
97
- │ LoopForge round boundary │
98
- │ │
99
- │ Evidence → Verify → Enforce → Commit → Compile │
100
- │ (Git/cmd) (11 checks) (7 rules) (vault) (next) │
101
- │ │
102
- │ accept: commit state, compile next round │
103
- │ reject: retry same round, zero state mutation │
104
- │ backtrack: roll back to last clean round, restore │
105
- │ terminate: persist terminal state │
106
- └──────────────────────┬──────────────────────────────┘
107
- │ Recompile prompt from vault
108
- ▼
109
- ┌─────────────────────────────────────────────────────┐
110
- │ Vault (typed JSON persistence) │
111
- │ loops/<id>/rounds/<n>.json · session.json · policy │
112
- │ Source of truth. Not a summary chain. │
113
- └─────────────────────────────────────────────────────┘
114
- ```
115
-
116
- ---
117
51
 
118
- ## Key capabilities
119
-
120
- **Vault → compile, not summary → summary.** Every round's self-evaluation is written to the vault. The next prompt is recompiled from vault entries. Stable IDs (`c-` / `cr-` / `sg-XXXXXXXX`) enable exact constraint, criterion, and sub-goal matching — no Jaccard false positives.
121
-
122
- **External judgment.** The verification gate cross-checks agent claims against independent evidence. The enforcement gate detects cognitive integrity violations — progress stalls, intent-action gaps, empty success claims. The judge never shares the agent's context.
123
-
124
- **Model expresses information needs.** Each round, the agent tells the compiler: what to emphasize, which sections to expand, where it's confused. The compiler reorders within safety boundaries — mandatory sections untouched, budget respected.
125
-
126
- **Walk back from dead ends.** Progress stall → roll back to last clean round with a diagnosis. Workspace restore is prompted and verified — the next submission is rejected if files from skipped rounds are still dirty.
127
-
128
- **Substantive drift, not filler.** R7 accepts intentional pivots only when the clarification references concrete IDs or file paths. Three consecutive weak clarifications terminate the loop.
129
-
130
- **Thin prompt, fat state file.** L0 (retry) / L1 (continuation) / L2 (full rehydration) control density only — reasoning strategy belongs to the agent. Truth is in the vault.
131
-
132
- **Pause · Resume · Replay.** Cross-process session leases. Idempotent resume after interruption. Time-travel queries over committed rounds.
133
-
134
- **Nine MCP tools.** `start` · `next` · `status` · `stop` · `pause` · `list` · `replay` · `resume` · `health`. Every tool returns typed `structuredContent`.
135
-
136
- **Zero dependencies. Policy-driven.** Node.js stdlib only. All thresholds, budgets, and intervals live in `loop_policy.json`. 491 tests.
52
+ `blocked` reports include a blocker. User decisions and external side effects
53
+ must stop at a User Gate; an Agent-resolvable technical blocker may continue
54
+ only with concrete evidence requirements.
55
+
56
+ ## State model and prompt artifact
57
+
58
+ The package follows a single-source rule: Goal, RoundEvent, EvidenceEnvelope,
59
+ Constraint, SubGoal and GateDecision are durable facts; phase history, Current
60
+ Focus, Todo, Handoff, progress, failed patterns and prompt diagnostics are
61
+ rebuildable projections, never a competing plan or persistence layer. Compiler
62
+ responses keep those derived views in one `projection` object. The full model,
63
+ the L0/L1/L2 prompt levels and the immutable prompt artifact are described in
64
+ the [project README](https://github.com/kyrielrving11/LoopForge/blob/main/README.md)
65
+ under “Canonical cognitive state” and “One prompt artifact per attempt”.
66
+
67
+ The default store is `.loopforge`. Events are written through the canonical
68
+ writer and receive a monotonic `event_sequence` within each loop. Prompt and
69
+ state hashes make a restart or replay auditable. Markdown state is only a
70
+ replaceable view, not the recovery truth.
71
+
72
+ Evidence collection and recovery are asynchronous. A malformed report is an
73
+ input error; corrupt JSON, an invalid event format, or a sequence gap is a
74
+ `storage_corruption` error and is never auto-repaired. The configured
75
+ `maxRounds` must be a positive integer no greater than the policy limit.
76
+
77
+ ## Verification, enforcement and gates
78
+
79
+ Git evidence is enabled by default. Explicit command providers run with an
80
+ executable and argument array (`shell: false`), bounded output, a timeout and a
81
+ workspace path check; required command failures contradict an unsupported
82
+ success claim. Agent claims remain `claimed` until a provider observes them —
83
+ provenance is owned by the runtime, and criteria coverage comes from verified
84
+ claims, never from a progress estimate. A successful report that requests a
85
+ stop is accepted as completion only when a live evidence provider produced
86
+ verifiable evidence; with no provider, completion stays unresolved.
87
+
88
+ Gate checks use `GateActionDescriptor` to make risk explicit: production,
89
+ credentials, data migration, publishing, payment, external communication,
90
+ public API changes, irreversible actions and unknown authorization are User
91
+ Gates; bounded, reversible, explicitly agent-allowed workspace work is an
92
+ Agent Gate. Decisions bind to an `actionHash`, so changing an action
93
+ invalidates an earlier approval.
94
+
95
+ For the full decision semantics — what the gate detects, how enforcement
96
+ decides accept, reject, backtrack and stop — see the corresponding sections in
97
+ the [project README](https://github.com/kyrielrving11/LoopForge/blob/main/README.md).
98
+
99
+ ## Recovery semantics
100
+
101
+ A rejected attempt is zero-commit: its report does not enter canonical state.
102
+ `loopforge_retry` keeps the same logical round ID and increments the attempt;
103
+ `loopforge_next` cannot bypass a rejection. `loopforge_backtrack` returns a
104
+ bounded restore point and verification requirements but never changes workspace
105
+ files. Pause and resume preserve the transaction across client or process
106
+ boundaries. Stop records termination without deleting the vault.
107
+
108
+ `agentIntent` is an optional, non-authoritative suggestion retained inside the
109
+ report for audit and drift comparison. It never overwrites Current Focus, Todo,
110
+ runtime progress, completion, or the compiler's Suggested Next Action.
111
+
112
+ Terminal enforcement escalation is tracked per rule. A rule can issue one
113
+ guided retry before a repeated hit terminates it; accepting progress or
114
+ backtracking clears the active rejection episode.
115
+
116
+ ## MCP surface
117
+
118
+ The server exposes exactly twelve Agent-driven tools:
119
+
120
+ ```text
121
+ loopforge_start loopforge_next loopforge_retry
122
+ loopforge_backtrack loopforge_resume loopforge_pause
123
+ loopforge_stop loopforge_status loopforge_history
124
+ loopforge_gate_check loopforge_gate_resolve loopforge_audit
125
+ ```
137
126
 
138
- ---
127
+ `status` combines session, loop and persisted-loop views. `history` combines
128
+ single-round inspection and event-timeline replay with sequence pagination. The
129
+ old `list`, `health`, `inspect` and `replay` MCP names are not aliases. MCP
130
+ Tasks and background Agent execution are intentionally outside this package.
131
+
132
+ ## Long-horizon use
133
+
134
+ LoopForge can support dozens or hundreds of explicit rounds, context
135
+ compression, restart, rejection and backtrack because every prompt is compiled
136
+ from durable facts rather than from a summary of the previous prompt. It does
137
+ not keep an Agent running after the client task ends. Use one loop per clear
138
+ objective; for a large roadmap, let the Agent carry explicit outcomes between
139
+ independent loops instead of creating an endless session.
140
+
141
+ ## Reliability boundaries
142
+
143
+ Malformed canonical reports are rejected without changing the current session,
144
+ round or vault, so callers can retry the same logical round. Persistence
145
+ failures are returned as errors and never become a successful or partial
146
+ commit. Drift clarification requires an explanation and a runtime-verifiable
147
+ anchor; agent waiver flags are not accepted. `loopforge doctor` diagnoses
148
+ unknown, deprecated, type-invalid and removed policy keys. Automatic Git
149
+ restore is intentionally not implemented. Persistence and evidence collection
150
+ are asynchronous; corrupt JSON, invalid event formats and sequence gaps return
151
+ `storage_corruption` instead of a partial status. `maxRounds` must be a positive
152
+ integer within the configured policy limit.
139
153
 
140
154
  ## Development
141
155
 
142
156
  ```bash
143
157
  npm run check
144
158
  npm test
145
- npm pack --dry-run --json
159
+ npm run build
160
+ npm run verify:artifacts
161
+ npm pack --dry-run --json --ignore-scripts
146
162
  ```
147
163
 
148
- The protocol schema in `../loopforge-protocol.json` is generated from `src/protocol.ts`. Do not edit it by hand.
149
-
150
- ---
164
+ The schema in the repository's `loopforge-protocol.json` is generated from
165
+ `src/protocol.ts`.
166
+ Do not edit it by hand. `init` installs `skills/perception/SKILL.md` for the
167
+ selected client and prints its MCP registration command.
151
168
 
152
169
  ## License
153
170
 
@@ -0,0 +1,20 @@
1
+ import type { LoopStore } from "./loop-store.js";
2
+ import type { VaultEntry } from "./vault-types.js";
3
+ /** Single write boundary for canonical loop events.
4
+ *
5
+ * Stores may provide their own atomic sequence allocator (FileLoopStore does),
6
+ * but the writer also assigns and validates sequences for lightweight test or
7
+ * embedding backends. Every runtime event therefore enters the Vault through
8
+ * one deterministic path.
9
+ */
10
+ export declare class CanonicalEventWriter {
11
+ private readonly backend;
12
+ constructor(backend: LoopStore);
13
+ private allEntries;
14
+ private replaceExisting;
15
+ private existing;
16
+ append(entry: VaultEntry): VaultEntry;
17
+ appendBatch(entries: VaultEntry[]): VaultEntry[];
18
+ private assertSequence;
19
+ }
20
+ //# sourceMappingURL=canonical-event-writer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical-event-writer.d.ts","sourceRoot":"","sources":["../src/canonical-event-writer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;;;;GAMG;AACH,qBAAa,oBAAoB;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,SAAS;IAE/C,OAAO,CAAC,UAAU;IAelB,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,QAAQ;IAMhB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,UAAU;IAkCrC,WAAW,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,UAAU,EAAE;IAuChD,OAAO,CAAC,cAAc;CAiBvB"}
@@ -0,0 +1,131 @@
1
+ import { StorageCorruptionError } from "./loop-store.js";
2
+ /** Single write boundary for canonical loop events.
3
+ *
4
+ * Stores may provide their own atomic sequence allocator (FileLoopStore does),
5
+ * but the writer also assigns and validates sequences for lightweight test or
6
+ * embedding backends. Every runtime event therefore enters the Vault through
7
+ * one deterministic path.
8
+ */
9
+ export class CanonicalEventWriter {
10
+ backend;
11
+ constructor(backend) {
12
+ this.backend = backend;
13
+ }
14
+ allEntries() {
15
+ // Global replacement needs entries from every loop, including backends
16
+ // whose default query excludes canonical `:event` records. Keep this
17
+ // fallback centralized here; per-loop runtime reads use queryLoopEvents.
18
+ const entries = this.backend.listLoopIds()
19
+ .flatMap((loopId) => this.backend.queryLoopEvents(loopId));
20
+ const seen = new Set();
21
+ return entries.filter((entry) => {
22
+ const key = `${entry.task_id ?? entry.id ?? ""}:${entry.event_sequence ?? ""}`;
23
+ if (seen.has(key))
24
+ return false;
25
+ seen.add(key);
26
+ return true;
27
+ });
28
+ }
29
+ replaceExisting(loopId, updated) {
30
+ const all = this.allEntries();
31
+ const filtered = all.filter((candidate) => !(candidate.loop_id === loopId && candidate.task_id === updated.task_id));
32
+ const replacement = [...filtered, updated];
33
+ this.backend.replaceEntries(replacement);
34
+ }
35
+ existing(loopId) {
36
+ const entries = this.backend.queryLoopEvents(loopId);
37
+ this.assertSequence(loopId, entries);
38
+ return entries;
39
+ }
40
+ append(entry) {
41
+ const write = () => {
42
+ const loopId = entry.loop_id;
43
+ if (!loopId)
44
+ throw new Error("Canonical events require loop_id");
45
+ if (entry.loop_id !== loopId)
46
+ throw new StorageCorruptionError("sequence_cross_loop", loopId, loopId);
47
+ const existing = this.existing(loopId);
48
+ const prior = existing.find((candidate) => candidate.task_id === entry.task_id);
49
+ if (prior && Number.isInteger(prior.event_sequence)) {
50
+ const updated = { ...entry, event_sequence: prior.event_sequence };
51
+ const priorComparable = { ...prior, id: undefined, timestamp: undefined };
52
+ const updatedComparable = { ...updated, id: undefined, timestamp: undefined };
53
+ if (JSON.stringify(priorComparable) === JSON.stringify(updatedComparable))
54
+ return prior;
55
+ this.replaceExisting(loopId, updated);
56
+ return updated;
57
+ }
58
+ const max = existing.reduce((value, candidate) => typeof candidate.event_sequence === "number" && Number.isInteger(candidate.event_sequence)
59
+ ? Math.max(value, candidate.event_sequence)
60
+ : value, 0);
61
+ const next = max + 1;
62
+ const sequenced = { ...entry, event_sequence: entry.event_sequence ?? next };
63
+ if (!Number.isInteger(sequenced.event_sequence) || sequenced.event_sequence < 1 ||
64
+ existing.some((candidate) => candidate.event_sequence === sequenced.event_sequence)) {
65
+ throw new StorageCorruptionError("sequence_duplicate", loopId, loopId, sequenced.event_sequence);
66
+ }
67
+ if (sequenced.event_sequence !== next) {
68
+ throw new StorageCorruptionError("sequence_gap", loopId, loopId, sequenced.event_sequence);
69
+ }
70
+ this.backend.appendEntry(sequenced);
71
+ return sequenced;
72
+ };
73
+ return this.backend.withLock(write);
74
+ }
75
+ appendBatch(entries) {
76
+ if (entries.length === 0)
77
+ return [];
78
+ const write = () => {
79
+ const loopIds = new Set(entries.map((entry) => entry.loop_id));
80
+ if (loopIds.size !== 1 || loopIds.has(undefined)) {
81
+ throw new Error("A canonical event batch must belong to one loop");
82
+ }
83
+ const loopId = [...loopIds][0];
84
+ const existing = this.existing(loopId);
85
+ const existingTaskIds = new Set(existing.map((candidate) => candidate.task_id).filter(Boolean));
86
+ const batchTaskIds = entries.map((entry) => entry.task_id).filter(Boolean);
87
+ if (batchTaskIds.length !== new Set(batchTaskIds).size ||
88
+ batchTaskIds.some((taskId) => existingTaskIds.has(taskId))) {
89
+ throw new Error(`Duplicate canonical task id in event batch for loop ${loopId}`);
90
+ }
91
+ const used = new Set(existing
92
+ .map((candidate) => candidate.event_sequence)
93
+ .filter((value) => typeof value === "number" && Number.isInteger(value)));
94
+ let next = existing.reduce((value, candidate) => typeof candidate.event_sequence === "number" && Number.isInteger(candidate.event_sequence)
95
+ ? Math.max(value, candidate.event_sequence)
96
+ : value, 0) + 1;
97
+ const sequenced = entries.map((entry) => ({ ...entry, event_sequence: entry.event_sequence ?? next++ }));
98
+ const seen = new Set();
99
+ for (const entry of sequenced) {
100
+ if (!Number.isInteger(entry.event_sequence) || used.has(entry.event_sequence) || seen.has(entry.event_sequence)) {
101
+ throw new StorageCorruptionError("sequence_duplicate", loopId, loopId, entry.event_sequence);
102
+ }
103
+ if (entry.event_sequence !== (existing.length ? Math.max(...used) : 0) + 1 + seen.size) {
104
+ throw new StorageCorruptionError("sequence_gap", loopId, loopId, entry.event_sequence);
105
+ }
106
+ seen.add(entry.event_sequence);
107
+ }
108
+ this.backend.appendEntries(sequenced);
109
+ return sequenced;
110
+ };
111
+ return this.backend.withLock(write);
112
+ }
113
+ assertSequence(loopId, entries) {
114
+ const sorted = [...entries].sort((a, b) => (a.event_sequence ?? 0) - (b.event_sequence ?? 0));
115
+ const seen = new Set();
116
+ for (let index = 0; index < sorted.length; index++) {
117
+ const sequence = sorted[index].event_sequence;
118
+ if (!Number.isInteger(sequence) || sequence < 1) {
119
+ throw new StorageCorruptionError("sequence_invalid", loopId, loopId, sequence);
120
+ }
121
+ if (seen.has(sequence)) {
122
+ throw new StorageCorruptionError("sequence_duplicate", loopId, loopId, sequence);
123
+ }
124
+ seen.add(sequence);
125
+ if (sequence !== index + 1) {
126
+ throw new StorageCorruptionError("sequence_gap", loopId, loopId, sequence);
127
+ }
128
+ }
129
+ }
130
+ }
131
+ //# sourceMappingURL=canonical-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AkB,CAAC,EAAE,CAAC;gBACjC,MAAM,IAAI,sBAAsB,CAAC,oBAAoB,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YACnF,CAAC;YACD,IAAI,CAAC,GAAG,CAAC,QAAkB,CAAC,CAAC;YAC7B,IAAI,QAAQ,KAAK,KAAK,GAAG,CAAC,EAAE,CAAC;gBAC3B,MAAM,IAAI,sBAAsB,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC7E,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
@@ -3,17 +3,16 @@
3
3
  * The canonical state is data, not Markdown. Prompt and state-file renderers
4
4
  * consume the same value so they cannot silently drift apart.
5
5
  */
6
- import type { ConstraintMeta, LoopCompileRequest, LoopCompileResponse, MilestoneSummary, SubGoal, VerificationFlag } from "./protocol.js";
7
- export declare const CANONICAL_STATE_SCHEMA_VERSION: 1;
6
+ import type { ConstraintMeta, LoopCompileRequest, LoopCompileResponse, SubGoal, VerificationFlag, DerivedGate, HandoffProjection, PhaseHistoryEntry, TodoProjection } from "./protocol.js";
7
+ export declare const CANONICAL_STATE_FORMAT: "loopforge.state";
8
8
  export interface CanonicalLoopState {
9
- schemaVersion: typeof CANONICAL_STATE_SCHEMA_VERSION;
9
+ format: "loopforge.state";
10
10
  loopId: string;
11
11
  round: number;
12
12
  maxRounds: number;
13
13
  goalId: string;
14
14
  objective: string;
15
15
  objectiveVersion: number;
16
- currentTask: string;
17
16
  successCriteria: string[];
18
17
  hardConstraints: string[];
19
18
  activeConstraints: string[];
@@ -27,20 +26,9 @@ export interface CanonicalLoopState {
27
26
  blockers: string[];
28
27
  verificationFlags: VerificationFlag[];
29
28
  discoveries: string[];
30
- nextAction: string;
31
29
  rollingOutcomes: string[];
32
30
  recurringIssues: string[];
33
31
  failedPatterns: string[];
34
- /** v2.6: derived from agent_declared milestones. */
35
- checkpoints: Array<{
36
- label: string;
37
- declared_at_round: number;
38
- outcome: string;
39
- carried_constraints: string[];
40
- resolved_constraints: string[];
41
- }>;
42
- /** v2.1: Phase-boundary milestone summaries that survive window eviction. */
43
- milestones: MilestoneSummary[];
44
32
  /** v2.1: Single-paragraph loop-level synthesis (formulaic). */
45
33
  loopSynthesis: string;
46
34
  /** v2.2: Structured sub-goals with compiler-managed lifecycle. */
@@ -49,7 +37,6 @@ export interface CanonicalLoopState {
49
37
  agentTrustScore: number | undefined;
50
38
  /** v2.5: Trust trend over last 10 rounds. */
51
39
  agentTrustTrend: number[];
52
- suggestedNextTask: string;
53
40
  externalContext: string;
54
41
  stateFilePath: string;
55
42
  progress: {
@@ -63,6 +50,23 @@ export interface CanonicalLoopState {
63
50
  skipped: number;
64
51
  } | null;
65
52
  };
53
+ /** Derived obligations that must be rechecked after a change. */
54
+ regressionObligations: Array<{
55
+ id: string;
56
+ description: string;
57
+ sourceRound: number;
58
+ evidenceRefs: string[];
59
+ status: "open" | "satisfied" | "contradicted";
60
+ }>;
61
+ /** Derived views. They are rebuilt on every compile and are not a
62
+ * second transaction truth. */
63
+ phaseHistory: PhaseHistoryEntry[];
64
+ currentFocus: string;
65
+ todoProjection: TodoProjection | null;
66
+ suggestedNextAction: string;
67
+ activeGate: DerivedGate | null;
68
+ stateFreshness: "fresh" | "stale" | "missing";
69
+ handoff: HandoffProjection;
66
70
  }
67
71
  /** Deterministic JSON serialization used by state and prompt hashes. */
68
72
  export declare function stableStringify(value: unknown): string;
@@ -1 +1 @@
1
- {"version":3,"file":"canonical-state.d.ts","sourceRoot":"","sources":["../src/canonical-state.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EACV,cAAc,EACd,kBAAkB,EAClB,mBAAmB,EACnB,gBAAgB,EAChB,OAAO,EACP,gBAAgB,EACjB,MAAM,eAAe,CAAC;AAIvB,eAAO,MAAM,8BAA8B,EAAG,CAAU,CAAC;AAEzD,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,OAAO,8BAA8B,CAAC;IACrD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