@tea-agent/loop-agent 0.42.0-next.2 → 0.42.0-next.4

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 (195) hide show
  1. package/CHANGELOG.md +244 -1
  2. package/dist/application/dag/generate-task-dag.js +75 -19
  3. package/dist/application/task-lifecycle/advance.js +24 -5
  4. package/dist/application/task-lifecycle/observe.js +171 -17
  5. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  6. package/dist/application/task-lifecycle/recommendations.js +13 -2
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +7 -0
  9. package/dist/cli/program.js +5 -0
  10. package/dist/commands/client-recovery.js +3 -0
  11. package/dist/commands/dag-follow-up.js +138 -0
  12. package/dist/commands/init.js +27 -1
  13. package/dist/commands/task-advance.js +19 -0
  14. package/dist/executors/dag-pi-executor.js +3789 -232
  15. package/dist/executors/pi-executor.js +15 -4
  16. package/dist/executors/pi-read-budget-policy.js +239 -0
  17. package/dist/executors/shell-executor.js +942 -187
  18. package/dist/executors/shell-write-guard.js +7 -0
  19. package/dist/infrastructure/console/operation-store.js +226 -6
  20. package/dist/shared/dag-failure-category.js +12 -0
  21. package/dist/shared/openspec-spec.js +70 -4
  22. package/dist/shared/operator/capabilities.js +7 -0
  23. package/dist/task/config-types.js +34 -5
  24. package/dist/task/contract/adopt.js +4 -0
  25. package/dist/task/contract/import-revision.js +4 -0
  26. package/dist/task/contract/project.js +3 -0
  27. package/dist/task/contract/schema.js +2 -1
  28. package/dist/task/frontend-project-capability.js +203 -20
  29. package/dist/task/runtime.js +5 -2
  30. package/dist/task/source-prepare/build-draft.js +3 -3
  31. package/dist/task/source-prepare/fragment-inventory.js +15 -9
  32. package/dist/task/source-prepare/prepare.js +89 -1
  33. package/dist/task/source-prepare/semantic-intake.js +6 -2
  34. package/dist/task/source-references.js +22 -1
  35. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  36. package/dist/worker/console/chat/pi-runtime.js +173 -7
  37. package/dist/worker/console/chat/repo-browser.js +10 -3
  38. package/dist/worker/console/chat/routes.js +30 -19
  39. package/dist/worker/console/chat/session-store.js +117 -70
  40. package/dist/worker/console/chat/shortcuts.js +1 -1
  41. package/dist/worker/console/chat/turn-process.js +111 -56
  42. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  43. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  44. package/dist/worker/console/index.js +3 -0
  45. package/dist/worker/console/operator-actions.js +169 -7
  46. package/dist/worker/console/server.js +3 -0
  47. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DZZ8m3PO.js → abnfDiagram-N423BO3Z-CeznJ4Iw.js} +1 -1
  48. package/dist/worker/console/static/assets/{arc-D6PvaVd-.js → arc-B4u9u7SX.js} +1 -1
  49. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B_OTOiI8.js → architectureDiagram-T3A2C74G-oghpT81p.js} +1 -1
  50. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bv6rqHBg.js → blockDiagram-VBNYF7ZC-BPJ5Kvcj.js} +1 -1
  51. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B8eHr0oz.js → c4Diagram-5PPSVZJV-CoIu69pd.js} +1 -1
  52. package/dist/worker/console/static/assets/channel-DmIXqJ6B.js +1 -0
  53. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DYwR0im2.js → chunk-2GRJ4B5K-DtgiAsSc.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-D2WPGqXt.js → chunk-2Q5K7J3B-YSu_EVSD.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CQISJ_I7.js → chunk-5RXB4S5H-DaRO-NB6.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-C0o2Du1e.js → chunk-5VM5RSS4-Dh0ZKiGA.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-4f8kr-U7.js → chunk-6Q2QTUOP-DOrvbR-H.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D_OWvXzX.js → chunk-GF5L2VYU-C3b22LN2.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CasdPz5X.js → chunk-JWPE2WC7-CXlqO8l6.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Cj8lRrla.js → chunk-KBJHAD2P-BblTBrDu.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CUvD1FSd.js → chunk-RYQCIY6F-DswqPALe.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CqLw_eqB.js → chunk-XXDRQBXY-CfTwVOlc.js} +1 -1
  63. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-MFV5Qxb5.js +1 -0
  64. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-MFV5Qxb5.js +1 -0
  65. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-ku-WqJPx.js → cose-bilkent-JH36ORCC-bLD8jVFo.js} +1 -1
  66. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-Bq_PYDhl.js → cynefin-VYW2F7L2-BvoG1fh5.js} +1 -1
  67. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BiGZV641.js → cynefinDiagram-MW4NZA55-DEPAdJu3.js} +1 -1
  68. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-C4JRlglF.js → dagre-VZM6K2ZE-DmrNvBLy.js} +1 -1
  69. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-B0dNeWYG.js → diagram-7IWD3JNH-CdwzIwvs.js} +1 -1
  70. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-Cj35YvYM.js → diagram-B4RE2ZJO-CJ3hj-md.js} +1 -1
  71. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-uzQoJ2-8.js → diagram-LBJQPF4R-C6YJT2a4.js} +1 -1
  72. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D1a-Buoz.js → diagram-Q27KOJAE-C_LPfjhX.js} +1 -1
  73. package/dist/worker/console/static/assets/{diagram-UB23O5K3-XjRrLRSs.js → diagram-UB23O5K3-xvsSb5Ie.js} +1 -1
  74. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Da_O24cW.js → ebnfDiagram-BXEA7PRR-Rxp2tKcD.js} +1 -1
  75. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BLJ8jrYU.js → erDiagram-JOGREHBK-DRyLYmZh.js} +1 -1
  76. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B9GrLjM0.js → flowDiagram-UKHOOZJN-TLSU_D2B.js} +1 -1
  77. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CeJ0TqiK.js → ganttDiagram-PKOTCBZU-DGqeTvHC.js} +1 -1
  78. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bm2eNNFX.js → gitGraphDiagram-DS77QQ5N-BZxyH2wh.js} +1 -1
  79. package/dist/worker/console/static/assets/index-C8V8K9b4.js +451 -0
  80. package/dist/worker/console/static/assets/index-Cnf_KxTQ.css +1 -0
  81. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DB26i3d8.js → infoDiagram-6WML65LV-BsYtzx01.js} +1 -1
  82. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BOGRyeZT.js → ishikawaDiagram-WSZJBQD7-Qr-ezGv-.js} +1 -1
  83. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CZRoBO_6.js → journeyDiagram-NVQOT4AX-DYbB3ibo.js} +1 -1
  84. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-qlWhJyoB.js → kanban-definition-27J2QSJJ-BHJHewZO.js} +1 -1
  85. package/dist/worker/console/static/assets/{linear-CfUiDDB3.js → linear-CmPIPmCG.js} +1 -1
  86. package/dist/worker/console/static/assets/{mermaid.core-BQe6fpqj.js → mermaid.core-F--C1uV0.js} +5 -5
  87. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zFzWHw64.js → mindmap-definition-FAOFIHXS-YTXfL1st.js} +1 -1
  88. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DFGUqjZO.js → pegDiagram-VL7TDLO6-DdDMYXP9.js} +1 -1
  89. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BB5i0l8Z.js → pieDiagram-7S7Q4E2Y-C3nH4KVd.js} +1 -1
  90. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-obbVZ_X5.js → quadrantDiagram-CIZ2JOQS-kXyxjG7Y.js} +1 -1
  91. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BwdaNzc1.js → railroadDiagram-AXF67PYL-KNzbl-7w.js} +1 -1
  92. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-CkTJaugh.js → requirementDiagram-LRYGKXZP-CSwI6dG0.js} +1 -1
  93. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BwJ-hIgq.js → sankeyDiagram-W5VNT64P-Bl1AyuXy.js} +1 -1
  94. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BzSgmm7w.js → sequenceDiagram-SI44F4Z6-2y4EmXQa.js} +1 -1
  95. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-Bn3oj5Q1.js → sizeCapture-X5ZJPWSS-E8v8YrMg.js} +1 -1
  96. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-dxhGtL8K.js → stateDiagram-OKZ733FA-eGGlR856.js} +1 -1
  97. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B8e4J3at.js +1 -0
  98. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BLpEInya.js → swimlanes-SLNWSIFB-B7g7xc07.js} +2 -2
  99. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Do88I1Nb.js +8 -0
  100. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-ChJGYcXy.js → timeline-definition-Z64GVDOM-DR3VCHBG.js} +1 -1
  101. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DK-qjRer.js → vennDiagram-T6HMQDX7-LUvapZIy.js} +1 -1
  102. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-3qeaWAg-.js → wardleyDiagram-T6FBY63Y-C7GDcaXq.js} +1 -1
  103. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CootlyP9.js → xychartDiagram-ELKLHX3M-CbNAqoGK.js} +1 -1
  104. package/dist/worker/console/static/index.html +2 -2
  105. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  106. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +19 -8
  107. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +15 -7
  108. package/dist/worker/console/workspace-context.js +111 -1
  109. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  110. package/dist/worker/observe/static/dag-node-purpose.js +5 -0
  111. package/dist/workflows/dag/backend-test-writer-completeness.js +10 -0
  112. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  113. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  114. package/dist/workflows/dag/frontend-closeout.js +221 -0
  115. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  116. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  117. package/dist/workflows/dag/frontend-implementation-contract.js +907 -162
  118. package/dist/workflows/dag/frontend-plan-render.js +2 -1
  119. package/dist/workflows/dag/frontend-prewrite-gate.js +255 -349
  120. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  121. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  122. package/dist/workflows/dag/frontend-recovery-controller.js +202 -0
  123. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  124. package/dist/workflows/dag/frontend-recovery-plan.js +17 -10
  125. package/dist/workflows/dag/frontend-recovery-run.js +33 -20
  126. package/dist/workflows/dag/frontend-repair.js +1 -432
  127. package/dist/workflows/dag/frontend-review-context.js +261 -15
  128. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  129. package/dist/workflows/dag/frontend-shadow-dual-write.js +914 -0
  130. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  131. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  132. package/dist/workflows/dag/frontend-shape.js +435 -0
  133. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  134. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  135. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  136. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  137. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  138. package/dist/workflows/dag/frontend-verification-trace.js +249 -24
  139. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  140. package/dist/workflows/dag/frontend-writer-admission.js +285 -0
  141. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  142. package/dist/workflows/dag/init-hybrid.js +677 -492
  143. package/dist/workflows/dag/interrupt-request.js +7 -0
  144. package/dist/workflows/dag/node-execution.js +732 -4
  145. package/dist/workflows/dag/prompt.js +34 -1
  146. package/dist/workflows/dag/recovery-lease.js +80 -0
  147. package/dist/workflows/dag/report.js +37 -1
  148. package/dist/workflows/dag/rerun-feedback.js +256 -1
  149. package/dist/workflows/dag/rerun-plan.js +17 -6
  150. package/dist/workflows/dag/rerun-run.js +23 -0
  151. package/dist/workflows/dag/rerun-task.js +29 -0
  152. package/dist/workflows/dag/retry-policy.js +214 -104
  153. package/dist/workflows/dag/runner.js +433 -126
  154. package/dist/workflows/dag/scheduler.js +114 -16
  155. package/dist/workflows/dag/types.js +239 -12
  156. package/dist/workflows/dag/validate.js +28 -12
  157. package/docs/examples/README.md +5 -0
  158. package/docs/init-surface.manifest.json +30 -12
  159. package/docs/skills/vetted-skill-registry.md +4 -2
  160. package/docs/templates/README.md +2 -0
  161. package/docs/templates/agent-dag-report.schema.json +8 -2
  162. package/docs/templates/agent-dag.schema.json +1 -1
  163. package/docs/templates/backend-test-dag.json +5 -2
  164. package/docs/templates/frontend-implementation-contract.schema.json +4 -1
  165. package/docs/templates/frontend-implementation-dag.json +89 -0
  166. package/docs/templates/spec-registry.schema.json +45 -0
  167. package/harness.json +1 -1
  168. package/package.json +1 -1
  169. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  170. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  171. package/skills/frontend-contract/SKILL.md +23 -0
  172. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  173. package/skills/frontend-design-review/SKILL.md +22 -41
  174. package/skills/frontend-plan/SKILL.md +26 -0
  175. package/skills/frontend-plan/references/decision-contract.md +37 -0
  176. package/skills/frontend-plan/references/design-decisions.md +17 -0
  177. package/skills/frontend-review/SKILL.md +20 -15
  178. package/skills/frontend-review/references/review-findings.md +6 -7
  179. package/skills/frontend-scout/SKILL.md +25 -0
  180. package/skills/frontend-scout/references/design-evidence.md +16 -0
  181. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  182. package/skills/frontend-verification/SKILL.md +1 -1
  183. package/skills/loop-agent/references/command-reference.md +1 -0
  184. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  185. package/dist/worker/console/static/assets/channel-BU5gOilw.js +0 -1
  186. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DIzKJGHr.js +0 -1
  187. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DIzKJGHr.js +0 -1
  188. package/dist/worker/console/static/assets/index-H9rFJiGL.css +0 -1
  189. package/dist/worker/console/static/assets/index-xwu9GxEc.js +0 -451
  190. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cld2qK9v.js +0 -1
  191. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-TIHpiT7w.js +0 -8
  192. package/skills/frontend-implementation/SKILL.md +0 -52
  193. package/skills/frontend-implementation/references/code-standards.md +0 -33
  194. package/skills/frontend-implementation/references/design-spec.md +0 -56
  195. package/skills/frontend-implementation/references/node-contracts.md +0 -31
@@ -0,0 +1,914 @@
1
+ import { readCommittedEvents, readTypedEventStoreFromJsonl, writeTypedEventStoreJsonl, } from "./frontend-typed-event-store.js";
2
+ import { adoptTypedEventFact, stageTypedEventFact, } from "./frontend-typed-event-transaction.js";
3
+ import { canonicalNodeOutput } from "./node-execution.js";
4
+ import { createDagEventObserver } from "./event-observer.js";
5
+ import { extractFrontendImplementationJson } from "./frontend-implementation-contract.js";
6
+ /**
7
+ * M2 shadow dual write (AC-001 / AC-002).
8
+ *
9
+ * The three read-only frontend nodes keep their authoritative text/JSON output
10
+ * protocols untouched. This module derives schema-valid shadow facts from those
11
+ * outputs and submits them through the M1 typed event store for audit and
12
+ * deterministic difference comparison only. Shadow facts never participate in
13
+ * writer admission and never control a DAG branch (M3 is the authority switch).
14
+ *
15
+ * Failure isolation (AC-001): every parse, stage, and adopt is swallowed, so a
16
+ * shadow-channel failure can never fail the producing node. The canonical event
17
+ * JSONL, when requested, is delegated to `createDagEventObserver`.
18
+ */
19
+ export const SHADOW_FACT_ORIGINS = ["contract", "scout", "plan"];
20
+ function isRecord(value) {
21
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22
+ }
23
+ function asString(value) {
24
+ return typeof value === "string" ? value.trim() : "";
25
+ }
26
+ function asStringArray(value) {
27
+ if (!Array.isArray(value))
28
+ return [];
29
+ return value
30
+ .map((item) => asString(item))
31
+ .filter((item) => item.length > 0);
32
+ }
33
+ /** Deterministic, sorted, de-duplicated string set. Lexicographic order only;
34
+ * never locale/Date-dependent so diff output is reproducible. */
35
+ function canonicalStringSet(values) {
36
+ return [
37
+ ...new Set(values
38
+ .map((item) => item.trim())
39
+ .filter((item) => item.length > 0)),
40
+ ].sort();
41
+ }
42
+ /* ------------------------------------------------------------------ *
43
+ * Contract Markdown parser (authoritative Markdown contract). *
44
+ * ------------------------------------------------------------------ */
45
+ const REQUIREMENT_ID_PATTERN = /(?:REQ|BR|AC)-[A-Z0-9]+(?:-[A-Z0-9]+)*/i;
46
+ function classifyContractHeading(heading) {
47
+ const normalized = heading.trim().toLowerCase().replace(/[^a-z0-9]+/g, " ");
48
+ if (normalized.includes("non goal"))
49
+ return "non-goal";
50
+ if (normalized.includes("acceptance"))
51
+ return "acceptance";
52
+ if (normalized.includes("open question"))
53
+ return "open-question";
54
+ if (normalized.includes("risk"))
55
+ return "risk";
56
+ if (normalized.includes("constraint"))
57
+ return "constraint";
58
+ if (normalized.includes("split"))
59
+ return "split";
60
+ if (normalized.includes("scope"))
61
+ return "scope";
62
+ return undefined;
63
+ }
64
+ function extractRequirementId(text) {
65
+ const match = REQUIREMENT_ID_PATTERN.exec(text);
66
+ return match ? match[0].toUpperCase() : undefined;
67
+ }
68
+ function extractBulletItems(sectionText) {
69
+ const items = [];
70
+ for (const rawLine of sectionText.split("\n")) {
71
+ const line = rawLine.trim();
72
+ if (!line)
73
+ continue;
74
+ const stripped = line.replace(/^(?:[-*+]|\d+[.)])\s*/, "").trim();
75
+ if (!stripped)
76
+ continue;
77
+ items.push(stripped);
78
+ }
79
+ return items;
80
+ }
81
+ function buildContractFact(section, item) {
82
+ switch (section) {
83
+ case "scope":
84
+ case "acceptance":
85
+ return {
86
+ kind: "requirement",
87
+ origin: "contract",
88
+ id: extractRequirementId(item) ?? item,
89
+ text: item,
90
+ };
91
+ case "non-goal":
92
+ return {
93
+ kind: "constraint",
94
+ origin: "contract",
95
+ category: "non-goal",
96
+ text: item,
97
+ };
98
+ case "constraint":
99
+ return {
100
+ kind: "constraint",
101
+ origin: "contract",
102
+ category: "constraint",
103
+ text: item,
104
+ };
105
+ case "risk":
106
+ return {
107
+ kind: "constraint",
108
+ origin: "contract",
109
+ category: "risk",
110
+ text: item,
111
+ };
112
+ case "open-question":
113
+ return { kind: "open-question", origin: "contract", text: item };
114
+ case "split":
115
+ return { kind: "split-proposal", origin: "contract", text: item };
116
+ }
117
+ }
118
+ export function parseContractFacts(text) {
119
+ const facts = [];
120
+ const lines = text.split("\n");
121
+ let current;
122
+ let buffer = [];
123
+ const flush = () => {
124
+ if (!current)
125
+ return;
126
+ for (const item of extractBulletItems(buffer.join("\n"))) {
127
+ facts.push(buildContractFact(current, item));
128
+ }
129
+ buffer = [];
130
+ };
131
+ for (const rawLine of lines) {
132
+ const line = rawLine.trimEnd();
133
+ const heading = /^#{1,6}\s+(.+?)\s*$/.exec(line.trim());
134
+ if (heading) {
135
+ flush();
136
+ current = classifyContractHeading(heading[1]);
137
+ continue;
138
+ }
139
+ if (current)
140
+ buffer.push(line);
141
+ }
142
+ flush();
143
+ return facts;
144
+ }
145
+ /* ------------------------------------------------------------------ *
146
+ * TARGET_SURFACE parser (authoritative scout text). *
147
+ * ------------------------------------------------------------------ */
148
+ const TARGET_SURFACE_LABELS = [
149
+ "entrypoint",
150
+ "routeOrMount",
151
+ "implementationPaths",
152
+ "testPaths",
153
+ "dataSource",
154
+ "allowedPathConflicts",
155
+ ];
156
+ function escapeRegex(value) {
157
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
158
+ }
159
+ function splitListValue(raw) {
160
+ const cleaned = raw.replace(/^\[|\]$/g, "").trim();
161
+ if (!cleaned)
162
+ return [];
163
+ return cleaned
164
+ .split(/[,\n]/)
165
+ .map((item) => item
166
+ .trim()
167
+ .replace(/^[-*+]\s+/, "")
168
+ .replace(/^["']|["']$/g, ""))
169
+ .filter((item) => item.length > 0);
170
+ }
171
+ function parseTargetSurfaceLabels(text) {
172
+ const result = {};
173
+ const sectionStart = text.indexOf("TARGET_SURFACE");
174
+ if (sectionStart < 0) {
175
+ for (const label of TARGET_SURFACE_LABELS)
176
+ result[label] = "";
177
+ return result;
178
+ }
179
+ const section = text.slice(sectionStart);
180
+ const positions = [];
181
+ for (const label of TARGET_SURFACE_LABELS) {
182
+ const match = new RegExp(`\\b${escapeRegex(label)}\\s*(?::|\\s)`).exec(section);
183
+ if (match && match.index !== undefined) {
184
+ positions.push({ label, index: match.index });
185
+ }
186
+ }
187
+ positions.sort((a, b) => a.index - b.index);
188
+ for (let i = 0; i < positions.length; i += 1) {
189
+ const current = positions[i];
190
+ const colon = section.indexOf(":", current.index);
191
+ const valueStart = colon >= 0 && colon < (positions[i + 1]?.index ?? section.length)
192
+ ? colon + 1
193
+ : current.index + current.label.length;
194
+ const valueEnd = i + 1 < positions.length ? positions[i + 1].index : section.length;
195
+ result[current.label] = section.slice(valueStart, valueEnd).trim();
196
+ }
197
+ for (const label of TARGET_SURFACE_LABELS) {
198
+ result[label] ??= "";
199
+ }
200
+ return result;
201
+ }
202
+ export function parseTargetSurfaceFacts(text) {
203
+ const values = parseTargetSurfaceLabels(text);
204
+ const implementationPaths = canonicalStringSet(splitListValue(values.implementationPaths));
205
+ const testPaths = canonicalStringSet(splitListValue(values.testPaths));
206
+ const allowedPathConflicts = canonicalStringSet(splitListValue(values.allowedPathConflicts));
207
+ return [
208
+ {
209
+ kind: "target-surface",
210
+ origin: "scout",
211
+ entrypoint: asString(values.entrypoint),
212
+ routeOrMount: asString(values.routeOrMount),
213
+ implementationPaths,
214
+ testPaths,
215
+ dataSource: asString(values.dataSource),
216
+ allowedPathConflicts,
217
+ },
218
+ {
219
+ kind: "design-evidence",
220
+ origin: "scout",
221
+ source: "TARGET_SURFACE",
222
+ paths: canonicalStringSet([...implementationPaths, ...testPaths]),
223
+ conflicts: allowedPathConflicts,
224
+ },
225
+ ];
226
+ }
227
+ export const PLAN_LEDGER_FACT_KINDS = [
228
+ "target-surface",
229
+ "component-choice",
230
+ "state-flow",
231
+ "data-flow",
232
+ "mock-api",
233
+ "design-deviation",
234
+ "dependency",
235
+ "plan-requirement",
236
+ "plan-verification-target",
237
+ "plan-evidence-gap",
238
+ ];
239
+ function skeletonTargetFiles(skeleton) {
240
+ if (!isRecord(skeleton))
241
+ return [];
242
+ const targets = isRecord(skeleton.targets) ? skeleton.targets : undefined;
243
+ return canonicalStringSet(asStringArray(targets?.files));
244
+ }
245
+ /** Restore the editable RFC 7386 plan patch from a committed plan ledger.
246
+ * Production compile authority is the tool payload (`patch` on any committed
247
+ * plan fact, else a `target-surface.patch`). Text JSON is never the compile
248
+ * authority. */
249
+ export function restorePlanPatchFromCommittedFacts(records) {
250
+ const planFacts = records
251
+ .filter((record) => record.phase === "committed")
252
+ .map((record) => record.fact)
253
+ .filter((fact) => isRecord(fact) &&
254
+ fact.origin === "plan" &&
255
+ typeof fact.kind === "string" &&
256
+ PLAN_LEDGER_FACT_KINDS.includes(fact.kind));
257
+ if (planFacts.length === 0)
258
+ return undefined;
259
+ for (const fact of planFacts) {
260
+ if (isRecord(fact.patch))
261
+ return fact.patch;
262
+ }
263
+ // No finalize-published snapshot: the receipt fix loop can end an attempt
264
+ // before any finalize_plan succeeds while dozens of record_* facts are
265
+ // already committed. Assemble the patch from those record facts instead of
266
+ // declaring the ledger missing (r19: "ledger missing" discarded a ledger
267
+ // with 92 committed facts).
268
+ return assemblePlanPatchFromCommittedFacts(records);
269
+ }
270
+ /**
271
+ * A+B (AC-004): reverse of `planLedgerFactsFromPatch` for the incremental
272
+ * `record_*` tool flow. Reconstructs the canonical editable patch from the raw
273
+ * fields each `record_*` tool committed. `finalize_plan` calls this and then
274
+ * re-publishes the assembled patch onto a `target-surface` fact so the
275
+ * writeSet-external compile authority (`frontend-implementation-contract.ts`)
276
+ * can still restore a plain `patch` object.
277
+ */
278
+ export function assemblePlanPatchFromCommittedFacts(records, contractRequirements) {
279
+ const facts = records
280
+ .filter((record) => record.phase === "committed")
281
+ .map((record) => record.fact)
282
+ .filter((fact) => isRecord(fact) &&
283
+ fact.origin === "plan" &&
284
+ typeof fact.kind === "string" &&
285
+ PLAN_LEDGER_FACT_KINDS.includes(fact.kind));
286
+ if (facts.length === 0)
287
+ return undefined;
288
+ // Singleton policy facts: the LAST committed fact wins. The model corrects a
289
+ // rejected plan by re-recording the policy (r18). Requirements / verification
290
+ // targets / evidence gaps stay additive; component choices accumulate; and
291
+ // state-flow is merged below by item name so UX-local batches do not erase one
292
+ // another.
293
+ const lastByKind = (kind) => {
294
+ let found;
295
+ for (const fact of facts) {
296
+ if (fact.kind === kind)
297
+ found = fact;
298
+ }
299
+ return found;
300
+ };
301
+ // Patch snapshots (published by earlier finalize calls) carry no routes;
302
+ // exclude them so a snapshot cannot shadow the model's route selection.
303
+ const routeSurface = (() => {
304
+ let found;
305
+ for (const fact of facts) {
306
+ if (fact.kind !== "target-surface" || isRecord(fact.patch))
307
+ continue;
308
+ found = fact;
309
+ }
310
+ return found;
311
+ })();
312
+ const patch = {};
313
+ const targetSurface = routeSurface;
314
+ if (targetSurface) {
315
+ const routes = canonicalStringSet(asStringArray(targetSurface.routes));
316
+ if (routes.length > 0)
317
+ patch.targets = { routes };
318
+ }
319
+ const componentChoices = facts.filter((fact) => fact.kind === "component-choice");
320
+ const collectedChoices = componentChoices.flatMap((fact) => Array.isArray(fact.uiComponentChoices)
321
+ ? fact.uiComponentChoices.filter(isRecord)
322
+ : []);
323
+ // Later corrections supersede earlier submissions per purpose: without
324
+ // this, a re-recorded choice (fixing a wrong specReference) would appear
325
+ // twice and the reviewer would still audit the stale entry (r19).
326
+ const choicesByPurpose = new Map();
327
+ const dedupedChoices = [];
328
+ for (const choice of collectedChoices) {
329
+ const purpose = asString(choice.purpose);
330
+ if (!purpose) {
331
+ dedupedChoices.push(choice);
332
+ continue;
333
+ }
334
+ if (choicesByPurpose.has(purpose)) {
335
+ const at = dedupedChoices.findIndex((existing) => asString(existing.purpose) === purpose);
336
+ dedupedChoices[at] = choice;
337
+ }
338
+ else {
339
+ choicesByPurpose.set(purpose, choice);
340
+ dedupedChoices.push(choice);
341
+ }
342
+ }
343
+ const stylingStrategy = componentChoices
344
+ .map((fact) => asString(fact.stylingStrategy))
345
+ .find((value) => value.length > 0);
346
+ if (dedupedChoices.length > 0)
347
+ patch.uiComponentChoices = dedupedChoices;
348
+ if (stylingStrategy)
349
+ patch.stylingStrategy = stylingStrategy;
350
+ // UX-local batches can emit several state-flow facts. Aggregate by the
351
+ // stable state/interaction name so a later correction replaces only that
352
+ // item; last-wins at the whole-fact level silently discarded earlier local
353
+ // batches when Segment 2 was split (r21).
354
+ const stateFlows = facts.filter((fact) => fact.kind === "state-flow");
355
+ const stateByName = new Map();
356
+ const unnamedStates = [];
357
+ const interactionByName = new Map();
358
+ const unnamedInteractions = [];
359
+ for (const flow of stateFlows) {
360
+ for (const name of asStringArray(flow.removeUiStateNames))
361
+ stateByName.delete(name);
362
+ for (const name of asStringArray(flow.removeInteractionNames))
363
+ interactionByName.delete(name);
364
+ for (const state of Array.isArray(flow.uiStates) ? flow.uiStates : []) {
365
+ if (!isRecord(state))
366
+ continue;
367
+ const name = asString(state.name);
368
+ if (name)
369
+ stateByName.set(name, state);
370
+ else
371
+ unnamedStates.push(state);
372
+ }
373
+ for (const interaction of Array.isArray(flow.interactions) ? flow.interactions : []) {
374
+ if (!isRecord(interaction))
375
+ continue;
376
+ const name = asString(interaction.name);
377
+ if (name)
378
+ interactionByName.set(name, interaction);
379
+ else
380
+ unnamedInteractions.push(interaction);
381
+ }
382
+ }
383
+ if (stateFlows.length > 0) {
384
+ patch.uiStates = [...stateByName.values(), ...unnamedStates];
385
+ patch.interactions = [...interactionByName.values(), ...unnamedInteractions];
386
+ }
387
+ const mockApi = lastByKind("mock-api");
388
+ if (mockApi && isRecord(mockApi.mockApi)) {
389
+ patch.mockApi = mockApi.mockApi;
390
+ }
391
+ const deviation = lastByKind("design-deviation");
392
+ if (deviation) {
393
+ const conflicts = canonicalStringSet(asStringArray(deviation.conflicts));
394
+ if (conflicts.length > 0)
395
+ patch.designEvidence = { conflicts };
396
+ }
397
+ const dependency = lastByKind("dependency");
398
+ const dependencyPolicy = asString(dependency?.policy);
399
+ if (dependencyPolicy)
400
+ patch.dependencyPolicy = dependencyPolicy;
401
+ // Requirements / verification targets / evidence gaps / implementation
402
+ // steps arrive as individual facts (one per record_plan_* call) so a large
403
+ // plan never exceeds a single model output budget. Aggregate them in
404
+ // ledger order.
405
+ const requirements = facts
406
+ .filter((fact) => fact.kind === "plan-requirement")
407
+ .map((fact) => fact.entry)
408
+ .filter(isRecord)
409
+ .map((entry) => {
410
+ // The canonical contract schema requires a non-empty
411
+ // expectedOutcome, but the plan should not be forced to re-write
412
+ // full outcome prose for every requirement (the contract node
413
+ // already captured requirement semantics). Derive a deterministic
414
+ // placeholder from the requirement id when omitted.
415
+ if (isRecord(entry) && !asString(entry.expectedOutcome)) {
416
+ const id = asString(entry.id) || "requirement";
417
+ return { ...entry, expectedOutcome: `implied by contract: ${id}` };
418
+ }
419
+ return entry;
420
+ })
421
+ // Source fidelity ledger (AC-005/AC-006): the contract node declared the
422
+ // authoritative sourceFragmentIds/sourceRefs for each requirement from
423
+ // the ledger's requirement→fragment mapping. The plan inherits them by
424
+ // requirement id so the compiled canonical contract carries the same
425
+ // provenance evidence without the plan re-deriving (or fabricating) it.
426
+ .map((entry) => {
427
+ if (!contractRequirements)
428
+ return entry;
429
+ const id = asString(entry.id);
430
+ if (!id)
431
+ return entry;
432
+ const inherited = contractRequirements.get(id);
433
+ if (!inherited)
434
+ return entry;
435
+ const merged = { ...entry };
436
+ // Inherit the contract-declared provenance only when the plan did
437
+ // not already declare it (model override wins; missing inherits).
438
+ if (!Array.isArray(entry.sourceFragmentIds)) {
439
+ if (inherited.sourceFragmentIds) {
440
+ merged.sourceFragmentIds = inherited.sourceFragmentIds;
441
+ }
442
+ }
443
+ if (!Array.isArray(entry.sourceRefs)) {
444
+ if (inherited.sourceRefs) {
445
+ merged.sourceRefs = inherited.sourceRefs;
446
+ }
447
+ }
448
+ return merged;
449
+ })
450
+ .map((entry) => {
451
+ if (isRecord(entry) && !isRecord(entry.evidenceGap)) {
452
+ const requirementId = asString(entry.id);
453
+ const standaloneGap = facts
454
+ .filter((fact) => fact.kind === "plan-evidence-gap")
455
+ .map((fact) => fact.entry)
456
+ .filter(isRecord)
457
+ .filter((gap) => asString(gap.requirementId) === requirementId)
458
+ .at(-1);
459
+ if (standaloneGap && asString(standaloneGap.description)) {
460
+ return { ...entry, evidenceGap: standaloneGap };
461
+ }
462
+ }
463
+ return entry;
464
+ })
465
+ // A requirement id is a canonical identity; drop duplicates so the
466
+ // compiled patch never carries the same requirement twice (the
467
+ // record_plan_requirement tool rejects re-records, this dedupes any
468
+ // legacy/edge duplicates at the compile authority).
469
+ .filter((entry, index, all) => all.map((other) => asString(other.id)).lastIndexOf(asString(entry.id)) === index);
470
+ if (requirements.length > 0)
471
+ patch.requirements = requirements;
472
+ const verificationTargetOrder = [];
473
+ const verificationTargetById = new Map();
474
+ for (const fact of facts.filter((item) => item.kind === "plan-verification-target")) {
475
+ const entry = fact.entry;
476
+ if (!isRecord(entry))
477
+ continue;
478
+ const id = asString(entry.id);
479
+ if (!id)
480
+ continue;
481
+ if (!verificationTargetById.has(id))
482
+ verificationTargetOrder.push(id);
483
+ verificationTargetById.set(id, entry);
484
+ }
485
+ const verificationTargets = verificationTargetOrder
486
+ .map((id) => verificationTargetById.get(id))
487
+ .filter((entry) => Boolean(entry));
488
+ if (verificationTargets.length > 0) {
489
+ patch.verificationTargets = verificationTargets;
490
+ }
491
+ const evidenceGaps = facts
492
+ .filter((fact) => fact.kind === "plan-evidence-gap")
493
+ .map((fact) => fact.entry)
494
+ .filter(isRecord);
495
+ if (evidenceGaps.length > 0)
496
+ patch.evidenceGaps = evidenceGaps;
497
+ return Object.keys(patch).length > 0 ? patch : undefined;
498
+ }
499
+ /** Derive the 7 origin=plan ledger facts from an editable patch. Skeleton
500
+ * `targets.files` fills `target-surface.files` because the patch must not
501
+ * write that protected path. */
502
+ export function planLedgerFactsFromPatch(patch, skeleton) {
503
+ const record = isRecord(patch) ? patch : undefined;
504
+ if (!record) {
505
+ throw new Error("frontend plan ledger requires an editable RFC 7386 patch object");
506
+ }
507
+ const facts = [];
508
+ const targets = isRecord(record.targets) ? record.targets : undefined;
509
+ const files = canonicalStringSet([
510
+ ...asStringArray(targets?.files),
511
+ ...skeletonTargetFiles(skeleton),
512
+ ]);
513
+ const routes = canonicalStringSet(asStringArray(targets?.routes));
514
+ facts.push({
515
+ kind: "target-surface",
516
+ origin: "plan",
517
+ files,
518
+ routes,
519
+ patch: record,
520
+ });
521
+ const uiComponentChoices = Array.isArray(record.uiComponentChoices)
522
+ ? record.uiComponentChoices.filter(isRecord)
523
+ : [];
524
+ const components = canonicalStringSet(uiComponentChoices.map((choice) => asString(choice.component)));
525
+ const stylingStrategy = asString(record.stylingStrategy);
526
+ if (components.length > 0 || stylingStrategy) {
527
+ facts.push({
528
+ kind: "component-choice",
529
+ origin: "plan",
530
+ components,
531
+ ...(stylingStrategy ? { stylingStrategy } : {}),
532
+ });
533
+ }
534
+ const uiStates = Array.isArray(record.uiStates)
535
+ ? record.uiStates.filter(isRecord)
536
+ : [];
537
+ const interactions = Array.isArray(record.interactions)
538
+ ? record.interactions.filter(isRecord)
539
+ : [];
540
+ const stateNames = canonicalStringSet(uiStates.map((state) => asString(state.name)));
541
+ const interactionNames = canonicalStringSet(interactions.map((interaction) => asString(interaction.name)));
542
+ if (stateNames.length > 0 || interactionNames.length > 0) {
543
+ facts.push({
544
+ kind: "state-flow",
545
+ origin: "plan",
546
+ states: stateNames,
547
+ interactions: interactionNames,
548
+ });
549
+ }
550
+ const mockApi = isRecord(record.mockApi) ? record.mockApi : undefined;
551
+ const endpoints = Array.isArray(mockApi?.endpoints)
552
+ ? mockApi.endpoints.filter(isRecord)
553
+ : [];
554
+ const endpointPaths = canonicalStringSet(endpoints.map((endpoint) => `${asString(endpoint.method)} ${asString(endpoint.path)}`.trim()));
555
+ if (interactionNames.length > 0 || endpointPaths.length > 0) {
556
+ facts.push({
557
+ kind: "data-flow",
558
+ origin: "plan",
559
+ interactions: interactionNames,
560
+ endpoints: endpointPaths,
561
+ });
562
+ }
563
+ if (mockApi) {
564
+ facts.push({
565
+ kind: "mock-api",
566
+ origin: "plan",
567
+ strategy: asString(mockApi.strategy),
568
+ endpoints: endpointPaths,
569
+ });
570
+ }
571
+ const designEvidence = isRecord(record.designEvidence)
572
+ ? record.designEvidence
573
+ : undefined;
574
+ const conflicts = canonicalStringSet(asStringArray(designEvidence?.conflicts));
575
+ if (conflicts.length > 0) {
576
+ facts.push({ kind: "design-deviation", origin: "plan", conflicts });
577
+ }
578
+ const dependencyPolicy = asString(record.dependencyPolicy);
579
+ if (dependencyPolicy) {
580
+ facts.push({ kind: "dependency", origin: "plan", policy: dependencyPolicy });
581
+ }
582
+ return facts;
583
+ }
584
+ /** Map committed plan facts, else a test-helper JSON patch, into the 7
585
+ * origin=plan kinds. Production compile authority is the committed ledger;
586
+ * a missing ledger/patch throws instead of returning a fake empty book. */
587
+ export function parsePlanLedgerFacts(textOrRecords, skeleton) {
588
+ if (typeof textOrRecords !== "string") {
589
+ const fromFacts = planLedgerFactsFromCommittedRecords(textOrRecords);
590
+ if (fromFacts.length > 0)
591
+ return fromFacts;
592
+ throw new Error("frontend plan ledger missing: no committed origin=plan facts");
593
+ }
594
+ const text = textOrRecords;
595
+ const jsonlLines = text
596
+ .split("\n")
597
+ .map((line) => line.trim())
598
+ .filter(Boolean);
599
+ const looksLikeJsonlLedger = jsonlLines.length > 0 &&
600
+ jsonlLines.every((line) => {
601
+ try {
602
+ const record = JSON.parse(line);
603
+ return (isRecord(record) &&
604
+ record.phase === "committed" &&
605
+ isRecord(record.fact) &&
606
+ typeof record.eventId === "string");
607
+ }
608
+ catch {
609
+ return false;
610
+ }
611
+ });
612
+ if (looksLikeJsonlLedger) {
613
+ const records = jsonlLines.map((line) => JSON.parse(line));
614
+ const fromFacts = planLedgerFactsFromCommittedRecords(records);
615
+ if (fromFacts.length > 0)
616
+ return fromFacts;
617
+ }
618
+ let value;
619
+ try {
620
+ value = extractFrontendImplementationJson(text);
621
+ }
622
+ catch {
623
+ throw new Error("frontend plan ledger missing: no committed plan facts");
624
+ }
625
+ return planLedgerFactsFromPatch(value, skeleton);
626
+ }
627
+ function planLedgerFactsFromCommittedRecords(records) {
628
+ const restored = restorePlanPatchFromCommittedFacts(records);
629
+ if (restored)
630
+ return planLedgerFactsFromPatch(restored);
631
+ return records
632
+ .filter((record) => record.phase === "committed")
633
+ .map((record) => record.fact)
634
+ .filter((fact) => isRecord(fact) &&
635
+ fact.origin === "plan" &&
636
+ typeof fact.kind === "string" &&
637
+ PLAN_LEDGER_FACT_KINDS.includes(fact.kind))
638
+ .map((fact) => fact);
639
+ }
640
+ export async function loadCommittedPlanLedgerFacts(runDir, nodeId = "frontend-plan-pi") {
641
+ const { readTypedEventStoreFromJsonl } = await import("./frontend-typed-event-store.js");
642
+ const pathMod = await import("node:path");
643
+ return readTypedEventStoreFromJsonl(pathMod.join(runDir, nodeId, "plan-typed-facts.jsonl"));
644
+ }
645
+ /** A+B (AC-001/003): read only the committed-phase origin facts from a node's
646
+ * typed event store JSONL. Staged/quarantined records never leak downstream. */
647
+ export async function readCommittedOriginFacts(runDir, nodeId, fileName) {
648
+ const pathMod = await import("node:path");
649
+ const records = await readTypedEventStoreFromJsonl(pathMod.join(runDir, nodeId, fileName));
650
+ return records.filter((record) => record.phase === "committed");
651
+ }
652
+ function latestCommittedScoutTargetSurface(records) {
653
+ return records
654
+ .filter((record) => record.phase === "committed" &&
655
+ isRecord(record.fact) &&
656
+ record.fact.origin === "scout" &&
657
+ record.fact.kind === "target-surface")
658
+ .at(-1)?.fact;
659
+ }
660
+ /**
661
+ * Scout owns discovery. A complete fact must explicitly say so, name at least
662
+ * one target candidate, leave no unresolved paths, and include fresh runtime
663
+ * evidence for a named target file. This deliberately accepts an empty test
664
+ * path list: some small changes have no existing focused test file, but they
665
+ * still need a proven implementation entrypoint.
666
+ */
667
+ export function readCompleteScoutTargetSurface(records) {
668
+ const fact = latestCommittedScoutTargetSurface(records);
669
+ if (!fact)
670
+ return {
671
+ ok: false,
672
+ reason: "frontend scout facts missing: no committed target-surface fact",
673
+ };
674
+ if (fact.completeness !== "complete")
675
+ return {
676
+ ok: false,
677
+ reason: "frontend scout target surface is not complete; resolve discovery gaps before Plan",
678
+ };
679
+ const unresolvedPaths = asStringArray(fact.unresolvedPaths);
680
+ if (unresolvedPaths.length > 0)
681
+ return {
682
+ ok: false,
683
+ reason: `frontend scout target surface has unresolved paths: ${unresolvedPaths.join(", ")}`,
684
+ };
685
+ const surface = {
686
+ entrypoint: asString(fact.entrypoint),
687
+ implementationPaths: canonicalStringSet(asStringArray(fact.implementationPaths)),
688
+ testPaths: canonicalStringSet(asStringArray(fact.testPaths)),
689
+ };
690
+ const namedPaths = canonicalStringSet([
691
+ ...(surface.entrypoint ? [surface.entrypoint] : []),
692
+ ...surface.implementationPaths,
693
+ ...surface.testPaths,
694
+ ]);
695
+ if (namedPaths.length === 0)
696
+ return {
697
+ ok: false,
698
+ reason: "frontend scout target surface is incomplete: name an entrypoint, implementation path, or test path",
699
+ };
700
+ const freshPaths = new Set(Array.isArray(fact.pathEvidence)
701
+ ? fact.pathEvidence
702
+ .filter(isRecord)
703
+ .filter((item) => item.fresh === true)
704
+ .map((item) => asString(item.path))
705
+ .filter(Boolean)
706
+ : []);
707
+ if (!namedPaths.some((candidate) => freshPaths.has(candidate)))
708
+ return {
709
+ ok: false,
710
+ reason: "frontend scout target surface lacks fresh runtime evidence for a named target path; record_target_surface enriches every declared entrypoint/implementation/test path against the real workspace, so at least one named path must exist on disk (an existing directory counts; a file to be created later cannot count)",
711
+ };
712
+ return { ok: true, surface };
713
+ }
714
+ /** Paths with Scout ownership that Plan may read for a specific decision. */
715
+ export function scoutConfirmedReadPaths(records) {
716
+ const checked = readCompleteScoutTargetSurface(records);
717
+ if (!checked.ok)
718
+ return [];
719
+ return canonicalStringSet([
720
+ ...(checked.surface.entrypoint ? [checked.surface.entrypoint] : []),
721
+ ...checked.surface.implementationPaths,
722
+ ...checked.surface.testPaths,
723
+ ]);
724
+ }
725
+ /** A+B (AC-001/003): fail-closed committed contract/scout fact prerequisites.
726
+ * `contract` requires a committed `contract-finalized` terminal fact; `scout`
727
+ * requires a complete target-surface fact. Missing or incomplete facts block
728
+ * downstream consumption — never fall back to text parsing. */
729
+ export function checkCommittedOriginFacts(input) {
730
+ const kinds = new Set(input.records
731
+ .filter((record) => record.phase === "committed")
732
+ .map((record) => record.fact.kind)
733
+ .filter((kind) => typeof kind === "string"));
734
+ if (input.origin === "contract") {
735
+ return kinds.has("contract-finalized")
736
+ ? { ok: true }
737
+ : {
738
+ ok: false,
739
+ reason: "frontend contract facts missing: no committed contract-finalized terminal fact",
740
+ };
741
+ }
742
+ if (input.origin === "scout") {
743
+ if (!kinds.has("target-surface"))
744
+ return {
745
+ ok: false,
746
+ reason: "frontend scout facts missing: no committed target-surface fact",
747
+ };
748
+ const checked = readCompleteScoutTargetSurface(input.records);
749
+ return checked.ok ? { ok: true } : { ok: false, reason: checked.reason };
750
+ }
751
+ return { ok: true };
752
+ }
753
+ /* ------------------------------------------------------------------ *
754
+ * Shadow observer factory. *
755
+ * ------------------------------------------------------------------ */
756
+ const SHADOW_NODE_PARSERS = {
757
+ "frontend-contract-pi": parseContractFacts,
758
+ "frontend-scout-pi": parseTargetSurfaceFacts,
759
+ "frontend-plan-pi": parsePlanLedgerFacts,
760
+ };
761
+ function isShadowNodeId(nodeId) {
762
+ return nodeId in SHADOW_NODE_PARSERS;
763
+ }
764
+ function reportError(context, error) {
765
+ const message = error instanceof Error ? error.message : String(error);
766
+ process.stderr.write(`[frontend-shadow-dual-write] ${context} failed: ${message}\n`);
767
+ }
768
+ export function createShadowDualWriteObserver(options) {
769
+ const base = options.eventsJsonlPath
770
+ ? createDagEventObserver({
771
+ eventsJsonlPath: options.eventsJsonlPath,
772
+ dagRunId: options.dagRunId,
773
+ spec: options.spec,
774
+ })
775
+ : null;
776
+ const recordNodeFacts = async (nodeId, state) => {
777
+ if (!isShadowNodeId(nodeId))
778
+ return;
779
+ const text = canonicalNodeOutput(state.nodes[nodeId]);
780
+ let facts;
781
+ try {
782
+ facts = options.parseNodeFacts
783
+ ? options.parseNodeFacts(nodeId, text)
784
+ : SHADOW_NODE_PARSERS[nodeId](text);
785
+ }
786
+ catch {
787
+ return;
788
+ }
789
+ for (const [index, fact] of facts.entries()) {
790
+ try {
791
+ // Deterministic requestId keeps replay idempotent within a node.
792
+ const requestId = `${options.requestId}:${nodeId}:${fact.kind}:${index}`;
793
+ const staged = stageTypedEventFact({
794
+ store: options.store,
795
+ requestId,
796
+ attemptId: options.attemptId,
797
+ fact,
798
+ });
799
+ await adoptTypedEventFact({
800
+ store: options.store,
801
+ requestId,
802
+ attemptId: options.attemptId,
803
+ fact,
804
+ eventId: staged.eventId,
805
+ expectedRevision: options.store.revision,
806
+ });
807
+ }
808
+ catch {
809
+ // A shadow commit failure never blocks the producing node (AC-001).
810
+ }
811
+ }
812
+ };
813
+ const observer = {
814
+ onRunStart: async (state) => {
815
+ await base?.observer.onRunStart?.(state);
816
+ },
817
+ onNodeStart: async (nodeId, state) => {
818
+ await base?.observer.onNodeStart?.(nodeId, state);
819
+ },
820
+ onNodeOutput: async (nodeId, chunk, state) => {
821
+ await base?.observer.onNodeOutput?.(nodeId, chunk, state);
822
+ },
823
+ onNodeFinish: async (nodeId, state) => {
824
+ try {
825
+ await recordNodeFacts(nodeId, state);
826
+ }
827
+ catch {
828
+ // Derived view; never affect canonical execution.
829
+ }
830
+ await base?.observer.onNodeFinish?.(nodeId, state);
831
+ },
832
+ onRunFinish: async (state) => {
833
+ await base?.observer.onRunFinish?.(state);
834
+ },
835
+ };
836
+ return {
837
+ observer,
838
+ flush: async () => {
839
+ try {
840
+ const committed = readCommittedEvents(options.store, options.attemptId);
841
+ await writeTypedEventStoreJsonl(options.shadowStoreJsonlPath, committed);
842
+ }
843
+ catch (error) {
844
+ reportError("flush", error);
845
+ }
846
+ await base?.flush();
847
+ },
848
+ };
849
+ }
850
+ function compareDimension(factValues, authorityValues) {
851
+ const facts = canonicalStringSet(factValues);
852
+ const authority = canonicalStringSet(authorityValues);
853
+ const matched = facts.filter((item) => authority.includes(item));
854
+ const factsOnly = facts.filter((item) => !authority.includes(item));
855
+ const authorityOnly = authority.filter((item) => !facts.includes(item));
856
+ return { facts, authority, matched, factsOnly, authorityOnly };
857
+ }
858
+ function factFieldStrings(facts, kinds, fields) {
859
+ const out = [];
860
+ for (const fact of facts) {
861
+ if (!kinds.includes(fact.kind))
862
+ continue;
863
+ for (const field of fields) {
864
+ const value = fact[field];
865
+ if (typeof value === "string")
866
+ out.push(value);
867
+ else if (Array.isArray(value))
868
+ out.push(...asStringArray(value));
869
+ }
870
+ }
871
+ return out;
872
+ }
873
+ export function compareShadowFactsToAuthority(input) {
874
+ const contractFacts = parseContractFacts(input.contractText);
875
+ const scoutFacts = parseTargetSurfaceFacts(input.scoutText);
876
+ const planFacts = parsePlanLedgerFacts(input.planText);
877
+ const requirementCoverage = compareDimension(factFieldStrings(input.facts, ["requirement"], ["id"]), factFieldStrings(contractFacts, ["requirement"], ["id"]));
878
+ const targetPaths = compareDimension([
879
+ ...factFieldStrings(input.facts, ["target-surface"], ["implementationPaths", "testPaths", "files", "routes"]),
880
+ ], [
881
+ ...factFieldStrings(scoutFacts, ["target-surface"], ["implementationPaths", "testPaths"]),
882
+ ...factFieldStrings(planFacts, ["target-surface"], ["files", "routes"]),
883
+ ]);
884
+ const componentDecisions = compareDimension(factFieldStrings(input.facts, ["component-choice", "state-flow", "data-flow", "mock-api"], ["components", "stylingStrategy", "states", "interactions", "endpoints", "strategy"]), factFieldStrings(planFacts, ["component-choice", "state-flow", "data-flow", "mock-api"], ["components", "stylingStrategy", "states", "interactions", "endpoints", "strategy"]));
885
+ const blockers = compareDimension(factFieldStrings(input.facts, ["constraint", "open-question", "design-deviation"], ["text", "conflicts"]), [
886
+ ...factFieldStrings(contractFacts, ["constraint", "open-question"], ["text"]),
887
+ ...factFieldStrings(planFacts, ["design-deviation"], ["conflicts"]),
888
+ ...factFieldStrings(scoutFacts, ["design-evidence"], ["conflicts"]),
889
+ ]);
890
+ return { requirementCoverage, targetPaths, componentDecisions, blockers };
891
+ }
892
+ export function renderShadowDiff(result) {
893
+ const lines = ["# Shadow Dual Write Diff", ""];
894
+ const sections = [
895
+ ["Requirement Coverage", result.requirementCoverage],
896
+ ["Target Paths", result.targetPaths],
897
+ ["Component Decisions", result.componentDecisions],
898
+ ["Blockers", result.blockers],
899
+ ];
900
+ for (const [title, dimension] of sections) {
901
+ lines.push(`## ${title}`);
902
+ lines.push(`- matched: ${dimension.matched.length}`);
903
+ lines.push(`- factsOnly: ${dimension.factsOnly.length}`);
904
+ lines.push(`- authorityOnly: ${dimension.authorityOnly.length}`);
905
+ for (const item of dimension.matched)
906
+ lines.push(` - [=] ${item}`);
907
+ for (const item of dimension.factsOnly)
908
+ lines.push(` - [+] ${item}`);
909
+ for (const item of dimension.authorityOnly)
910
+ lines.push(` - [-] ${item}`);
911
+ lines.push("");
912
+ }
913
+ return lines.join("\n");
914
+ }