@tea-agent/loop-agent 0.44.0-next.6 → 0.44.0-next.8

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 (105) hide show
  1. package/CHANGELOG.md +288 -454
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/dag-pi/guards.js +4 -0
  4. package/dist/executors/dag-pi/model-config.js +30 -0
  5. package/dist/{workflows/dag/frontend-plan-completeness.js → executors/dag-pi/plan/facts.js} +25 -41
  6. package/dist/executors/dag-pi/plan/ledger-contract.js +55 -0
  7. package/dist/executors/dag-pi/tools/contract-tools.js +515 -0
  8. package/dist/executors/dag-pi/tools/design-terminal-tools.js +156 -0
  9. package/dist/executors/dag-pi/tools/plan-decision-tools.js +519 -0
  10. package/dist/executors/dag-pi/tools/review-terminal-tools.js +156 -0
  11. package/dist/executors/dag-pi/tools/scout-evidence-tools.js +270 -0
  12. package/dist/executors/dag-pi-executor.js +64 -1907
  13. package/dist/shared/git-workspace-status.js +2 -0
  14. package/dist/task/frontend-preflight.js +1 -1
  15. package/dist/task/source-prepare/semantic-intake.js +1 -1
  16. package/dist/task/source-prepare/source-fidelity-pi.js +1 -1
  17. package/dist/worker/console/chat/assistant-content.js +5 -34
  18. package/dist/worker/console/chat/chat-event-store.js +27 -10
  19. package/dist/worker/console/chat/db-connections.js +72 -8
  20. package/dist/worker/console/chat/pi-runtime/custom-tools/sql-tools.js +52 -24
  21. package/dist/worker/console/chat/pi-runtime.js +34 -0
  22. package/dist/worker/console/chat/routes.js +138 -9
  23. package/dist/worker/console/chat/session-store.js +147 -19
  24. package/dist/worker/console/chat/turn-process.js +69 -23
  25. package/dist/worker/console/chat/user-turn-outline.js +19 -0
  26. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-Brn2sPzL.js → abnfDiagram-N423BO3Z-r1NAPU_5.js} +1 -1
  27. package/dist/worker/console/static/assets/{arc-BIMNTG0W.js → arc-dT5T4sVL.js} +1 -1
  28. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G--WtcgR_A.js → architectureDiagram-T3A2C74G-CP_cOq46.js} +1 -1
  29. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BT_Ztog1.js → blockDiagram-VBNYF7ZC-sToEZxEf.js} +1 -1
  30. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-C5hbVr-l.js → c4Diagram-5PPSVZJV-DSxwwi2m.js} +1 -1
  31. package/dist/worker/console/static/assets/channel-CyBY_yGk.js +1 -0
  32. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BKKnyR9Z.js → chunk-2GRJ4B5K-B9fh0IkF.js} +1 -1
  33. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BHs6biqA.js → chunk-2Q5K7J3B-CAUNl-A6.js} +1 -1
  34. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BdSFy_vP.js → chunk-5RXB4S5H-BomeqbNX.js} +1 -1
  35. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BpJIdTKV.js → chunk-5VM5RSS4-BNAuTOLE.js} +1 -1
  36. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-C_iWJhkT.js → chunk-6Q2QTUOP-DfzjRD5y.js} +1 -1
  37. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-BTbmx3-k.js → chunk-GF5L2VYU-C3uE-yc2.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-D4Ee6DmP.js → chunk-JWPE2WC7-C3sQMMYr.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B487SORR.js → chunk-KBJHAD2P-D_AtEYQL.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-BKYHjNrr.js → chunk-RYQCIY6F-DW4TwhKv.js} +1 -1
  41. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DrTdoYZG.js → chunk-XXDRQBXY-CTQDmJcp.js} +1 -1
  42. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D5lN4E_E.js +1 -0
  43. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D5lN4E_E.js +1 -0
  44. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-CttUY_Jo.js → cose-bilkent-JH36ORCC-iMqPuBsL.js} +1 -1
  45. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-B4Rm5gnR.js → cynefin-VYW2F7L2-DktIuDWs.js} +1 -1
  46. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-ByxHBq_S.js → cynefinDiagram-MW4NZA55-BgVnjyEs.js} +1 -1
  47. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DGrfNFA0.js → dagre-VZM6K2ZE-CR25E4bu.js} +1 -1
  48. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-KjrUPquv.js → diagram-7IWD3JNH-CPM2h5HY.js} +1 -1
  49. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-VS4mlm75.js → diagram-B4RE2ZJO-DqF0x2g1.js} +1 -1
  50. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-BLXYmFTM.js → diagram-LBJQPF4R-G8BYp2eb.js} +1 -1
  51. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-C6xoFAqH.js → diagram-Q27KOJAE-BbC4kT_D.js} +1 -1
  52. package/dist/worker/console/static/assets/{diagram-UB23O5K3-C478dCe7.js → diagram-UB23O5K3-CKZwZ-G5.js} +1 -1
  53. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-DHEpW5zN.js → ebnfDiagram-BXEA7PRR-kJDmheia.js} +1 -1
  54. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CA5GKfo9.js → erDiagram-JOGREHBK-DFTVHyxB.js} +1 -1
  55. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-zysi0Fl-.js → flowDiagram-UKHOOZJN-BqdN5_os.js} +1 -1
  56. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DGzcKA8Y.js → ganttDiagram-PKOTCBZU-SYDjVakh.js} +1 -1
  57. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-CHsuIG1w.js → gitGraphDiagram-DS77QQ5N-Bf8bNpGA.js} +1 -1
  58. package/dist/worker/console/static/assets/index-B28Onmfy.css +1 -0
  59. package/dist/worker/console/static/assets/index-CTMZsDmh.js +486 -0
  60. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-BexZHPCp.js → infoDiagram-6WML65LV-DIeAmJ45.js} +1 -1
  61. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Gkx8q-DB.js → ishikawaDiagram-WSZJBQD7-oikqUAlo.js} +1 -1
  62. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-XDW3qrJ7.js → journeyDiagram-NVQOT4AX-mKEF_xYT.js} +1 -1
  63. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DJ07eEaN.js → kanban-definition-27J2QSJJ-BdWJHPnN.js} +1 -1
  64. package/dist/worker/console/static/assets/{linear-DL-zeqOn.js → linear-DGRlieMH.js} +1 -1
  65. package/dist/worker/console/static/assets/{mermaid.core-C0HdXtOf.js → mermaid.core-4P9yPC9c.js} +5 -5
  66. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CqRX0lrt.js → mindmap-definition-FAOFIHXS-5PTSkos6.js} +1 -1
  67. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BVM9JZ2H.js → pegDiagram-VL7TDLO6-DONIFpG5.js} +1 -1
  68. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BA3ozdKk.js → pieDiagram-7S7Q4E2Y-D_Z4S70M.js} +1 -1
  69. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-B-0_p9_4.js → quadrantDiagram-CIZ2JOQS-CAsjh8iY.js} +1 -1
  70. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-DHRzPWFc.js → railroadDiagram-AXF67PYL-Cx4Dd6ac.js} +1 -1
  71. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-9BEC_PcW.js → requirementDiagram-LRYGKXZP-cQb7mwyH.js} +1 -1
  72. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-DMxeW4rN.js → sankeyDiagram-W5VNT64P-Cd-DhUdf.js} +1 -1
  73. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DixP6LIU.js → sequenceDiagram-SI44F4Z6-AlKYRgIk.js} +1 -1
  74. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-B_EifJBo.js → sizeCapture-X5ZJPWSS-CUy_ET4e.js} +1 -1
  75. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-BwikwWbX.js → stateDiagram-OKZ733FA-CTuVe6Sa.js} +1 -1
  76. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BsWhs8O7.js +1 -0
  77. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-C162l9o1.js → swimlanes-SLNWSIFB-ChFLJb-v.js} +2 -2
  78. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CJcioYGH.js +8 -0
  79. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-mpe_u1i4.js → timeline-definition-Z64GVDOM-DZZeiAPr.js} +1 -1
  80. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DyUk54HX.js → vennDiagram-T6HMQDX7-t4O91cZU.js} +1 -1
  81. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-HYyMkzfm.js → wardleyDiagram-T6FBY63Y-CV5qGHZu.js} +1 -1
  82. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-DRoh7skR.js → xychartDiagram-ELKLHX3M-DyXbytUI.js} +1 -1
  83. package/dist/worker/console/static/index.html +2 -2
  84. package/dist/worker/console/static-src/operator-chat/chat-link.js +20 -0
  85. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +58 -3
  86. package/dist/worker/console/static-src/operator-chat/process-label.js +19 -6
  87. package/dist/worker/console/static-src/operator-chat/transcript-mode.js +21 -0
  88. package/dist/worker/console/static-src/operator-chat/turn-group-equality.js +2 -0
  89. package/dist/worker/console/static-src/operator-chat/turn-process-disclosure.js +13 -5
  90. package/dist/worker/console/static-src/operator-chat/turn-state-projection.js +166 -0
  91. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +56 -2
  92. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +202 -43
  93. package/dist/worker/console/static-src/operator-chat/useChatStream.js +78 -23
  94. package/dist/worker/console/static-src/operator-chat/useChatThread.js +55 -18
  95. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +5 -2
  96. package/dist/worker/scheduler/scheduled-goal-dispatch.js +3 -2
  97. package/dist/worker/scheduler/scheduled-goal-evidence.js +6 -1
  98. package/package.json +1 -1
  99. package/dist/worker/console/static/assets/channel-DNWB4hpR.js +0 -1
  100. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-COhFgJji.js +0 -1
  101. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-COhFgJji.js +0 -1
  102. package/dist/worker/console/static/assets/index-CJh6pVLm.js +0 -482
  103. package/dist/worker/console/static/assets/index-C_kvKmFM.css +0 -1
  104. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-S2ZHMo1c.js +0 -1
  105. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BZm4ByfV.js +0 -8
@@ -1,21 +1,28 @@
1
1
  import { classifyFrontendPlanRecovery } from "../workflows/dag/frontend-plan-recovery-policy.js";
2
- import { collectFrontendExecutionGroups, frontendExecutionSchema } from "../workflows/dag/frontend-execution-groups.js";
2
+ import { collectFrontendExecutionGroups } from "../workflows/dag/frontend-execution-groups.js";
3
3
  import { FRONTEND_SCOPE_TARGET_BYTES, packFrontendInputUnits, parseFrontendInputBlock, projectFrontendContractPrompt, projectFrontendInputScope } from "../workflows/dag/frontend-input-projection.js";
4
4
  import { createDurableFrontendTools } from "../workflows/dag/frontend-durable-tools.js";
5
5
  import { sha256OfCanonicalJson } from "../task/contract/hash.js";
6
6
  import { z } from "zod";
7
- import { createFrontendReviewScopeProtocol, loadFrontendReviewScopes } from "../workflows/dag/frontend-review-scopes.js";
7
+ import { loadFrontendReviewScopes } from "../workflows/dag/frontend-review-scopes.js";
8
8
  import { observeFrontendSession } from "../workflows/dag/frontend-session-budget.js";
9
9
  import path from "node:path";
10
10
  import { createHash, randomUUID } from "node:crypto";
11
11
  import { readFile, stat } from "node:fs/promises";
12
12
  import { writeDagNodeJsonArtifact, writeTextArtifactFile, } from "../infrastructure/harness/artifact-store.js";
13
- import { writeJsonAtomic } from "../infrastructure/harness/atomic-write.js";
14
- import { mapContractBlockedOwner } from "../workflows/dag/frontend-human-decision.js";
15
13
  import { routeFrontendProviderCapability } from "../workflows/dag/frontend-provider-capability-matrix.js";
16
14
  import { executePiStep, resolvePiBackend, } from "./pi-executor.js";
17
15
  import { resolveDagPiExtensions, } from "./pi-extension-resolver.js";
18
16
  import { buildPiWriterToolPolicyContext, createPiReaderCustomTools, createPiWriterCustomTools, } from "./pi-writer-tool-policy.js";
17
+ import { resolveDagPiModelConfig } from "./dag-pi/model-config.js";
18
+ import { isRecordObject } from "./dag-pi/guards.js";
19
+ import { createFrontendReviewTerminalTools } from "./dag-pi/tools/review-terminal-tools.js";
20
+ import { createFrontendDesignTerminalTools } from "./dag-pi/tools/design-terminal-tools.js";
21
+ import { createFrontendScoutEvidenceTools } from "./dag-pi/tools/scout-evidence-tools.js";
22
+ import { createFrontendPlanDecisionTools, translateDecisionPatchFindings } from "./dag-pi/tools/plan-decision-tools.js";
23
+ import { createFrontendContractTools } from "./dag-pi/tools/contract-tools.js";
24
+ import { loadContractRequirementInheritance } from "./dag-pi/plan/ledger-contract.js";
25
+ import { collectFrontendPlanMissingFacts, collectFrontendPlanPhaseMissingFacts, committedFactFromPlanRecord, planFactStringList, planFactScopeIntersects } from "./dag-pi/plan/facts.js";
19
26
  import { createPiReadBudgetCustomTools, } from "./pi-read-budget-policy.js";
20
27
  import { cleanupPlaywrightCliDefaultSession, createPlaywrightCliTool, PI_COMMAND_CAPABILITY_REGISTRY, resolveCaseIdFromWriteSet, resolveEvidenceDirFromWriteSet, } from "./pi-playwright-cli-tool.js";
21
28
  import { dagCommandPolicyAllows, resolveDagCommandPolicy, } from "../workflows/dag/types.js";
@@ -26,7 +33,7 @@ import { GitStatusUnavailableError, pathsChangedDuringRun, readGitStatusPorcelai
26
33
  import { captureWorkspaceWriteSnapshot, diffWorkspaceWriteSnapshots, } from "./workspace-write-snapshot.js";
27
34
  import { pathMatchesPattern } from "../shared/git-progress.js";
28
35
  import { readTypedEventStoreFromJsonl, typedEventPayloadSha256, } from "../workflows/dag/frontend-typed-event-store.js";
29
- import { collectCanonicalStateFlowNames, frontendEvidenceExpectationSchema, resolveFrontendContractRequirements, validateFrontendRequiredDeliverables, } from "../workflows/dag/frontend-contract-facts.js";
36
+ import { collectCanonicalStateFlowNames, resolveFrontendContractRequirements, } from "../workflows/dag/frontend-contract-facts.js";
30
37
  import { isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, INCOMPLETE_WRITE_SET_RETRY_CATEGORY, OUTPUT_LIMIT_RETRY_CATEGORY, STRUCTURED_OUTPUT_RETRY_CATEGORY, WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY, WRITER_EMPTY_DIFF_RETRY_CATEGORY, } from "../workflows/dag/retry-policy.js";
31
38
  import { assessBackendTestMdPlanCompleteness, assessBackendTestMdWriterCompleteness, assessBackendTestPytestPlanCompleteness, assessBackendTestPytestWriterCompleteness, assessBackendTestShardChildCompleteness, backendTestWriterProgressRoleForTask, classifyBackendTestWriterCompletenessFailure, isBackendTestCompletenessRetryCandidate, isBackendTestMdPlanTask, isBackendTestPytestCollectionRepairOutcomeRecoveryCandidate, isBackendTestPytestPlanTask, isBackendTestShardChildTask, writeBackendTestWriterProgressArtifacts, } from "../workflows/dag/backend-test-writer-completeness.js";
32
39
  import { resolveBackendTestLayout } from "../workflows/dag/backend-test-layout.js";
@@ -348,15 +355,7 @@ export const DAG_PI_WRITE_TOOLS = [
348
355
  "ls",
349
356
  "bash",
350
357
  ];
351
- export const DEFAULT_DAG_PI_PROVIDER = "wizard-local";
352
358
  const WRITER_OUTCOME_PROTOCOL_LINE = "IMPLEMENTATION_OUTCOME:";
353
- export const DAG_PI_MODEL_PROVIDERS = {
354
- "gpt-5.3-codex-spark": "wizard-local",
355
- "gpt-5.5": "wizard-local",
356
- "glm-5.2": "wizard-local",
357
- "deepseek-v4-flash": "deepseek",
358
- "deepseek-v4-pro": "deepseek",
359
- };
360
359
  const SAFE_PI_STEPS = new Set([
361
360
  "analyze",
362
361
  "plan",
@@ -829,360 +828,6 @@ export function scanDesignTerminalKindsFromSessionEvents(content) {
829
828
  }
830
829
  return kinds;
831
830
  }
832
- /**
833
- * M5: build the two committed typed review terminal tools (approve_review /
834
- * request_review_changes). Each tool validates its parameters with the review
835
- * fact zod schemas, stages + adopts a terminal fact into the typed event
836
- * store, and returns a structured receipt. Terminal conflicts (a second
837
- * terminal commit) are caught inside execute and returned as an error receipt
838
- * rather than crashing the node.
839
- */
840
- export async function createFrontendReviewTerminalTools(input) {
841
- const [{ Type }, { defineTool }] = await Promise.all([
842
- import("typebox"),
843
- import("@earendil-works/pi-coding-agent"),
844
- ]);
845
- const { approveReviewFactSchema, readCommittedEvents, requestReviewChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
846
- const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
847
- let store = input.store;
848
- const attemptId = input.attemptId;
849
- const findingSchema = Type.Object({
850
- severity: Type.Enum({ Critical: "Critical", Important: "Important", Minor: "Minor", Info: "Info" }),
851
- file: Type.Optional(Type.String({ minLength: 1 })),
852
- line: Type.Optional(Type.Integer({ minimum: 1 })),
853
- issue: Type.String({ minLength: 1 }),
854
- requiredChange: Type.Optional(Type.String({ minLength: 1 })),
855
- }, { additionalProperties: false });
856
- const scopeProtocol = createFrontendReviewScopeProtocol({ phase: "review", inventory: input.inventory, getStore: () => store, attemptId });
857
- const savedFindings = () => [...new Map(readCommittedEvents(store, attemptId).filter(r => r.fact.kind === "review-finding").map(r => [r.fact.id, r.fact.finding])).values()];
858
- const allFindings = (direct) => [...new Map([...savedFindings(), ...(Array.isArray(direct) ? direct : [])].map(finding => [JSON.stringify(finding), finding])).values()];
859
- const recordFindingTool = defineTool({
860
- name: "record_review_finding", label: "record_review_finding",
861
- description: "Save one finding with a stable id. Submit findings incrementally, then finalize without repeating the findings array. Saved blocking findings cannot be omitted from approval; correct a finding explicitly with replace:true.",
862
- parameters: Type.Object({ id: Type.String({ minLength: 1 }), finding: findingSchema }, { additionalProperties: false }),
863
- async execute(_callId, params) {
864
- const fact = { kind: "review-finding", id: params.id, finding: params.finding };
865
- const requestId = `${attemptId}:finding:${randomUUID()}`;
866
- const staged = stageTypedEventFact({ store, requestId, attemptId, fact });
867
- const adopted = await adoptTypedEventFact({ store, requestId, attemptId, fact, eventId: staged.eventId, expectedRevision: store.revision });
868
- const details = { ok: true, eventId: adopted.eventId, revision: adopted.revision };
869
- return { content: [{ type: "text", text: JSON.stringify(details) }], details };
870
- },
871
- });
872
- const approveParameters = Type.Object({
873
- findings: Type.Optional(Type.Array(findingSchema, {
874
- description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
875
- })),
876
- }, { additionalProperties: false });
877
- const requestParameters = Type.Object({
878
- issueCategory: Type.Enum({
879
- "implementation-mismatch": "implementation-mismatch",
880
- "approved-design-defect": "approved-design-defect",
881
- "target-surface-defect": "target-surface-defect",
882
- "contract-requirement-gap": "contract-requirement-gap",
883
- "unknown": "unknown",
884
- }, { description: "Typed issue category (five-value enum)" }),
885
- evidenceRefs: Type.Array(Type.String({ minLength: 1 }), {
886
- description: "Evidence refs (paths or artifact ids); at least one", minItems: 1,
887
- }),
888
- findings: Type.Optional(Type.Array(findingSchema, {
889
- description: "At least one finding", minItems: 1,
890
- })),
891
- }, { additionalProperties: false });
892
- async function adoptReviewFact(kind, fact) {
893
- const requestId = randomUUID();
894
- try {
895
- scopeProtocol.assertComplete();
896
- const parsed = kind === "approve_review"
897
- ? approveReviewFactSchema.parse(fact)
898
- : requestReviewChangesFactSchema.parse(fact);
899
- const staged = stageTypedEventFact({
900
- store,
901
- requestId,
902
- attemptId,
903
- fact: parsed,
904
- });
905
- const adopted = await adoptTypedEventFact({
906
- store,
907
- requestId,
908
- attemptId,
909
- fact: parsed,
910
- eventId: staged.eventId,
911
- expectedRevision: store.revision,
912
- });
913
- return {
914
- content: [
915
- {
916
- type: "text",
917
- text: JSON.stringify({
918
- ok: true,
919
- kind,
920
- eventId: adopted.eventId,
921
- revision: adopted.revision,
922
- }),
923
- },
924
- ],
925
- details: {
926
- ok: true,
927
- kind,
928
- eventId: adopted.eventId,
929
- revision: adopted.revision,
930
- },
931
- };
932
- }
933
- catch (error) {
934
- const code = error?.code;
935
- const message = error instanceof Error ? error.message : String(error);
936
- return {
937
- content: [
938
- {
939
- type: "text",
940
- text: JSON.stringify({ ok: false, kind, code, error: message }),
941
- },
942
- ],
943
- details: { ok: false, kind, code, error: message },
944
- };
945
- }
946
- }
947
- const approveReviewTool = defineTool({
948
- name: "approve_review",
949
- label: "approve_review",
950
- description: "Commit the authoritative approve_review terminal fact. Use only when the implementation passes review with no Critical/Important findings.",
951
- promptSnippet: "Commit the authoritative approve_review terminal verdict (no Critical/Important findings).",
952
- parameters: approveParameters,
953
- async execute(_toolCallId, params) {
954
- return adoptReviewFact("approve_review", {
955
- kind: "approve_review",
956
- verdict: "approve_review",
957
- findings: allFindings(params?.findings),
958
- });
959
- },
960
- });
961
- const requestReviewChangesTool = defineTool({
962
- name: "request_review_changes",
963
- label: "request_review_changes",
964
- description: "Commit the authoritative request_review_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
965
- promptSnippet: "Commit the authoritative request_review_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
966
- parameters: requestParameters,
967
- async execute(_toolCallId, params) {
968
- return adoptReviewFact("request_review_changes", {
969
- kind: "request_review_changes",
970
- verdict: "request_review_changes",
971
- issueCategory: params?.issueCategory,
972
- evidenceRefs: params?.evidenceRefs,
973
- findings: allFindings(params?.findings),
974
- });
975
- },
976
- });
977
- const durable = await createDurableFrontendTools({
978
- file: path.join(input.runDir, input.nodeId, "review-typed-facts.jsonl"), attemptId, store: input.store,
979
- binding: { inputDigest: input.inputDigest, scopeDigest: input.inventory?.digest }, setWorkingStore: next => { store = next; }, tools: [...scopeProtocol.customTools, recordFindingTool, approveReviewTool, requestReviewChangesTool], validateRestored: async () => { await input.inventory?.validate(); },
980
- });
981
- return { ...durable, scopeProtocol };
982
- }
983
- /**
984
- * M8: build the two committed typed design terminal tools (approve_design /
985
- * request_design_changes). Each tool validates its parameters with the design
986
- * fact zod schemas, stages + adopts a terminal fact into the typed event
987
- * store, and returns a structured receipt. Terminal conflicts are caught
988
- * inside execute and returned as an error receipt rather than crashing the
989
- * node.
990
- */
991
- export async function createFrontendDesignTerminalTools(input) {
992
- const [{ Type }, { defineTool }] = await Promise.all([
993
- import("typebox"),
994
- import("@earendil-works/pi-coding-agent"),
995
- ]);
996
- const { approveDesignFactSchema, readCommittedEvents, requestDesignChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
997
- const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
998
- let store = input.store;
999
- const attemptId = input.attemptId;
1000
- const findingSchema = Type.Object({
1001
- severity: Type.Enum({ Critical: "Critical", Important: "Important", Minor: "Minor", Info: "Info" }),
1002
- file: Type.Optional(Type.String({ minLength: 1 })),
1003
- line: Type.Optional(Type.Integer({ minimum: 1 })),
1004
- issue: Type.String({ minLength: 1 }),
1005
- requiredChange: Type.Optional(Type.String({ minLength: 1 })),
1006
- }, { additionalProperties: false });
1007
- const scopeProtocol = createFrontendReviewScopeProtocol({ phase: "design", inventory: input.inventory, getStore: () => store, attemptId });
1008
- const savedFindings = () => [...new Map(readCommittedEvents(store, attemptId).filter(r => r.fact.kind === "design-finding").map(r => [r.fact.id, r.fact.finding])).values()];
1009
- const allFindings = (direct) => [...new Map([...savedFindings(), ...(Array.isArray(direct) ? direct : [])].map(finding => [JSON.stringify(finding), finding])).values()];
1010
- const recordFindingTool = defineTool({
1011
- name: "record_design_finding", label: "record_design_finding",
1012
- description: "Save one finding with a stable id. Submit findings incrementally, then finalize without repeating the findings array. Saved blocking findings cannot be omitted from approval; correct a finding explicitly with replace:true.",
1013
- parameters: Type.Object({ id: Type.String({ minLength: 1 }), finding: findingSchema }, { additionalProperties: false }),
1014
- async execute(_callId, params) {
1015
- const fact = { kind: "design-finding", id: params.id, finding: params.finding };
1016
- const requestId = `${attemptId}:finding:${randomUUID()}`;
1017
- const staged = stageTypedEventFact({ store, requestId, attemptId, fact });
1018
- const adopted = await adoptTypedEventFact({ store, requestId, attemptId, fact, eventId: staged.eventId, expectedRevision: store.revision });
1019
- const details = { ok: true, eventId: adopted.eventId, revision: adopted.revision };
1020
- return { content: [{ type: "text", text: JSON.stringify(details) }], details };
1021
- },
1022
- });
1023
- const approveParameters = Type.Object({
1024
- findings: Type.Optional(Type.Array(findingSchema, {
1025
- description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
1026
- })),
1027
- }, { additionalProperties: false });
1028
- const requestParameters = Type.Object({
1029
- issueCategory: Type.Enum({
1030
- "implementation-mismatch": "implementation-mismatch",
1031
- "approved-design-defect": "approved-design-defect",
1032
- "target-surface-defect": "target-surface-defect",
1033
- "contract-requirement-gap": "contract-requirement-gap",
1034
- "unknown": "unknown",
1035
- }, { description: "Typed issue category (five-value enum)" }),
1036
- evidenceRefs: Type.Array(Type.String({ minLength: 1 }), {
1037
- description: "Evidence refs (paths or artifact ids); at least one", minItems: 1,
1038
- }),
1039
- findings: Type.Optional(Type.Array(findingSchema, {
1040
- description: "At least one finding", minItems: 1,
1041
- })),
1042
- }, { additionalProperties: false });
1043
- async function adoptDesignFact(kind, fact) {
1044
- const requestId = randomUUID();
1045
- try {
1046
- scopeProtocol.assertComplete();
1047
- const parsed = kind === "approve_design"
1048
- ? approveDesignFactSchema.parse(fact)
1049
- : requestDesignChangesFactSchema.parse(fact);
1050
- const staged = stageTypedEventFact({
1051
- store,
1052
- requestId,
1053
- attemptId,
1054
- fact: parsed,
1055
- });
1056
- const adopted = await adoptTypedEventFact({
1057
- store,
1058
- requestId,
1059
- attemptId,
1060
- fact: parsed,
1061
- eventId: staged.eventId,
1062
- expectedRevision: store.revision,
1063
- });
1064
- return {
1065
- content: [
1066
- {
1067
- type: "text",
1068
- text: JSON.stringify({
1069
- ok: true,
1070
- kind,
1071
- eventId: adopted.eventId,
1072
- revision: adopted.revision,
1073
- }),
1074
- },
1075
- ],
1076
- details: {
1077
- ok: true,
1078
- kind,
1079
- eventId: adopted.eventId,
1080
- revision: adopted.revision,
1081
- },
1082
- };
1083
- }
1084
- catch (error) {
1085
- const code = error?.code;
1086
- const message = error instanceof Error ? error.message : String(error);
1087
- return {
1088
- content: [
1089
- {
1090
- type: "text",
1091
- text: JSON.stringify({ ok: false, kind, code, error: message }),
1092
- },
1093
- ],
1094
- details: { ok: false, kind, code, error: message },
1095
- };
1096
- }
1097
- }
1098
- const approveDesignTool = defineTool({
1099
- name: "approve_design",
1100
- label: "approve_design",
1101
- description: "Commit the authoritative approve_design terminal fact. Use only when the plan passes design review with no Critical/Important findings.",
1102
- promptSnippet: "Commit the authoritative approve_design terminal verdict (no Critical/Important findings).",
1103
- parameters: approveParameters,
1104
- async execute(_toolCallId, params) {
1105
- return adoptDesignFact("approve_design", {
1106
- kind: "approve_design",
1107
- verdict: "approve_design",
1108
- findings: allFindings(params?.findings),
1109
- });
1110
- },
1111
- });
1112
- const requestDesignChangesTool = defineTool({
1113
- name: "request_design_changes",
1114
- label: "request_design_changes",
1115
- description: "Commit the authoritative request_design_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
1116
- promptSnippet: "Commit the authoritative request_design_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
1117
- parameters: requestParameters,
1118
- async execute(_toolCallId, params) {
1119
- return adoptDesignFact("request_design_changes", {
1120
- kind: "request_design_changes",
1121
- verdict: "request_design_changes",
1122
- issueCategory: params?.issueCategory,
1123
- evidenceRefs: params?.evidenceRefs,
1124
- findings: allFindings(params?.findings),
1125
- });
1126
- },
1127
- });
1128
- const durable = await createDurableFrontendTools({
1129
- file: path.join(input.runDir, input.nodeId, "design-typed-facts.jsonl"), attemptId, store: input.store,
1130
- binding: { inputDigest: input.inputDigest, scopeDigest: input.inventory?.digest }, setWorkingStore: next => { store = next; }, tools: [...scopeProtocol.customTools, recordFindingTool, approveDesignTool, requestDesignChangesTool], validateRestored: async () => { await input.inventory?.validate(); },
1131
- });
1132
- return { ...durable, scopeProtocol };
1133
- }
1134
- /**
1135
- * Source fidelity ledger (AC-005/AC-006): load the contract node's committed
1136
- * requirement facts and build a requirement-id → provenance map. The contract
1137
- * node declared sourceFragmentIds/sourceRefs from the ledger's
1138
- * requirement→fragment mapping; the plan inherits them by id so the compiled
1139
- * canonical contract carries authoritative provenance without the plan
1140
- * re-deriving (or fabricating) it. Best-effort: missing/unreadable contract
1141
- * ledger yields an empty map and the plan compiles as before (the design
1142
- * policy shell will then fail closed on missing provenance).
1143
- */
1144
- async function loadContractRequirementInheritance(runDir) {
1145
- const { readTypedEventStoreFromJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
1146
- let records;
1147
- try {
1148
- records = await readTypedEventStoreFromJsonl(path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
1149
- }
1150
- catch {
1151
- return new Map();
1152
- }
1153
- const byId = new Map();
1154
- for (const record of records) {
1155
- const fact = record.fact;
1156
- if (!fact || typeof fact !== "object")
1157
- continue;
1158
- const recordFact = fact;
1159
- if (recordFact.origin !== "contract" ||
1160
- recordFact.kind !== "requirement") {
1161
- continue;
1162
- }
1163
- // Contract requirement facts carry id/sourceFragmentIds/sourceRefs on
1164
- // the fact itself (origin=contract, kind=requirement, id, text, ...),
1165
- // not inside an `entry` wrapper.
1166
- const id = typeof recordFact.id === "string" ? recordFact.id : "";
1167
- if (!id)
1168
- continue;
1169
- const sourceFragmentIds = Array.isArray(recordFact.sourceFragmentIds)
1170
- ? recordFact.sourceFragmentIds.filter((value) => typeof value === "string")
1171
- : undefined;
1172
- const sourceRefs = Array.isArray(recordFact.sourceRefs)
1173
- ? recordFact.sourceRefs.filter((value) => typeof value === "string")
1174
- : undefined;
1175
- if (sourceFragmentIds || sourceRefs) {
1176
- byId.set(id, {
1177
- ...(typeof recordFact.text === "string" ? { text: recordFact.text } : {}),
1178
- ...(recordFact.execution !== undefined ? { execution: frontendExecutionSchema.parse(recordFact.execution) } : {}),
1179
- ...(sourceFragmentIds ? { sourceFragmentIds } : {}),
1180
- ...(sourceRefs ? { sourceRefs } : {}),
1181
- });
1182
- }
1183
- }
1184
- return byId;
1185
- }
1186
831
  export async function resolveFrontendDecisionAuthority(input) {
1187
832
  const inheritance = await loadContractRequirementInheritance(input.runDir);
1188
833
  if (inheritance.size === 0)
@@ -2820,56 +2465,6 @@ export async function createFrontendPlanLedgerTools(input) {
2820
2465
  committedFacts: () => readCommittedEvents(store, attemptId),
2821
2466
  };
2822
2467
  }
2823
- /** Translate derived-patch validation findings into decision-channel
2824
- * vocabulary. Each zod issue path names a COMPILED patch array, but the model
2825
- * authored record_* facts — so quote the offending entry's identity and name
2826
- * the tool that owns it (r14: "uiComponentChoices.0.specReference.section:
2827
- * Required" is unactionable when the model has never heard of specReference). */
2828
- export function translateDecisionPatchFindings(message, decision) {
2829
- const body = message.replace(/^invalid-output:\s*/, "");
2830
- return body
2831
- .split(/;\s*/)
2832
- .map(issue => {
2833
- const choice = issue.match(/uiComponentChoices\.(\d+)\.(.+)/);
2834
- if (choice) {
2835
- const row = decision.reuseDecisions[Number(choice[1])];
2836
- const base = row
2837
- ? `record_reuse_decision purpose "${row.purpose}" (component ${row.symbol}, decision ${row.decision}): ${issue}`
2838
- : `record_reuse_decision row ${choice[1]}: ${issue}`;
2839
- const field = choice[2];
2840
- return field?.startsWith("specReference")
2841
- ? `${base} — pass specSection (the AC id / task-source section it implements) on that entry, or use decision "reuse-existing"`
2842
- : base;
2843
- }
2844
- const focus = issue.match(/verificationTargets\.(\d+)\.(.+)/);
2845
- if (focus) {
2846
- const row = decision.verificationFocus[Number(focus[1])];
2847
- if (!row)
2848
- return `record_verification_focus row ${focus[1]}: ${issue}`;
2849
- return `record_verification_focus ${row.id}: ${issue} — behavior targets derive uiStates from record_state_ownership rows whose owner equals behaviorGroupId "${row.behaviorGroupId}"; record one for this group if missing`;
2850
- }
2851
- const state = issue.match(/uiStates\.(\d+)\.(.+)/);
2852
- if (state) {
2853
- const row = decision.stateOwnership[Number(state[1])];
2854
- return row
2855
- ? `record_state_ownership "${row.state}" (owner ${row.owner}): ${issue}`
2856
- : `record_state_ownership row ${state[1]}: ${issue}`;
2857
- }
2858
- const interaction = issue.match(/interactions\.(\d+)\.(.+)/);
2859
- if (interaction) {
2860
- const row = decision.dataFlows[Number(interaction[1])];
2861
- return row
2862
- ? `record_data_flow "${row.interaction}": ${issue}`
2863
- : `record_data_flow row ${interaction[1]}: ${issue}`;
2864
- }
2865
- const requirement = issue.match(/requirements\.(\d+)\.(.+)/);
2866
- if (requirement) {
2867
- return `record_module_placement row ${requirement[1]}: ${issue}`;
2868
- }
2869
- return issue;
2870
- })
2871
- .join("; ");
2872
- }
2873
2468
  /** Read the recovery child's read-only parent decision snapshot (written by
2874
2469
  * the recovery continuation). Absent file → undefined (fresh plan). */
2875
2470
  export async function readParentDecisionSnapshot(runDir, nodeId) {
@@ -2914,525 +2509,59 @@ export async function replayParentDecisionSnapshot(snapshot, tools) {
2914
2509
  }
2915
2510
  }
2916
2511
  }
2917
- export async function createFrontendPlanDecisionTools(input) {
2918
- const [{ Type }, { defineTool }, { assembleDecisionContractFromFacts, assembleExperimentPlanContract, buildFrontendPlanRelationshipPatch }] = await Promise.all([
2919
- import("typebox"),
2920
- import("@earendil-works/pi-coding-agent"),
2921
- import("../workflows/dag/frontend-plan-decision-contract.js"),
2922
- ]);
2923
- const { readCommittedEvents } = await import("../workflows/dag/frontend-typed-event-store.js");
2924
- const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
2925
- const { createDurableFrontendTools } = await import("../workflows/dag/frontend-durable-tools.js");
2926
- let store = input.store;
2927
- const { attemptId, authority } = input;
2928
- const optionalStringArray = Type.Optional(Type.Array(Type.String({ minLength: 1 })));
2929
- const optionalString = Type.Optional(Type.String({ minLength: 1 }));
2930
- // In-session pre-validation of the derived relationship patch. The
2931
- // post-session bridge runs the identical analysis; running it first inside
2932
- // finalize_decision turns findings into a bounded in-session correction
2933
- // (fix facts, finalize again) instead of an attempt burn. Skipped when the
2934
- // caller does not supply the runtime skeleton/sourceBinding.
2935
- let requiredDeliverablesCache;
2936
- const prevalidateDerivedPatch = async () => {
2937
- if (!input.skeleton || !input.sourceBinding)
2938
- return { ok: true, canonicalSha256: "", canonical: {} };
2939
- const committed = readCommittedEvents(store, attemptId);
2940
- const decision = assembleDecisionContractFromFacts(committed.map(record => record.fact));
2941
- requiredDeliverablesCache ??= (async () => {
2942
- const map = new Map();
2943
- try {
2944
- const { readTypedEventStoreFromJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
2945
- const contractRecords = await readTypedEventStoreFromJsonl(path.join(input.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
2946
- for (const record of [...contractRecords].reverse()) {
2947
- const fact = record.fact;
2948
- if (!fact || fact.origin !== "contract" || fact.kind !== "required-deliverables")
2949
- continue;
2950
- for (const item of Array.isArray(fact.items) ? fact.items : []) {
2951
- if (!item || typeof item !== "object" || Array.isArray(item))
2952
- continue;
2953
- const requirementId = item.requirementId;
2954
- const file = item.path;
2955
- if (typeof requirementId !== "string" || typeof file !== "string")
2956
- continue;
2957
- const paths = map.get(requirementId) ?? [];
2958
- paths.push(file);
2959
- map.set(requirementId, paths);
2960
- }
2961
- break;
2962
- }
2963
- }
2964
- catch {
2965
- // Missing/unreadable contract ledger → no deliverable obligations.
2966
- }
2967
- return map;
2968
- })();
2969
- const concreteWriteSet = [
2970
- ...new Set([
2971
- ...decision.modulePlacements.flatMap(item => item.paths),
2972
- ...decision.verificationFocus.map(item => item.file),
2973
- ]),
2974
- ];
2975
- const { applyFrontendContractMergePatch, analyzeFrontendPlanPatchCandidate, FrontendContractFailure, PlanPolicyPrecheckFailure, serializeDeterministicJson, } = await import("../workflows/dag/frontend-implementation-contract.js");
2976
- try {
2977
- const patch = buildFrontendPlanRelationshipPatch({
2978
- decision,
2979
- authority,
2980
- concreteWriteSet,
2981
- requiredDeliverables: await requiredDeliverablesCache,
2982
- });
2983
- const merged = applyFrontendContractMergePatch(input.skeleton, patch);
2984
- const analysis = await analyzeFrontendPlanPatchCandidate({
2985
- runDir: input.runDir,
2986
- rawContractText: serializeDeterministicJson(merged),
2987
- sourceBinding: input.sourceBinding,
2988
- });
2989
- return {
2990
- ok: true,
2991
- canonicalSha256: createHash("sha256")
2992
- .update(serializeDeterministicJson(analysis.canonical))
2993
- .digest("hex"),
2994
- canonical: analysis.canonical,
2995
- };
2996
- }
2997
- catch (error) {
2998
- if (error instanceof PlanPolicyPrecheckFailure) {
2999
- // Template the fix: every uncovered interaction/state maps to a
3000
- // fill-in record_reuse_decision row (the decision channel's
3001
- // component-choice tool).
3002
- const suggestions = error.findings
3003
- .filter(finding => finding.code === "ui-design-coverage-missing" && finding.path)
3004
- .map(finding => ({
3005
- tool: "record_reuse_decision",
3006
- args: {
3007
- entry: {
3008
- symbol: "<name the existing or new component>",
3009
- decision: "reuse-existing",
3010
- evidence: ["<existing repo file that proves this reuse>"],
3011
- purpose: finding.path,
3012
- },
3013
- },
3014
- }));
3015
- const suggestionBlock = suggestions.length > 0
3016
- ? ` Suggested record_* calls (copy, fill component, submit): ${JSON.stringify(suggestions)}`
3017
- : "";
3018
- return {
3019
- ok: false,
3020
- error: `finalize_decision pre-validation failed (fix the listed plan facts, then call finalize_decision again): ${error.message}${suggestionBlock}`,
3021
- };
2512
+ /**
2513
+ * Decision → relationship bridge: after a successful decision `finalize`
2514
+ * (kind finalize_decision committed in plan-decision-facts.jsonl) the plan
2515
+ * node ALSO publishes the relationship-shaped plan ledger
2516
+ * (`<runDir>/<nodeId>/plan-typed-facts.jsonl`) carrying a committed
2517
+ * `target-surface` patch fact + a `finalize_plan` terminal fact derived from
2518
+ * the committed decision facts. The unchanged R1 self-check
2519
+ * (`validateFrontendPlanPatchNodeOutput`) and every downstream shell
2520
+ * (`buildContractFromCommittedFacts`) read ONLY that ledger, so without this
2521
+ * bridge every decision run fails deterministically with "frontend plan
2522
+ * ledger missing" → invalid-output on all attempts.
2523
+ *
2524
+ * The patch is compiled by `buildFrontendPlanRelationshipPatch` and front-loads
2525
+ * the exact validation the relationship finalize receipt runs (merge onto the
2526
+ * runtime skeleton + analyzeFrontendPlanPatchCandidate). When the derived
2527
+ * canonical fails, this returns a fixable error and the executor turns it into
2528
+ * an invalid-output so the node retry ladder restarts the session with the
2529
+ * diagnostics instead of writing a ledger that R1 would reject.
2530
+ */
2531
+ export async function bridgeFrontendPlanDecisionToRelationshipLedger(input) {
2532
+ const { assembleDecisionContractFromFacts, buildFrontendPlanRelationshipPatch, } = await import("../workflows/dag/frontend-plan-decision-contract.js");
2533
+ const committed = input.facts
2534
+ .filter(record => record.phase === "committed")
2535
+ .map(record => record.fact);
2536
+ const decision = assembleDecisionContractFromFacts(committed);
2537
+ const concreteWriteSet = [
2538
+ ...new Set([
2539
+ ...decision.modulePlacements.flatMap(item => item.paths),
2540
+ ...decision.verificationFocus.map(item => item.file),
2541
+ ]),
2542
+ ];
2543
+ // Contract-declared deliverable obligations (the same ledger the analyzer
2544
+ // extracts `requiredDeliverables` from): bind each path to its requirement
2545
+ // so the derived canonical contract plans every contract-mandated file.
2546
+ const requiredDeliverables = new Map();
2547
+ try {
2548
+ const contractRecords = await readTypedEventStoreFromJsonl(path.join(input.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
2549
+ for (const record of [...contractRecords].reverse()) {
2550
+ const fact = record.fact;
2551
+ if (!fact || fact.origin !== "contract" || fact.kind !== "required-deliverables")
2552
+ continue;
2553
+ for (const item of Array.isArray(fact.items) ? fact.items : []) {
2554
+ if (!item || typeof item !== "object" || Array.isArray(item))
2555
+ continue;
2556
+ const requirementId = item.requirementId;
2557
+ const file = item.path;
2558
+ if (typeof requirementId !== "string" || typeof file !== "string")
2559
+ continue;
2560
+ const paths = requiredDeliverables.get(requirementId) ?? [];
2561
+ paths.push(file);
2562
+ requiredDeliverables.set(requirementId, paths);
3022
2563
  }
3023
- // FrontendContractFailure messages carry zod issue paths and are
3024
- // translated into record_* vocabulary; the bridge compiler throws
3025
- // decision-state-unbindable / decision-styling-strategy-conflict
3026
- // diagnostics that are already model-fixable as written.
3027
- const message = error instanceof Error ? error.message : String(error);
3028
- const translated = error instanceof FrontendContractFailure
3029
- ? translateDecisionPatchFindings(message, decision)
3030
- : message;
3031
- return {
3032
- ok: false,
3033
- error: `finalize_decision pre-validation failed (fix the listed facts with the named record_* tools — resubmit a corrected row with the same identity and replace:true to replace it — then call finalize_decision again): ${translated}`,
3034
- };
3035
- }
3036
- };
3037
- const planToolReceipt = (details) => ({
3038
- content: [{ type: "text", text: JSON.stringify(details) }],
3039
- details,
3040
- });
3041
- async function adoptDecisionFact(kind, requestId, fact) {
3042
- try {
3043
- const staged = stageTypedEventFact({
3044
- store,
3045
- requestId,
3046
- attemptId,
3047
- fact: fact,
3048
- });
3049
- const committed = await adoptTypedEventFact({
3050
- store,
3051
- requestId,
3052
- attemptId,
3053
- fact: fact,
3054
- eventId: staged.eventId,
3055
- expectedRevision: store.revision,
3056
- });
3057
- return { ok: true, kind, eventId: committed.eventId, revision: committed.revision, error: "" };
3058
- }
3059
- catch (error) {
3060
- return {
3061
- ok: false,
3062
- kind,
3063
- code: error?.code,
3064
- error: error instanceof Error ? error.message : String(error),
3065
- };
3066
- }
3067
- }
3068
- const record = (name, label, description, entrySchema, gate) => defineTool({
3069
- name,
3070
- label,
3071
- description,
3072
- promptSnippet: `Record ${label}.`,
3073
- parameters: Type.Object({ entry: entrySchema }, { additionalProperties: false }),
3074
- async execute(_toolCallId, params) {
3075
- const entry = params?.entry;
3076
- const kind = name.replace("record_", "").replace(/_/g, "-");
3077
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
3078
- return planToolReceipt({ ok: false, kind, error: `${name} requires a non-empty entry object` });
3079
- }
3080
- if (gate) {
3081
- const rejected = await gate(entry);
3082
- if (rejected)
3083
- return rejected;
3084
- }
3085
- const result = await adoptDecisionFact(kind, `${attemptId}:${name}:${randomUUID()}`, { kind, origin: "plan", entry });
3086
- return planToolReceipt(result);
3087
- },
3088
- });
3089
- const recordModulePlacementTool = record("record_module_placement", "module placement", "Record one module placement: which behavior-group/module id maps to which concrete files. Example: {\"entry\": {\"id\": \"page\", \"paths\": [\"src/page.tsx\"]}}", Type.Object({ id: Type.String({ minLength: 1 }), paths: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }) }, { additionalProperties: false }));
3090
- const recordReuseDecisionTool = record("record_reuse_decision", "reuse decision", "Record one component decision: which component serves which UI state/interaction (purpose). decision \"reuse-existing\" = an existing repo component (evidence[0] = the repo file that proves it); \"specified\" = the frontend spec mandates it; \"new\" = the task source mandates a bounded addition — specified/new require specSection naming the spec/task-source declaration they implement (e.g. an AC id). Set stylingStrategy once (on the first call) when the task mandates a style contract. Resubmit the same purpose with replace:true to correct a row. Example: {\"entry\": {\"symbol\": \"Spinner\", \"decision\": \"reuse-existing\", \"evidence\": [\"src/ui/Spinner.tsx\"], \"purpose\": \"loading\"}} or {\"entry\": {\"symbol\": \"SmokeCounter\", \"decision\": \"new\", \"evidence\": [\"需求.md\"], \"purpose\": \"increment\", \"specSection\": \"AC-FE-002\", \"stylingStrategy\": \"compact, stable, animation-free single card\"}}", Type.Object({
3091
- symbol: Type.String({ minLength: 1 }),
3092
- decision: Type.Union([Type.Literal("specified"), Type.Literal("reuse-existing"), Type.Literal("new")]),
3093
- evidence: Type.Array(Type.String()),
3094
- specSection: Type.Optional(Type.String({ minLength: 1 })),
3095
- purpose: Type.String({ minLength: 1 }),
3096
- covers: optionalStringArray,
3097
- rationale: optionalString,
3098
- stylingStrategy: optionalString,
3099
- }, { additionalProperties: false }), async (entry) => {
3100
- // specified/new compile into a canonical specReference whose .section
3101
- // the contract schema mandates; without the section the row can only
3102
- // fail at finalize, so demand it here where the model can still act.
3103
- if (entry.decision === "specified") {
3104
- const evidenceList = Array.isArray(entry.evidence) ? entry.evidence : [];
3105
- const evidencePath = typeof evidenceList[0] === "string" ? evidenceList[0] : "";
3106
- const candidates = input.componentSpecCandidatePaths ?? [];
3107
- if (candidates.length === 0) {
3108
- return planToolReceipt({
3109
- ok: false,
3110
- kind: "reuse-decision",
3111
- error: `record_reuse_decision specified-requires-spec-candidates: decision "specified" means a declared component spec mandates this choice, but this task declares no component spec candidates — use decision "new" (task-source-mandated addition, evidence[0] = the task-source file) or "reuse-existing"`,
3112
- });
3113
- }
3114
- if (evidencePath && !candidates.includes(evidencePath)) {
3115
- return planToolReceipt({
3116
- ok: false,
3117
- kind: "reuse-decision",
3118
- error: `record_reuse_decision specified-spec-reference-outside-candidates: evidence[0] "${evidencePath}" is not a declared component spec candidate; declared candidates: [${candidates.join(", ")}]`,
3119
- });
3120
- }
3121
- }
3122
- if ((entry.decision === "specified" || entry.decision === "new") &&
3123
- !(typeof entry.specSection === "string" && entry.specSection.trim())) {
3124
- return planToolReceipt({
3125
- ok: false,
3126
- kind: "reuse-decision",
3127
- error: `record_reuse_decision spec-section-required: decision "${entry.decision}" must name the spec/task-source declaration it implements via specSection (e.g. an AC id); use decision "reuse-existing" for existing repo conventions. Example: {"entry": {"symbol": "SmokeCounter", "decision": "new", "evidence": ["src/components/SmokeCounter.tsx"], "purpose": "render the counter card", "specSection": "AC-FE-001"}}`,
3128
- });
3129
- }
3130
- return undefined;
3131
- });
3132
- const recordStateOwnershipTool = record("record_state_ownership", "state ownership", "Record one UI state and its owner, applicability and expected behavior. owner must equal the behaviorGroupId of the record_verification_focus entries it supports; every behavior group referenced by a verification focus needs at least one state row or finalize fails. Resubmit the same state name with replace:true to correct a row. Example: {\"entry\": {\"state\": \"loading\", \"owner\": \"page\", \"applicable\": true, \"expectedBehavior\": \"render loading\"}}", Type.Object({
3133
- state: Type.String({ minLength: 1 }),
3134
- owner: Type.String({ minLength: 1 }),
3135
- applicable: Type.Boolean(),
3136
- expectedBehavior: optionalString,
3137
- notApplicableReason: optionalString,
3138
- }, { additionalProperties: false }));
3139
- const frozenInteractionIds = authority.interactionIds ?? [];
3140
- const recordDataFlowTool = record("record_data_flow", "data flow", "Record one interaction data flow: source behavior group, trigger and expected behavior. One row per interaction name; resubmit the same interaction name to replace it. When a frozen interaction id vocabulary is declared, the interaction name MUST be one of the declared ids — wrong-named records are rejected at submission and stale ones are retracted via retract_data_flow. Example: {\"entry\": {\"interaction\": \"load\", \"source\": \"page\", \"trigger\": \"submit query\", \"expectedBehavior\": \"show loading then results\"}}", Type.Object({
3141
- interaction: Type.String({ minLength: 1 }),
3142
- source: Type.String({ minLength: 1 }),
3143
- trigger: Type.String({ minLength: 1 }),
3144
- expectedBehavior: Type.String({ minLength: 1 }),
3145
- }, { additionalProperties: false }), frozenInteractionIds.length > 0
3146
- ? async (entry) => {
3147
- const name = typeof entry.interaction === "string" ? entry.interaction : "";
3148
- if (name && !frozenInteractionIds.includes(name)) {
3149
- return planToolReceipt({
3150
- ok: false,
3151
- kind: "data-flow",
3152
- code: "INTERACTION_ID_NOT_DECLARED",
3153
- error: `interaction "${name}" is not in the frozen vocabulary; allowed: [${frozenInteractionIds.join(", ")}]. Submit the declared id. To remove an already-recorded wrong interaction, call retract_data_flow with {"interaction": "${name}"}.`,
3154
- });
3155
- }
3156
- return undefined;
3157
- }
3158
- : undefined);
3159
- const retractDataFlowTool = defineTool({
3160
- name: "retract_data_flow",
3161
- label: "retract data flow",
3162
- description: "Retract a previously recorded interaction data flow (e.g. one recorded under a wrong interaction id). The retracted record and every fact keyed to that interaction name stop participating in the compiled plan. Declared vocabulary ids cannot be retracted. Example: {\"interaction\": \"increment-counter\", \"reason\": \"recorded under a wrong id\"}",
3163
- promptSnippet: "Retract one interaction data flow by interaction name.",
3164
- parameters: Type.Object({
3165
- interaction: Type.String({ minLength: 1 }),
3166
- reason: Type.Optional(Type.String({ minLength: 1 })),
3167
- }, { additionalProperties: false }),
3168
- async execute(_toolCallId, params) {
3169
- const interaction = typeof params?.interaction === "string" ? params.interaction : "";
3170
- if (!interaction) {
3171
- return planToolReceipt({ ok: false, kind: "data-flow", error: "retract_data_flow requires a non-empty interaction" });
3172
- }
3173
- if (frozenInteractionIds.includes(interaction)) {
3174
- return planToolReceipt({ ok: false, kind: "data-flow", error: `interaction "${interaction}" is a declared vocabulary id and cannot be retracted` });
3175
- }
3176
- const result = await adoptDecisionFact("data-flow", `${attemptId}:retract_data_flow:${randomUUID()}`, { kind: "data-flow", origin: "plan", entry: { interaction, retracted: true, ...(typeof params?.reason === "string" ? { reason: params.reason } : {}) } });
3177
- return planToolReceipt(result);
3178
- },
3179
- });
3180
- const recordApiMockBoundaryTool = record("record_api_mock_boundary", "API/Mock boundary", "Record one API boundary and its mode (real/mock/not-needed) with evidence. The boundary is the stable identity: resubmit the same boundary with replace:true to change its mode (e.g. mock→real); the old decision is replaced, not appended. Real/mock endpoints require fixture (the test fixture path) and consumer (the implementation file that calls the API) — design policy rejects endpoints without them. Example: {\"entry\": {\"boundary\": \"GET /items\", \"mode\": \"mock\", \"evidence\": \"fixture only\", \"fixture\": \"test/fixtures/items.ts\", \"consumer\": \"src/page.tsx\"}}", Type.Object({
3181
- boundary: Type.String({ minLength: 1 }),
3182
- mode: Type.Union([Type.Literal("real"), Type.Literal("mock"), Type.Literal("not-needed")]),
3183
- evidence: Type.String({ minLength: 1 }),
3184
- fixture: optionalString,
3185
- consumer: optionalString,
3186
- }, { additionalProperties: false }), async (entry) => {
3187
- // Design policy hard-requires fixture + consumer on every derived
3188
- // endpoint (non-not-needed strategies); demand them here where the
3189
- // model can still act instead of failing the compile post-session.
3190
- if ((entry.mode === "real" || entry.mode === "mock") &&
3191
- (!(typeof entry.fixture === "string" && entry.fixture.trim()) ||
3192
- !(typeof entry.consumer === "string" && entry.consumer.trim()))) {
3193
- return planToolReceipt({
3194
- ok: false,
3195
- kind: "api-mock-boundary",
3196
- error: `record_api_mock_boundary fixture-and-consumer-required: ${entry.mode} boundary "${entry.boundary}" needs fixture (the test fixture path) and consumer (the implementation file that calls the API). Example: {"entry": {"boundary": "${entry.boundary}", "mode": "${entry.mode}", "evidence": "<why>", "fixture": "test/fixtures/items.ts", "consumer": "src/page.tsx"}}`,
3197
- });
3198
- }
3199
- return undefined;
3200
- });
3201
- const recordVerificationFocusTool = record("record_verification_focus", "verification focus", "Record one behavior-group verification focus: which test file/command proves which behavior group at what evidence level. Every behaviorGroupId must have at least one record_state_ownership row whose owner equals it — declare one UI state per behavior group before finalizing. Example: {\"entry\": {\"id\": \"VT-1\", \"behaviorGroupId\": \"page\", \"file\": \"test/page.test.tsx\", \"commandId\": \"test\", \"evidenceLevel\": \"mounted\"}}", Type.Object({
3202
- id: Type.String({ minLength: 1 }),
3203
- behaviorGroupId: Type.String({ minLength: 1 }),
3204
- file: Type.String({ minLength: 1 }),
3205
- commandId: Type.String({ minLength: 1 }),
3206
- evidenceLevel: Type.Union([Type.Literal("unit"), Type.Literal("mounted"), Type.Literal("real-integration")]),
3207
- boundary: optionalString,
3208
- }, { additionalProperties: false }), async (entry) => {
3209
- // Mirror the relationship record_plan_verification_target boundary so
3210
- // protocol errors surface in-node (bounded correction) instead of
3211
- // burning attempts on an immutable committed fact that finalize rejects.
3212
- // Duplicate/identity enforcement lives in the durable wrapper (FACT_IDENTITY_CONFLICT
3213
- // unless replace:true) and the compile collapses same-id records to the
3214
- // latest replacement, so no duplicate gate is needed here.
3215
- const verificationCommandId = typeof entry.commandId === "string" ? entry.commandId.trim() : "";
3216
- if (!verificationCommandId) {
3217
- return planToolReceipt({
3218
- ok: false,
3219
- kind: "verification-focus",
3220
- error: `record_verification_focus entry.commandId is required (received ${JSON.stringify(entry.commandId ?? null)}); pick one id from the frozen command directory in your prompt`,
3221
- });
3222
- }
3223
- const { deriveFrontendVerifyCommandDirectoryFromRun, isFrontendTestFilePath } = await import("../workflows/dag/frontend-implementation-contract.js");
3224
- const verifyDirectory = await deriveFrontendVerifyCommandDirectoryFromRun(input.runDir);
3225
- if (verifyDirectory.length > 0) {
3226
- const directoryEntry = verifyDirectory.find((candidate) => candidate.commandId === verificationCommandId);
3227
- if (!directoryEntry) {
3228
- return planToolReceipt({
3229
- ok: false,
3230
- kind: "verification-focus",
3231
- error: `record_verification_focus verification-target-unknown-command: unknown commandId "${verificationCommandId}"; available frozen commands: [${verifyDirectory.map((candidate) => `${candidate.commandId} (${candidate.mode}: ${candidate.label})`).join(", ")}]`,
3232
- });
3233
- }
3234
- if (directoryEntry.mode === "behavior" &&
3235
- typeof entry.file === "string" &&
3236
- !isFrontendTestFilePath(entry.file)) {
3237
- return planToolReceipt({
3238
- ok: false,
3239
- kind: "verification-focus",
3240
- error: `record_verification_focus verification-target-phase-mismatch: behavior command "${directoryEntry.label}" (${directoryEntry.commandId}) must bind a test file (__tests__/, tests?/, e2e/, cypress/, *.test.*, *.spec.*, *.cy.*); received file "${entry.file}"`,
3241
- });
3242
- }
3243
- }
3244
- // A behavior verification target derives its contract uiStates solely
3245
- // from the committed state-ownership rows whose owner equals its
3246
- // behaviorGroupId, and the relationship patch rejects a behavior
3247
- // target with empty uiStates whenever the plan declares any state or
3248
- // interaction. That rejection currently surfaces only in the
3249
- // post-session bridge and burns the whole attempt, so enforce the
3250
- // pairing here as a bounded in-session correction. A ledger with no
3251
- // ownership and no data-flow facts stays exempt (pure-logic plan),
3252
- // mirroring the contract-level exemption.
3253
- const committedLedger = readCommittedEvents(store, attemptId);
3254
- const ownershipRows = committedLedger.filter((event) => event.fact.kind === "state-ownership");
3255
- const hasInteractionFacts = committedLedger.some((event) => event.fact.kind === "data-flow");
3256
- if ((ownershipRows.length > 0 || hasInteractionFacts) &&
3257
- !ownershipRows.some((event) => event.fact.entry?.owner ===
3258
- entry.behaviorGroupId)) {
3259
- return planToolReceipt({
3260
- ok: false,
3261
- kind: "verification-focus",
3262
- error: `record_verification_focus undeclared-behavior-group-state: behavior group "${entry.behaviorGroupId}" (verification target ${entry.id}) has no record_state_ownership row; finalize derives each behavior target's UI states from ownership rows whose owner equals the behaviorGroupId, so record at least one for this group: {"state": "<name>", "owner": "${entry.behaviorGroupId}", "applicable": true, "expectedBehavior": "<what the state does>"}`,
3263
- });
3264
- }
3265
- return undefined;
3266
- });
3267
- const recordDependencyTool = record("record_dependency", "dependency", "Record one dependency name. Example: {\"entry\": {\"name\": \"none\"}}", Type.Object({ name: Type.String({ minLength: 1 }) }, { additionalProperties: false }));
3268
- const finalizeDecisionTool = defineTool({
3269
- name: "finalize_decision",
3270
- label: "finalize_decision",
3271
- description: "Compile the committed decision facts into a decision contract, pre-validate the derived canonical contract, and commit the terminal. Fails closed on any safety finding or validation finding; correct the reported record_* facts and call finalize_decision again.",
3272
- promptSnippet: "Compile and finalize the committed decision facts.",
3273
- parameters: Type.Object({}, { additionalProperties: false }),
3274
- async execute(_toolCallId) {
3275
- const committed = readCommittedEvents(store, attemptId);
3276
- const decision = assembleDecisionContractFromFacts(committed.map(record => record.fact));
3277
- const expectedWriteSet = [
3278
- ...decision.modulePlacements.flatMap(item => item.paths),
3279
- ...decision.verificationFocus.map(item => item.file),
3280
- ];
3281
- const derived = assembleExperimentPlanContract({
3282
- decision,
3283
- authority,
3284
- concreteWriteSet: expectedWriteSet,
3285
- });
3286
- if (derived.findings.length > 0) {
3287
- return planToolReceipt({
3288
- ok: false,
3289
- kind: "finalize_decision",
3290
- code: "DECISION_SAFETY_FINDINGS",
3291
- error: `decision safety projection failed: ${derived.findings.join("; ")}`,
3292
- });
3293
- }
3294
- const prevalidation = await prevalidateDerivedPatch();
3295
- if (!prevalidation.ok) {
3296
- return planToolReceipt({
3297
- ok: false,
3298
- kind: "finalize_decision",
3299
- code: "DECISION_PREVALIDATION_FAILED",
3300
- error: prevalidation.error,
3301
- });
3302
- }
3303
- // Recovery-mode guard: a repair child that finalizes a plan identical
3304
- // to its parent's has not performed the repair the findings demand —
3305
- // the identical plan is exactly what admission rejected. Both hashes
3306
- // use the same deterministic serializer over the canonical contract,
3307
- // so only a real semantic change passes.
3308
- // Recovery-mode guard: a repair child must demonstrably close the
3309
- // parent findings before the run re-enters design review.
3310
- if (input.parentDecisionSnapshot) {
3311
- const { readParentCanonical, parentCanonicalContentSha256 } = await import("../workflows/dag/frontend-implementation-contract.js");
3312
- const { extractRepairAssertions, evaluateRepairClosure, decisionIdentitySha256 } = await import("../workflows/dag/frontend-plan-decision-contract.js");
3313
- const parentRunDir = path.join(input.runDir, "..", input.parentDecisionSnapshot.parentRunId);
3314
- const parentCanonical = await readParentCanonical(parentRunDir);
3315
- // 1. identical-plan guard. Decisions, not prose: a rationale-only
3316
- // rewrite is not a repair (smoke r27 cleared a raw byte-hash guard
3317
- // by editing two rationale strings and changing nothing else). The
3318
- // byte hash stays as the fallback when the parent canonical cannot
3319
- // be read.
3320
- const parentSha = await parentCanonicalContentSha256(parentRunDir);
3321
- const parentDecisions = parentCanonical
3322
- ? decisionIdentitySha256(parentCanonical)
3323
- : undefined;
3324
- const childDecisions = decisionIdentitySha256(prevalidation.canonical);
3325
- if (parentDecisions
3326
- ? parentDecisions === childDecisions
3327
- : parentSha !== undefined && parentSha === prevalidation.canonicalSha256) {
3328
- return planToolReceipt({
3329
- ok: false,
3330
- kind: "finalize_decision",
3331
- code: "DECISION_REPAIR_NO_CHANGE",
3332
- error: "recovery finalize blocked: every structured decision row is identical to the parent run's (rationale-only edits do not count as a repair), but the review findings require changes. Correct the flagged rows (same identity, replace:true), then call finalize_decision again.",
3333
- });
3334
- }
3335
- // 2. per-finding closure: every deterministic assertion extracted
3336
- // from the parent findings must hold on the child canonical.
3337
- const findings = input.parentDecisionSnapshot.designFindings ?? [];
3338
- if (parentCanonical && findings.length > 0) {
3339
- const assertions = extractRepairAssertions(findings, parentCanonical);
3340
- const closure = evaluateRepairClosure(assertions, prevalidation.canonical, parentCanonical);
3341
- if (!closure.closed) {
3342
- return planToolReceipt({
3343
- ok: false,
3344
- kind: "finalize_decision",
3345
- code: "DECISION_REPAIR_NOT_CLOSED",
3346
- error: `recovery finalize blocked: ${closure.unmet.length} finding(s) are still not closed — ${closure.unmet.join("; ")}. Correct the flagged rows (same identity, replace:true), then call finalize_decision again.`,
3347
- });
3348
- }
3349
- }
3350
- }
3351
- const result = await adoptDecisionFact("finalize_decision", `${attemptId}:finalize_decision:${randomUUID()}`, { kind: "finalize_decision", origin: "plan", findings: [] });
3352
- return planToolReceipt(result);
3353
- },
3354
- });
3355
- const durable = await createDurableFrontendTools({
3356
- file: path.join(input.runDir, input.nodeId, "plan-decision-facts.jsonl"),
3357
- attemptId,
3358
- store: input.store,
3359
- setWorkingStore: next => { store = next; },
3360
- binding: { authority },
3361
- tools: [
3362
- recordModulePlacementTool,
3363
- recordReuseDecisionTool,
3364
- recordStateOwnershipTool,
3365
- recordDataFlowTool,
3366
- retractDataFlowTool,
3367
- recordApiMockBoundaryTool,
3368
- recordVerificationFocusTool,
3369
- recordDependencyTool,
3370
- finalizeDecisionTool,
3371
- ],
3372
- });
3373
- const durableFinalizeDecisionTool = durable.customTools.find((tool) => typeof tool === "object" && tool !== null && tool.name === "finalize_decision");
3374
- if (!durableFinalizeDecisionTool)
3375
- throw new Error("frontend plan decision durable finalize tool unavailable");
3376
- return {
3377
- customTools: durable.customTools,
3378
- flush: durable.flush,
3379
- committedFacts: () => readCommittedEvents(store, attemptId),
3380
- finalizeDecision: () => durableFinalizeDecisionTool.execute(`${attemptId}:auto-finalize-decision`, {}, undefined, undefined, {}),
3381
- };
3382
- }
3383
- /**
3384
- * Decision → relationship bridge: after a successful decision `finalize`
3385
- * (kind finalize_decision committed in plan-decision-facts.jsonl) the plan
3386
- * node ALSO publishes the relationship-shaped plan ledger
3387
- * (`<runDir>/<nodeId>/plan-typed-facts.jsonl`) carrying a committed
3388
- * `target-surface` patch fact + a `finalize_plan` terminal fact derived from
3389
- * the committed decision facts. The unchanged R1 self-check
3390
- * (`validateFrontendPlanPatchNodeOutput`) and every downstream shell
3391
- * (`buildContractFromCommittedFacts`) read ONLY that ledger, so without this
3392
- * bridge every decision run fails deterministically with "frontend plan
3393
- * ledger missing" → invalid-output on all attempts.
3394
- *
3395
- * The patch is compiled by `buildFrontendPlanRelationshipPatch` and front-loads
3396
- * the exact validation the relationship finalize receipt runs (merge onto the
3397
- * runtime skeleton + analyzeFrontendPlanPatchCandidate). When the derived
3398
- * canonical fails, this returns a fixable error and the executor turns it into
3399
- * an invalid-output so the node retry ladder restarts the session with the
3400
- * diagnostics instead of writing a ledger that R1 would reject.
3401
- */
3402
- export async function bridgeFrontendPlanDecisionToRelationshipLedger(input) {
3403
- const { assembleDecisionContractFromFacts, buildFrontendPlanRelationshipPatch, } = await import("../workflows/dag/frontend-plan-decision-contract.js");
3404
- const committed = input.facts
3405
- .filter(record => record.phase === "committed")
3406
- .map(record => record.fact);
3407
- const decision = assembleDecisionContractFromFacts(committed);
3408
- const concreteWriteSet = [
3409
- ...new Set([
3410
- ...decision.modulePlacements.flatMap(item => item.paths),
3411
- ...decision.verificationFocus.map(item => item.file),
3412
- ]),
3413
- ];
3414
- // Contract-declared deliverable obligations (the same ledger the analyzer
3415
- // extracts `requiredDeliverables` from): bind each path to its requirement
3416
- // so the derived canonical contract plans every contract-mandated file.
3417
- const requiredDeliverables = new Map();
3418
- try {
3419
- const contractRecords = await readTypedEventStoreFromJsonl(path.join(input.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
3420
- for (const record of [...contractRecords].reverse()) {
3421
- const fact = record.fact;
3422
- if (!fact || fact.origin !== "contract" || fact.kind !== "required-deliverables")
3423
- continue;
3424
- for (const item of Array.isArray(fact.items) ? fact.items : []) {
3425
- if (!item || typeof item !== "object" || Array.isArray(item))
3426
- continue;
3427
- const requirementId = item.requirementId;
3428
- const file = item.path;
3429
- if (typeof requirementId !== "string" || typeof file !== "string")
3430
- continue;
3431
- const paths = requiredDeliverables.get(requirementId) ?? [];
3432
- paths.push(file);
3433
- requiredDeliverables.set(requirementId, paths);
3434
- }
3435
- break;
2564
+ break;
3436
2565
  }
3437
2566
  }
3438
2567
  catch {
@@ -3488,515 +2617,6 @@ export async function bridgeFrontendPlanDecisionToRelationshipLedger(input) {
3488
2617
  await writeTypedEventStoreJsonl(file, store.records.filter(record => record.phase === "committed"));
3489
2618
  return { ok: true, patch };
3490
2619
  }
3491
- function isRecordObject(value) {
3492
- return typeof value === "object" && value !== null && !Array.isArray(value);
3493
- }
3494
- /** A contract fact is source-mapped when it carries a non-empty `sourceSpan`
3495
- * (object or string), a non-empty `sourceRefs` array, or a non-empty `source`
3496
- * string. Anything else is an unmapped source segment (AC-001). */
3497
- function contractFactSourceSpan(fact) {
3498
- if (isRecordObject(fact.sourceSpan) || typeof fact.sourceSpan === "string") {
3499
- return fact.sourceSpan;
3500
- }
3501
- if (Array.isArray(fact.sourceRefs) && fact.sourceRefs.length > 0) {
3502
- return fact.sourceRefs;
3503
- }
3504
- if (Array.isArray(fact.sourceFragmentIds) &&
3505
- fact.sourceFragmentIds.some((value) => typeof value === "string" && value.trim().length > 0)) {
3506
- return fact.sourceFragmentIds;
3507
- }
3508
- if (typeof fact.source === "string" && fact.source.trim().length > 0) {
3509
- return fact.source;
3510
- }
3511
- return undefined;
3512
- }
3513
- /**
3514
- * A+B (AC-001): deterministically assemble the read-only `frontend-task-contract-vNext`
3515
- * audit artifact from committed contract facts. It never rewrites the original
3516
- * task source: unmapped requirement/constraint segments are listed explicitly
3517
- * so Plan/Implement/Review keep binding to the raw source, not the model's
3518
- * summarized contract. The blocked disposition is projected through the frozen
3519
- * `mapContractBlockedOwner` mapping (AC-002).
3520
- */
3521
- export function buildFrontendTaskContractVNext(records) {
3522
- const facts = records
3523
- .filter((record) => record.phase === "committed")
3524
- .map((record) => record.fact)
3525
- .filter(isRecordObject);
3526
- const finalized = facts.find((fact) => fact.kind === "contract-finalized");
3527
- const disposition = typeof finalized?.disposition === "string" ? finalized.disposition : null;
3528
- const blockingOwner = typeof finalized?.blockingOwner === "string"
3529
- ? finalized.blockingOwner
3530
- : null;
3531
- const projected = mapContractBlockedOwner({
3532
- disposition: disposition ?? "",
3533
- blockingOwner: blockingOwner ?? undefined,
3534
- });
3535
- const byKind = (kind) => facts.filter((fact) => fact.kind === kind);
3536
- const requirements = byKind("requirement");
3537
- const unmappedSourceSegments = requirements
3538
- .filter((fact) => contractFactSourceSpan(fact) === undefined)
3539
- .map((fact) => ({
3540
- kind: "requirement",
3541
- id: typeof fact.id === "string"
3542
- ? fact.id
3543
- : typeof fact.text === "string"
3544
- ? fact.text
3545
- : undefined,
3546
- }))
3547
- .filter((segment) => segment.id !== undefined);
3548
- return {
3549
- schemaVersion: 1,
3550
- schemaId: "frontend-task-contract-vNext",
3551
- disposition,
3552
- blockingOwner,
3553
- blockedOwner: projected === "not-blocked" ? null : projected,
3554
- requirements,
3555
- constraints: byKind("constraint"),
3556
- evidenceExpectations: byKind("evidence-expectation"),
3557
- deliverableDeclarations: byKind("required-deliverables").at(-1)?.items ?? [],
3558
- handoffIntents: byKind("handoff-intent"),
3559
- openQuestions: byKind("open-question"),
3560
- splitProposals: byKind("split-proposal"),
3561
- unmappedSourceSegments,
3562
- };
3563
- }
3564
- /**
3565
- * A+B: `frontend-contract-pi` incremental contract tools. The `record_*` tools
3566
- * commit origin=contract facts and `finalize_contract` commits the terminal
3567
- * disposition (ready | ready-with-assumptions | blocked + blockingOwner).
3568
- */
3569
- export async function createFrontendContractTools(input) {
3570
- const [{ Type }, { defineTool }] = await Promise.all([
3571
- import("typebox"),
3572
- import("@earendil-works/pi-coding-agent"),
3573
- ]);
3574
- const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
3575
- const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
3576
- let store = input.store;
3577
- const attemptId = input.attemptId;
3578
- let activeScope = null;
3579
- const committedRequirementIds = () => new Set(readCommittedEvents(store, attemptId).filter(r => r.fact.kind === "requirement").map(r => String(r.fact.id)));
3580
- const completedScopeRequirementIds = () => new Set(readCommittedEvents(store, attemptId).filter(r => r.fact.kind === "contract-scope-completed").flatMap(r => Array.isArray(r.fact.requirementIds) ? r.fact.requirementIds.filter((id) => typeof id === "string") : []));
3581
- const receipt = (details) => ({
3582
- content: [{ type: "text", text: JSON.stringify(details) }],
3583
- details,
3584
- });
3585
- async function adoptContractFact(kind, fact) {
3586
- try {
3587
- const requestId = `${attemptId}:${kind}:${randomUUID()}`;
3588
- const staged = stageTypedEventFact({
3589
- store,
3590
- requestId,
3591
- attemptId,
3592
- fact: fact,
3593
- });
3594
- const committed = await adoptTypedEventFact({
3595
- store,
3596
- requestId,
3597
- attemptId,
3598
- fact: fact,
3599
- eventId: staged.eventId,
3600
- expectedRevision: store.revision,
3601
- });
3602
- return {
3603
- ok: true,
3604
- kind,
3605
- eventId: committed.eventId,
3606
- revision: committed.revision,
3607
- error: "",
3608
- };
3609
- }
3610
- catch (error) {
3611
- return {
3612
- ok: false,
3613
- kind,
3614
- code: error?.code,
3615
- error: error instanceof Error ? error.message : String(error),
3616
- };
3617
- }
3618
- }
3619
- const recordKinds = {
3620
- record_constraint: "constraint",
3621
- record_handoff_intent: "handoff-intent",
3622
- record_open_question: "open-question",
3623
- record_split_proposal: "split-proposal",
3624
- };
3625
- const recordTools = Object.entries(recordKinds).map(([name, kind]) => defineTool({
3626
- name,
3627
- label: name,
3628
- description: `Commit an origin=contract ${kind} fact. IMPORTANT: submit incrementally — batch up to 5 record_* calls per message, starting from the FIRST message; never attempt to emit the whole contract in one response (a single large dump will be truncated and rejected). Every message must make progress by committing at least one record_* fact.`,
3629
- promptSnippet: `Commit 1-5 origin=contract ${kind} facts (up to 5 per message).`,
3630
- parameters: Type.Object({
3631
- text: Type.String({ minLength: 1 }),
3632
- requirementIds: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
3633
- sourceFragmentIds: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
3634
- ...(kind === "constraint" ? { category: Type.Optional(Type.Enum({ constraint: "constraint", "non-goal": "non-goal", risk: "risk" })) } : {}),
3635
- ...(kind === "handoff-intent" ? { taskKind: Type.Literal("frontend-test"), blocking: Type.Optional(Type.Boolean()) } : {}),
3636
- }, { additionalProperties: false }),
3637
- async execute(_toolCallId, params) {
3638
- const data = params;
3639
- if (!data.text?.trim())
3640
- return receipt({ ok: false, code: "TOOL_SCHEMA_INVALID", error: `${name}: text must be non-empty` });
3641
- const knownFragments = new Set([...(input.canonicalRequirements?.values() ?? [])].flatMap(r => r.sourceFragmentIds));
3642
- if (data.requirementIds?.some(id => !input.canonicalRequirements?.has(id)) || data.sourceFragmentIds?.some(id => !knownFragments.has(id)))
3643
- return receipt({ ok: false, code: "CONTRACT_REFERENCE_UNKNOWN", error: `${name}: reference is outside the frozen source inventory` });
3644
- const result = await adoptContractFact(kind, {
3645
- ...(params ?? {}),
3646
- kind,
3647
- origin: "contract",
3648
- });
3649
- return receipt(result);
3650
- },
3651
- }));
3652
- // record_requirement is runtime-owned by design: the requirement TEXT and
3653
- // sourceFragmentIds come from the frozen source-fidelity ledger, never from
3654
- // model-authored prose. The model only names the canonical id it confirms.
3655
- // This closes the free-shape hole (additionalProperties:true accepted
3656
- // `statement` rewrites and JSON-stringified `sourceFragmentIds` arrays,
3657
- // which then reached the planner as empty text + dead fragment bindings).
3658
- const recordRequirementTool = defineTool({
3659
- name: "record_requirement",
3660
- label: "record_requirement",
3661
- description: 'Confirm one canonical ledger requirement (origin=contract requirement fact). Pass the canonical id and optional execution:{groupId,kind,summary} only. Reuse a group only when its behavior and all permission/threshold/error conditions agree; retain separate groups for differences. Constraints/exclusions do not require invented UI. The canonical id is listed in the <frontend_contract_input> inventory, e.g. {"id": "AC-001"} — the runtime commits the authoritative text and sourceFragmentIds from the frozen ledger. Never pass text/statement/sourceFragmentIds yourself: free-form rewrites and JSON-stringified fragment arrays are rejected. IMPORTANT: batch up to 5 record_* calls per message, starting from the FIRST message.',
3662
- promptSnippet: "Confirm 1-5 canonical requirements by id (up to 5 per message).",
3663
- parameters: Type.Object({ id: Type.String({ description: "Canonical ledger requirement id (e.g. AC-001)" }), execution: Type.Optional(Type.Object({ groupId: Type.String({ minLength: 1 }), kind: Type.Union([Type.Literal("behavior"), Type.Literal("constraint"), Type.Literal("exclusion")]), summary: Type.String({ minLength: 1 }) }, { additionalProperties: false })) }, { additionalProperties: false }),
3664
- async execute(_toolCallId, params) {
3665
- const id = typeof params?.id === "string" ? params.id.trim() : "";
3666
- if (!id) {
3667
- return receipt({
3668
- ok: false,
3669
- kind: "requirement",
3670
- error: "record_requirement requires the canonical requirement id",
3671
- });
3672
- }
3673
- if (activeScope && !activeScope.has(id))
3674
- return receipt({ ok: false, code: "FRONTEND_INPUT_SCOPE_VIOLATION", error: `requirement ${id} is outside the complete input scope of this session` });
3675
- const canonical = input.canonicalRequirements?.get(id);
3676
- if (!canonical) {
3677
- const known = [...(input.canonicalRequirements?.keys() ?? [])];
3678
- return receipt({
3679
- ok: false,
3680
- kind: "requirement",
3681
- error: `record_requirement id "${id}" is not a canonical ledger requirement; canonical ids are: ${known.join(", ") || "(none)"}`,
3682
- });
3683
- }
3684
- if (params.execution) {
3685
- try {
3686
- collectFrontendExecutionGroups([...readCommittedEvents(store, attemptId).filter(r => r.fact.kind === "requirement" && r.fact.id !== id).map(r => ({ id: String(r.fact.id), execution: r.fact.execution })), { id, execution: params.execution }]);
3687
- }
3688
- catch (error) {
3689
- return receipt({ ok: false, code: "EXECUTION_GROUP_CONFLICT", error: String(error) });
3690
- }
3691
- }
3692
- const result = await adoptContractFact("requirement", {
3693
- kind: "requirement",
3694
- origin: "contract",
3695
- disposition: "explicit",
3696
- id,
3697
- text: canonical.text,
3698
- sourceFragmentIds: canonical.sourceFragmentIds,
3699
- ...(params.execution ? { execution: params.execution } : {}),
3700
- });
3701
- return receipt(result);
3702
- },
3703
- });
3704
- // Requirement identity/text/source are runtime-owned and seeded before the
3705
- // model starts. Execution grouping is still a model decision, so expose it
3706
- // as a small typed update instead of forcing the model to re-submit the same
3707
- // requirement just to attach execution metadata.
3708
- const recordRequirementExecutionTool = defineTool({
3709
- name: "record_requirement_execution",
3710
- label: "record_requirement_execution",
3711
- description: "Attach execution ownership to already-confirmed canonical requirements.",
3712
- promptSnippet: "Record execution group metadata for confirmed requirements.",
3713
- parameters: Type.Object({
3714
- requirementIds: Type.Array(Type.String({ minLength: 1 }), { minItems: 1, uniqueItems: true }),
3715
- execution: Type.Object({
3716
- groupId: Type.String({ minLength: 1 }),
3717
- kind: Type.Union([Type.Literal("behavior"), Type.Literal("constraint"), Type.Literal("exclusion")]),
3718
- summary: Type.String({ minLength: 1 }),
3719
- }, { additionalProperties: false }),
3720
- }, { additionalProperties: false }),
3721
- async execute(callId, params) {
3722
- const ids = params.requirementIds;
3723
- if (activeScope && ids.some((id) => !activeScope?.has(id)))
3724
- return receipt({ ok: false, code: "FRONTEND_INPUT_SCOPE_VIOLATION", error: "execution metadata references a requirement outside the active contract scope" });
3725
- const canonical = input.canonicalRequirements;
3726
- const unknown = ids.filter((id) => !canonical?.has(id));
3727
- if (unknown.length > 0)
3728
- return receipt({ ok: false, code: "CONTRACT_REFERENCE_UNKNOWN", error: `record_requirement_execution references unknown canonical requirements: ${unknown.join(", ")}` });
3729
- const execution = frontendExecutionSchema.parse(params.execution);
3730
- const existing = readCommittedEvents(store, attemptId)
3731
- .filter((record) => record.fact.kind === "requirement")
3732
- .map((record) => ({ id: String(record.fact.id), execution: record.fact.execution }))
3733
- .filter((unit) => !ids.includes(unit.id));
3734
- try {
3735
- collectFrontendExecutionGroups([...existing, ...ids.map((id) => ({ id, execution }))]);
3736
- }
3737
- catch (error) {
3738
- return receipt({ ok: false, code: "EXECUTION_GROUP_CONFLICT", error: error instanceof Error ? error.message : String(error) });
3739
- }
3740
- let result = { ok: true };
3741
- for (const id of ids) {
3742
- const requirement = canonical.get(id);
3743
- result = await adoptContractFact("requirement", { kind: "requirement", origin: "contract", disposition: "explicit", id, text: requirement.text, sourceFragmentIds: requirement.sourceFragmentIds, execution });
3744
- if (result.ok !== true)
3745
- return receipt(result);
3746
- }
3747
- return receipt({ ...result, requestId: callId });
3748
- },
3749
- });
3750
- // Authoritative UI state declarations: the contract node extracts the
3751
- // PRD/reference UI-state table into structured facts so the planner binds
3752
- // uiStates to declared ids instead of inventing names (dogfood
3753
- // dag-1788504923861-0f7b17a9: 10 invented list-visibility variants, 0 of
3754
- // the 7 PRD states).
3755
- const recordUiStateTool = defineTool({
3756
- name: "record_ui_state",
3757
- label: "record_ui_state",
3758
- description: 'Declare ONE authoritative UI state extracted from the task source\'s UI-state table (origin=contract ui-state-declaration fact). Call once per declared state, exactly as the source names it: {"id": "<state id from the source table>", "trigger": "<when this state applies>", "observableOutcome": "<what the user can observe>"}. The planner must bind these ids later; do not rename or invent states.',
3759
- promptSnippet: "Declare 1-5 authoritative UI states (up to 5 per message).",
3760
- parameters: Type.Object({
3761
- id: Type.String({ description: "UI state id exactly as the source table declares it" }),
3762
- trigger: Type.String({ description: "When this state applies" }),
3763
- observableOutcome: Type.String({ description: "Observable result for the user" }),
3764
- }, { additionalProperties: false }),
3765
- async execute(_toolCallId, params) {
3766
- const id = typeof params?.id === "string" ? params.id.trim() : "";
3767
- const trigger = typeof params?.trigger === "string" ? params.trigger.trim() : "";
3768
- const observableOutcome = typeof params?.observableOutcome === "string"
3769
- ? params.observableOutcome.trim()
3770
- : "";
3771
- if (!id || !trigger || !observableOutcome) {
3772
- return receipt({
3773
- ok: false,
3774
- kind: "ui-state-declaration",
3775
- error: "record_ui_state requires non-empty id, trigger, and observableOutcome",
3776
- });
3777
- }
3778
- const result = await adoptContractFact("ui-state-declaration", {
3779
- kind: "ui-state-declaration",
3780
- origin: "contract",
3781
- id,
3782
- trigger,
3783
- observableOutcome,
3784
- });
3785
- return receipt(result);
3786
- },
3787
- });
3788
- const evidenceStatus = Type.Enum({
3789
- required: "required", optional: "optional", "not-applicable": "not-applicable",
3790
- });
3791
- const recordEvidenceExpectationTool = defineTool({
3792
- name: "record_evidence_expectation",
3793
- label: "record_evidence_expectation",
3794
- description: 'Record evidence requirements as {requirementId:"<canonical id>",evidence:{static:"required|optional|not-applicable",behavior:"required|optional|not-applicable",mock:"required|optional|not-applicable","real-integration":"required|optional|not-applicable"}}. Declare at least one lane; later calls replace only the lanes they name.',
3795
- parameters: Type.Object({
3796
- requirementId: Type.String(),
3797
- evidence: Type.Object({
3798
- static: Type.Optional(evidenceStatus),
3799
- behavior: Type.Optional(evidenceStatus),
3800
- mock: Type.Optional(evidenceStatus),
3801
- "real-integration": Type.Optional(evidenceStatus),
3802
- }, { additionalProperties: false }),
3803
- }, { additionalProperties: false }),
3804
- async execute(_toolCallId, params) {
3805
- try {
3806
- const fact = frontendEvidenceExpectationSchema.parse(params);
3807
- if (!input.canonicalRequirements?.has(fact.requirementId)) {
3808
- throw new Error(`unknown canonical requirement ${fact.requirementId}`);
3809
- }
3810
- return receipt(await adoptContractFact("evidence-expectation", {
3811
- kind: "evidence-expectation", origin: "contract", ...fact,
3812
- }));
3813
- }
3814
- catch (error) {
3815
- return receipt({
3816
- ok: false, kind: "evidence-expectation",
3817
- error: error instanceof Error ? error.message : String(error),
3818
- });
3819
- }
3820
- },
3821
- });
3822
- const recordRequiredDeliverablesTool = defineTool({
3823
- name: "record_required_deliverables",
3824
- label: "record_required_deliverables",
3825
- description: 'Declare the complete source-required file deliverables as {items:[{path,requirementId,sourceFragmentId}]}. Interpret obligations from the original source, including lists/tables: permissions (allowedPaths/only allowed to modify), prohibitions, examples and read-only references are NOT delivery obligations. Each path must appear exactly in its frozen requirement-bound source fragment. Submit {items:[]} explicitly if no files are mandatory. Each call appends complete source-bound items; replace:true explicitly replaces the inventory. Required before finalize_contract ready.',
3826
- parameters: Type.Object({ replace: Type.Optional(Type.Boolean()), items: Type.Array(Type.Object({
3827
- path: Type.String(), requirementId: Type.String(), sourceFragmentId: Type.String(),
3828
- }, { additionalProperties: false })) }, { additionalProperties: false }),
3829
- async execute(_toolCallId, params) {
3830
- try {
3831
- const declaration = validateFrontendRequiredDeliverables({ items: params.items }, input.canonicalRequirements ?? new Map());
3832
- const previous = params.replace ? [] : readCommittedEvents(store, attemptId).filter(r => r.fact.kind === "required-deliverables").at(-1)?.fact.items;
3833
- const items = [...new Map([...(Array.isArray(previous) ? previous : []), ...declaration.items].map(item => [JSON.stringify(item), item])).values()];
3834
- return receipt(await adoptContractFact("required-deliverables", {
3835
- kind: "required-deliverables", origin: "contract", items,
3836
- }));
3837
- }
3838
- catch (error) {
3839
- return receipt({
3840
- ok: false, kind: "required-deliverables",
3841
- error: error instanceof Error ? error.message : String(error),
3842
- });
3843
- }
3844
- },
3845
- });
3846
- // OpenSpec selection committed as individual typed facts (one path per
3847
- // call) so a large candidate set never exceeds a single model output
3848
- // budget: each tool call carries exactly one {path, disposition,
3849
- // rationale} row and the ledger accumulates them across calls. Only
3850
- // positive classifications (required | relevant) are legal; unmentioned
3851
- // candidates default to irrelevant at the prewrite gate.
3852
- const recordOpenspecSelectionTool = defineTool({
3853
- name: "record_openspec_selection",
3854
- label: "record_openspec_selection",
3855
- description: "Commit one OpenSpec candidate classification (origin=contract openspec-selection fact). Call once per path you actually use or consult: required (must be read and cited) or relevant (informs planning). Never call it for irrelevant candidates — unmentioned candidates default to irrelevant. You may call it many times; one row per call.",
3856
- promptSnippet: "Commit one OpenSpec candidate classification (required | relevant); one path per call; skip irrelevant candidates.",
3857
- parameters: Type.Object({
3858
- path: Type.String({
3859
- description: "Repo-relative candidate spec path, e.g. openspec/project-specs/ui/ucp-components-md/AdvancedSearch.md",
3860
- }),
3861
- disposition: Type.Enum({
3862
- required: "required",
3863
- relevant: "relevant",
3864
- }),
3865
- rationale: Type.String({}),
3866
- }, { additionalProperties: false }),
3867
- async execute(_toolCallId, params) {
3868
- const path = typeof params?.path === "string" ? params.path : "";
3869
- const disposition = params?.disposition;
3870
- const rationale = typeof params?.rationale === "string" ? params.rationale : "";
3871
- if (!path || !disposition || !rationale.trim()) {
3872
- return receipt({
3873
- ok: false,
3874
- kind: "openspec-selection",
3875
- error: "record_openspec_selection requires non-empty path, disposition (required|relevant), and rationale",
3876
- });
3877
- }
3878
- const result = await adoptContractFact("openspec-selection", {
3879
- kind: "openspec-selection",
3880
- origin: "contract",
3881
- path,
3882
- disposition,
3883
- rationale,
3884
- });
3885
- return receipt(result);
3886
- },
3887
- });
3888
- const finalizeContractTool = defineTool({
3889
- name: "finalize_contract",
3890
- label: "finalize_contract",
3891
- description: "Commit the contract-finalized terminal fact with a disposition of ready | ready-with-assumptions | blocked (blocked requires blockingOwner). A successful terminal commit occurs exactly once. If validation fails, correct only the reported facts and retry finalize.",
3892
- promptSnippet: "Commit the contract-finalized terminal (disposition + optional blockingOwner).",
3893
- parameters: Type.Object({
3894
- disposition: Type.Enum({
3895
- ready: "ready",
3896
- "ready-with-assumptions": "ready-with-assumptions",
3897
- blocked: "blocked",
3898
- }),
3899
- blockingOwner: Type.Optional(Type.Enum({
3900
- "blocked-human": "blocked-human",
3901
- "blocked-external": "blocked-external",
3902
- })),
3903
- assumptions: Type.Optional(Type.Array(Type.String({}))),
3904
- summary: Type.Optional(Type.String({})),
3905
- }, { additionalProperties: false }),
3906
- async execute(_toolCallId, params) {
3907
- const disposition = params?.disposition;
3908
- const blockingOwner = params?.blockingOwner;
3909
- if (disposition === "blocked" && !blockingOwner) {
3910
- return receipt({
3911
- ok: false,
3912
- kind: "finalize_contract",
3913
- error: "blocked disposition requires blockingOwner (blocked-human | blocked-external)",
3914
- });
3915
- }
3916
- if (disposition !== "blocked" && input.canonicalRequirements?.size &&
3917
- !readCommittedEvents(store, attemptId).some((record) => record.fact.kind === "required-deliverables")) {
3918
- return receipt({
3919
- ok: false, kind: "finalize_contract",
3920
- error: "call record_required_deliverables with the complete source-bound inventory (or items:[] when none) before finalizing",
3921
- });
3922
- }
3923
- const missing = [...(input.canonicalRequirements?.keys() ?? [])].filter(id => !committedRequirementIds().has(id) || (activeScope !== null && !completedScopeRequirementIds().has(id)));
3924
- if (disposition !== "blocked" && missing.length)
3925
- return receipt({ ok: false, code: "CONTRACT_REQUIREMENT_COVERAGE_MISSING", error: `Confirm all complete source obligations before finalizing: ${missing.join(", ")}` });
3926
- const blockedOwner = mapContractBlockedOwner({
3927
- disposition: disposition ?? "",
3928
- blockingOwner,
3929
- });
3930
- const result = await adoptContractFact("contract-finalized", {
3931
- kind: "contract-finalized",
3932
- origin: "contract",
3933
- disposition,
3934
- ...(blockingOwner ? { blockingOwner } : {}),
3935
- ...(blockedOwner !== "not-blocked" ? { blockedOwner } : {}),
3936
- ...(Array.isArray(params?.assumptions)
3937
- ? { assumptions: params.assumptions }
3938
- : {}),
3939
- ...(typeof params?.summary === "string"
3940
- ? { summary: params.summary }
3941
- : {}),
3942
- });
3943
- return receipt(result);
3944
- },
3945
- });
3946
- const completeScopeTool = defineTool({
3947
- name: "complete_contract_scope", label: "complete_contract_scope",
3948
- description: "After recording all requirements AND their evidence, constraints, questions and deliverables for this session, mark the scope complete. Confirming an ID alone does not complete its analysis. Do this before finalize_contract.",
3949
- parameters: Type.Object({ requirementIds: Type.Array(Type.String({ minLength: 1 }), { uniqueItems: true }) }, { additionalProperties: false }),
3950
- async execute(_id, params) {
3951
- const ids = params.requirementIds;
3952
- if (activeScope === null || ids.length !== activeScope.size || ids.some(id => !activeScope?.has(id) || !committedRequirementIds().has(id)))
3953
- return receipt({ ok: false, code: "CONTRACT_SCOPE_INCOMPLETE", error: "Complete exactly the active scope after confirming all its obligations" });
3954
- return receipt(await adoptContractFact("contract-scope-completed", { kind: "contract-scope-completed", origin: "contract", requirementIds: ids }));
3955
- },
3956
- });
3957
- const durable = await createDurableFrontendTools({
3958
- file: path.join(input.runDir, input.nodeId, "contract-typed-facts.jsonl"), attemptId, store: input.store,
3959
- setWorkingStore: next => { store = next; }, binding: { canonicalRequirements: input.canonicalRequirements, sourceDigest: input.sourceDigest },
3960
- tools: [
3961
- ...recordTools,
3962
- recordRequirementTool,
3963
- recordRequirementExecutionTool,
3964
- recordEvidenceExpectationTool,
3965
- recordUiStateTool,
3966
- recordRequiredDeliverablesTool,
3967
- recordOpenspecSelectionTool,
3968
- completeScopeTool,
3969
- finalizeContractTool,
3970
- ],
3971
- });
3972
- const durableRecordRequirementTool = durable.customTools.find((tool) => typeof tool === "object" && tool !== null && tool.name === "record_requirement");
3973
- if (!durableRecordRequirementTool)
3974
- throw new Error("frontend contract durable requirement tool unavailable");
3975
- return {
3976
- customTools: durable.customTools,
3977
- inputRequirements: () => [...(input.canonicalRequirements ?? [])].map(([id, value]) => ({ id, text: value.text, sourceFragmentIds: [...value.sourceFragmentIds] })),
3978
- seedCanonicalRequirements: async () => {
3979
- for (const id of input.canonicalRequirements?.keys() ?? []) {
3980
- if (committedRequirementIds().has(id))
3981
- continue;
3982
- const receipt = await durableRecordRequirementTool.execute(`${attemptId}:seed-requirement:${id}`, { id }, undefined, undefined, {});
3983
- if (receipt.details?.ok !== true) {
3984
- throw new Error(`runtime requirement seed rejected for ${id}`);
3985
- }
3986
- }
3987
- await durable.flush();
3988
- },
3989
- completedScopeRequirementIds,
3990
- setActiveRequirementScope: ids => { activeScope = ids === null ? null : new Set(ids); },
3991
- committedRequirementIds,
3992
- committedFacts: () => readCommittedEvents(input.store, attemptId),
3993
- flush: async () => {
3994
- await durable.flush();
3995
- const committed = readCommittedEvents(input.store, attemptId);
3996
- await writeJsonAtomic(path.join(input.runDir, input.nodeId, "frontend-task-contract-vNext.json"), buildFrontendTaskContractVNext(committed));
3997
- },
3998
- };
3999
- }
4000
2620
  async function resolveFrontendScoutSourceDeclaredPaths(input) {
4001
2621
  const binding = input.spec.sourceBinding;
4002
2622
  if (!binding?.sources?.length)
@@ -4032,270 +2652,6 @@ async function resolveFrontendScoutSourceDeclaredPaths(input) {
4032
2652
  }
4033
2653
  return [...declared].sort();
4034
2654
  }
4035
- /**
4036
- * A+B: `frontend-scout-pi` incremental evidence tools (origin=scout). Runtime
4037
- * enriches committed target-surface / design-evidence facts with hash/section/
4038
- * freshness from real read events; the tool itself never trusts model self-report.
4039
- */
4040
- export async function createFrontendScoutEvidenceTools(input) {
4041
- const [{ Type }, { defineTool }] = await Promise.all([
4042
- import("typebox"),
4043
- import("@earendil-works/pi-coding-agent"),
4044
- ]);
4045
- const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
4046
- const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
4047
- let store = input.store;
4048
- const attemptId = input.attemptId;
4049
- const stringArray = Type.Array(Type.String({}));
4050
- const optionalString = Type.Optional(Type.String({}));
4051
- const scoutCompleteness = Type.Union([
4052
- Type.Literal("complete"),
4053
- Type.Literal("blocked"),
4054
- ]);
4055
- const receipt = (details) => ({
4056
- content: [{ type: "text", text: JSON.stringify(details) }],
4057
- details,
4058
- });
4059
- const sourceDeclaredPaths = (input.sourceDeclaredPaths ?? []).map((value) => value.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, ""));
4060
- const hasSourceDeclarations = input.sourceDeclaredPaths !== undefined;
4061
- let activeScope;
4062
- const scopeIdentity = (ids) => createHash("sha256").update(JSON.stringify([...ids].sort())).digest("hex");
4063
- const latestScopes = () => {
4064
- const byRequirement = new Map();
4065
- for (const record of readCommittedEvents(store, attemptId))
4066
- if (record.fact.kind === "scout-scope" && Array.isArray(record.fact.requirementIds)) {
4067
- for (const id of record.fact.requirementIds)
4068
- if (typeof id === "string")
4069
- byRequirement.set(id, record.fact);
4070
- }
4071
- return byRequirement;
4072
- };
4073
- const isSourceDeclared = (candidate) => {
4074
- const normalized = candidate.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, "");
4075
- return sourceDeclaredPaths.some((declared) => declared === normalized || declared.startsWith(`${normalized}/`));
4076
- };
4077
- // A+B (AC-003): runtime enriches declared scout paths with hash/freshness
4078
- // from the real filesystem. The model's self-reported path list is never
4079
- // trusted for content identity; a missing file fails closed to fresh=false
4080
- // with a zero hash instead of inventing content.
4081
- const enrichScoutPathEvidence = async (paths) => {
4082
- if (!input.workspaceRoot)
4083
- return [];
4084
- const workspaceRoot = path.resolve(input.workspaceRoot);
4085
- const evidence = [];
4086
- for (const relative of new Set(paths)) {
4087
- const absolute = path.resolve(workspaceRoot, relative);
4088
- if (absolute !== workspaceRoot &&
4089
- !absolute.startsWith(`${workspaceRoot}${path.sep}`)) {
4090
- evidence.push({ path: relative, sha256: "0".repeat(64), fresh: false, sourceDeclared: isSourceDeclared(relative) });
4091
- continue;
4092
- }
4093
- try {
4094
- // Directories are legitimate named targets (greenfield smoke: the
4095
- // page directory exists while the files inside it are to be
4096
- // created). readFile on a directory throws EISDIR, which used to
4097
- // mark every directory path fresh=false and structurally fail the
4098
- // freshness gate for create-new surfaces. stat() first: a directory
4099
- // counts as fresh existence evidence; its content hash is a stable
4100
- // directory marker since there is no single file content to hash.
4101
- const info = await stat(absolute);
4102
- if (info.isDirectory()) {
4103
- evidence.push({
4104
- path: relative,
4105
- sha256: createHash("sha256").update(`directory:${relative}`).digest("hex"),
4106
- fresh: true,
4107
- sourceDeclared: isSourceDeclared(relative),
4108
- });
4109
- continue;
4110
- }
4111
- const bytes = await readFile(absolute);
4112
- evidence.push({
4113
- path: relative,
4114
- sha256: createHash("sha256").update(bytes).digest("hex"),
4115
- fresh: true,
4116
- sourceDeclared: isSourceDeclared(relative),
4117
- });
4118
- }
4119
- catch {
4120
- evidence.push({ path: relative, sha256: "0".repeat(64), fresh: false, sourceDeclared: isSourceDeclared(relative) });
4121
- }
4122
- }
4123
- return evidence;
4124
- };
4125
- async function adoptScoutFact(kind, fact) {
4126
- try {
4127
- const requestId = `${attemptId}:${kind}:${randomUUID()}`;
4128
- const staged = stageTypedEventFact({
4129
- store,
4130
- requestId,
4131
- attemptId,
4132
- fact: fact,
4133
- });
4134
- const committed = await adoptTypedEventFact({
4135
- store,
4136
- requestId,
4137
- attemptId,
4138
- fact: fact,
4139
- eventId: staged.eventId,
4140
- expectedRevision: store.revision,
4141
- });
4142
- return {
4143
- ok: true,
4144
- kind,
4145
- eventId: committed.eventId,
4146
- revision: committed.revision,
4147
- error: "",
4148
- };
4149
- }
4150
- catch (error) {
4151
- return {
4152
- ok: false,
4153
- kind,
4154
- code: error?.code,
4155
- error: error instanceof Error ? error.message : String(error),
4156
- };
4157
- }
4158
- }
4159
- const recordTargetSurfaceTool = defineTool({
4160
- name: "record_target_surface",
4161
- label: "record_target_surface",
4162
- description: "Commit an origin=scout target-surface fact with complete/blocked discovery status. A complete surface needs a proven target path and no unresolved paths; blocked surfaces name the unresolved paths instead of guessing. Example: {\"completeness\": \"complete\", \"entrypoint\": \"<file>\", \"implementationPaths\": [\"<dir or file>\"], \"testPaths\": [\"<file>\"], \"allowedPathConflicts\": [], \"unresolvedPaths\": []}",
4163
- promptSnippet: "Commit an origin=scout target-surface fact.",
4164
- parameters: Type.Object({
4165
- scopeId: Type.Optional(Type.String({ minLength: 1 })),
4166
- completeness: scoutCompleteness,
4167
- entrypoint: optionalString,
4168
- routeOrMount: optionalString,
4169
- implementationPaths: stringArray,
4170
- proposedPaths: Type.Optional(stringArray),
4171
- testPaths: stringArray,
4172
- dataSource: optionalString,
4173
- allowedPathConflicts: stringArray,
4174
- unresolvedPaths: stringArray,
4175
- }, { additionalProperties: false }),
4176
- async execute(_toolCallId, params) {
4177
- if (input.requirementIds && (!activeScope?.length || params.scopeId !== scopeIdentity(activeScope)))
4178
- return receipt({ ok: false, code: "FRONTEND_INPUT_SCOPE_VIOLATION", error: "Use exactly the runtime Scout scopeId; discovery may complete only the supplied obligations" });
4179
- const implementationPaths = params?.implementationPaths ?? [];
4180
- const proposedPaths = params?.proposedPaths ?? [];
4181
- const testPaths = params?.testPaths ?? [];
4182
- const pathEvidence = await enrichScoutPathEvidence([
4183
- ...(params?.entrypoint ? [params.entrypoint] : []),
4184
- ...implementationPaths,
4185
- ...testPaths,
4186
- ]);
4187
- for (const proposedPath of proposedPaths) {
4188
- if (!pathEvidence.some((item) => item.path === proposedPath)) {
4189
- pathEvidence.push({ path: proposedPath, sha256: "0".repeat(64), fresh: false, sourceDeclared: false, proposed: true });
4190
- }
4191
- }
4192
- const surface = {
4193
- kind: "target-surface",
4194
- origin: "scout",
4195
- completeness: params?.completeness ?? "blocked",
4196
- entrypoint: params?.entrypoint ?? "",
4197
- routeOrMount: params?.routeOrMount ?? "",
4198
- implementationPaths,
4199
- ...(proposedPaths.length > 0 ? { proposedPaths } : {}),
4200
- testPaths,
4201
- dataSource: params?.dataSource ?? "",
4202
- allowedPathConflicts: params?.allowedPathConflicts ?? [],
4203
- unresolvedPaths: params?.unresolvedPaths ?? [],
4204
- ...(hasSourceDeclarations ? { sourceDeclaredPaths } : {}),
4205
- ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
4206
- };
4207
- if (activeScope) {
4208
- const { readCompleteScoutTargetSurface } = await import("../workflows/dag/frontend-committed-facts.js");
4209
- if (surface.completeness === "complete") {
4210
- const check = readCompleteScoutTargetSurface([{ phase: "committed", fact: surface }]);
4211
- if (!check.ok)
4212
- return receipt({ ok: false, code: "SCOUT_SCOPE_INCOMPLETE", error: check.reason });
4213
- }
4214
- const saved = await adoptScoutFact("scout-scope", { kind: "scout-scope", origin: "scout", id: params.scopeId, requirementIds: activeScope, surface });
4215
- if (!saved.ok)
4216
- return receipt(saved);
4217
- const current = latestScopes();
4218
- if (input.requirementIds?.every(id => current.get(id)?.surface?.completeness === "complete")) {
4219
- const surfaces = [...new Set(input.requirementIds.map(id => current.get(id)))].map(f => f.surface);
4220
- const union = (key) => [...new Set(surfaces.flatMap(s => Array.isArray(s[key]) ? s[key] : []))];
4221
- const entries = [...new Set(surfaces.map(s => String(s.entrypoint ?? "")).filter(Boolean))];
4222
- return receipt(await adoptScoutFact("target-surface", { kind: "target-surface", origin: "scout", completeness: "complete", entrypoint: entries[0] ?? "", implementationPaths: [...new Set([...entries, ...union("implementationPaths")])], proposedPaths: union("proposedPaths"), testPaths: union("testPaths"), allowedPathConflicts: union("allowedPathConflicts"), unresolvedPaths: union("unresolvedPaths"), routeOrMount: [...new Set(surfaces.map(s => s.routeOrMount).filter(Boolean))].join("\n"), dataSource: [...new Set(surfaces.map(s => s.dataSource).filter(Boolean))].join("\n"), pathEvidence: surfaces.flatMap(s => s.pathEvidence ?? []), ...(hasSourceDeclarations ? { sourceDeclaredPaths } : {}) }));
4223
- }
4224
- return receipt(saved);
4225
- }
4226
- const result = await adoptScoutFact("target-surface", surface);
4227
- return receipt(result);
4228
- },
4229
- });
4230
- const recordDesignEvidenceTool = defineTool({
4231
- name: "record_design_evidence",
4232
- label: "record_design_evidence",
4233
- description: "Commit an origin=scout design-evidence fact (source, paths, conflicts). Example: {\"source\": \"<source>\", \"paths\": [\"<file>\"], \"conflicts\": []}",
4234
- promptSnippet: "Commit an origin=scout design-evidence fact.",
4235
- parameters: Type.Object({ source: Type.String({}), paths: stringArray, conflicts: stringArray }, { additionalProperties: false }),
4236
- async execute(_toolCallId, params) {
4237
- const paths = params?.paths ?? [];
4238
- const pathEvidence = await enrichScoutPathEvidence(paths);
4239
- const result = await adoptScoutFact("design-evidence", {
4240
- kind: "design-evidence",
4241
- origin: "scout",
4242
- source: params?.source ?? "",
4243
- paths,
4244
- conflicts: params?.conflicts ?? [],
4245
- ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
4246
- });
4247
- return receipt(result);
4248
- },
4249
- });
4250
- const durable = await createDurableFrontendTools({
4251
- file: path.join(input.runDir, input.nodeId, "scout-typed-facts.jsonl"), attemptId, store: input.store,
4252
- setWorkingStore: next => { store = next; }, binding: { requirementIds: input.requirementIds, sourceDeclaredPaths: input.sourceDeclaredPaths, sourceDigest: input.sourceDigest, workspaceRoot: input.workspaceRoot },
4253
- tools: [recordTargetSurfaceTool, recordDesignEvidenceTool],
4254
- validateRestored: async (records) => {
4255
- if (!input.workspaceRoot)
4256
- return;
4257
- for (const record of records) {
4258
- const evidence = record.fact.kind === "scout-scope" ? record.fact.surface?.pathEvidence : record.fact.pathEvidence;
4259
- if (!Array.isArray(evidence))
4260
- continue;
4261
- for (const previous of evidence) {
4262
- if (!isRecordObject(previous) || typeof previous.path !== "string")
4263
- throw Error("scout path evidence is malformed");
4264
- const current = (await enrichScoutPathEvidence([previous.path]))[0];
4265
- if (!current || current.sha256 !== previous.sha256 || current.fresh !== previous.fresh)
4266
- throw Error(`scout evidence drift: ${previous.path}; refresh Scout before reusing facts`);
4267
- }
4268
- }
4269
- },
4270
- });
4271
- return {
4272
- ...durable,
4273
- adoptCommittedFacts: async (records) => durable.commitExternal(async () => {
4274
- for (const record of records) {
4275
- if (record.phase !== "committed")
4276
- continue;
4277
- const fact = record.fact;
4278
- if (!fact || typeof fact !== "object" || Array.isArray(fact))
4279
- continue;
4280
- const result = await adoptScoutFact(typeof fact.kind === "string"
4281
- ? fact.kind
4282
- : "scout-fact", fact);
4283
- if (!result.ok) {
4284
- throw new Error(`frontend scout shard fact merge failed: ${result.error}`);
4285
- }
4286
- }
4287
- }),
4288
- setActiveScope: ids => {
4289
- if (!ids.length || ids.some(id => !input.requirementIds?.includes(id)))
4290
- throw Error("FRONTEND_INPUT_SCOPE_VIOLATION");
4291
- activeScope = [...new Set(ids)];
4292
- return scopeIdentity(activeScope);
4293
- },
4294
- completedRequirementIds: () => new Set([...latestScopes()].filter(([, fact]) => fact.surface?.completeness === "complete").map(([id]) => id)),
4295
- completedScopeFacts: () => [...new Set(latestScopes().values())].filter(f => f.surface?.completeness === "complete"),
4296
- committedFacts: () => readCommittedEvents(store, attemptId),
4297
- };
4298
- }
4299
2655
  export function buildDagPiUserMessage(task, persona, step) {
4300
2656
  const role = task.role ?? "unspecified";
4301
2657
  const writePolicy = task.writePolicy ?? "read-only (default)";
@@ -4355,27 +2711,6 @@ export function buildDagPiUserMessage(task, persona, step) {
4355
2711
  "Do not wrap the output in code fences and do not add conversational preamble.",
4356
2712
  ].join(" ");
4357
2713
  }
4358
- export function resolveDagPiModelConfig(modelReference, options) {
4359
- const separatorIndex = modelReference.indexOf("/");
4360
- const qualified = separatorIndex >= 0;
4361
- const provider = qualified
4362
- ? modelReference.slice(0, separatorIndex)
4363
- : (DAG_PI_MODEL_PROVIDERS[modelReference] ?? DEFAULT_DAG_PI_PROVIDER);
4364
- const model = qualified
4365
- ? modelReference.slice(separatorIndex + 1)
4366
- : modelReference;
4367
- if (!provider || !model) {
4368
- throw new Error(`invalid DAG Pi model reference "${modelReference}": expected non-empty provider/model`);
4369
- }
4370
- const explicitThinking = options?.thinking?.trim();
4371
- const thinking = explicitThinking ??
4372
- (provider === "wizard-local" && model === "gpt-5.5" ? "low" : undefined);
4373
- return {
4374
- provider,
4375
- model,
4376
- ...(thinking ? { thinking } : {}),
4377
- };
4378
- }
4379
2714
  const SUMMARY_STDOUT_MAX = 4_000;
4380
2715
  const SUMMARY_STDERR_MAX = 2_000;
4381
2716
  export function buildPiPromptRedactedMarkdown(prompt) {
@@ -4660,184 +2995,6 @@ const FRONTEND_PLAN_SEGMENTS = [
4660
2995
  ].join(" "),
4661
2996
  },
4662
2997
  ];
4663
- function committedFactFromPlanRecord(value) {
4664
- if (!value || typeof value !== "object" || Array.isArray(value))
4665
- return undefined;
4666
- const record = value;
4667
- if (record.phase !== undefined && record.phase !== "committed")
4668
- return undefined;
4669
- const fact = record.fact;
4670
- return fact && typeof fact === "object" && !Array.isArray(fact)
4671
- ? fact
4672
- : typeof record.kind === "string"
4673
- ? record
4674
- : undefined;
4675
- }
4676
- function planFactStringList(value) {
4677
- if (!Array.isArray(value))
4678
- return [];
4679
- return value.filter((item) => typeof item === "string" && item.trim().length > 0);
4680
- }
4681
- function planFactScopeIntersects(fact, requirementIds) {
4682
- return planFactStringList(fact.scopeRequirementIds).some((id) => requirementIds.has(id));
4683
- }
4684
- /** Compute the authoritative coverage queue from the committed plan ledger. */
4685
- export function collectFrontendPlanMissingFacts(input) {
4686
- const requirements = new Map();
4687
- const standaloneEvidenceGaps = new Set();
4688
- const verificationTargetIds = new Set();
4689
- const verificationTargetRequirements = new Map();
4690
- for (const value of input.committedFacts) {
4691
- const fact = committedFactFromPlanRecord(value);
4692
- if (!fact || fact.origin !== "plan")
4693
- continue;
4694
- if (fact.kind === "plan-requirement" && fact.entry && typeof fact.entry === "object") {
4695
- const entry = fact.entry;
4696
- if (typeof entry.id === "string" && entry.id.trim())
4697
- requirements.set(entry.id, entry);
4698
- }
4699
- if (fact.kind === "plan-verification-target" && fact.entry && typeof fact.entry === "object") {
4700
- const entry = fact.entry;
4701
- const id = entry.id;
4702
- if (typeof id === "string" && id.trim()) {
4703
- verificationTargetIds.add(id);
4704
- verificationTargetRequirements.set(id, new Set(Array.isArray(entry.requirementIds)
4705
- ? entry.requirementIds.filter((value) => typeof value === "string")
4706
- : []));
4707
- }
4708
- }
4709
- if (fact.kind === "plan-evidence-gap" && fact.entry && typeof fact.entry === "object") {
4710
- const entry = fact.entry;
4711
- const requirementId = entry.requirementId;
4712
- const description = entry.description;
4713
- if (typeof requirementId === "string" && requirementId.trim() && typeof description === "string" && description.trim()) {
4714
- standaloneEvidenceGaps.add(requirementId);
4715
- }
4716
- }
4717
- }
4718
- const missing = [];
4719
- for (const id of input.requirementIds) {
4720
- const entry = requirements.get(id);
4721
- if (!entry) {
4722
- missing.push({
4723
- kind: "plan-requirement",
4724
- id,
4725
- requirementIds: [id],
4726
- reason: `requirement ${id} has no committed plan-requirement fact`,
4727
- });
4728
- continue;
4729
- }
4730
- // Verification targets are the single authoritative direction. The
4731
- // legacy requirement-side list is accepted only as a fallback while
4732
- // resuming older ledgers; new plans derive it from target.requirementIds.
4733
- const derivedTargetIds = [...verificationTargetRequirements.entries()]
4734
- .filter(([, requirementIds]) => requirementIds.has(id))
4735
- .map(([targetId]) => targetId);
4736
- const legacyTargetIds = Array.isArray(entry.verificationTargetIds)
4737
- ? entry.verificationTargetIds.filter((value) => typeof value === "string" && value.trim().length > 0)
4738
- : [];
4739
- const targetIds = derivedTargetIds.length > 0 ? derivedTargetIds : legacyTargetIds;
4740
- const gap = entry.evidenceGap && typeof entry.evidenceGap === "object"
4741
- ? entry.evidenceGap
4742
- : undefined;
4743
- const hasEvidenceGap = (typeof gap?.description === "string" && gap.description.trim().length > 0) ||
4744
- standaloneEvidenceGaps.has(id);
4745
- if (targetIds.length === 0 && !hasEvidenceGap) {
4746
- missing.push({
4747
- kind: "plan-verification-target",
4748
- requirementIds: [id],
4749
- reason: `requirement ${id} declares neither a verification target nor a non-empty evidenceGap`,
4750
- });
4751
- continue;
4752
- }
4753
- for (const targetId of targetIds) {
4754
- if (!verificationTargetIds.has(targetId) ||
4755
- !verificationTargetRequirements.get(targetId)?.has(id)) {
4756
- missing.push({
4757
- kind: "plan-verification-target",
4758
- id: targetId,
4759
- requirementIds: [id],
4760
- reason: `requirement ${id} references verification target ${targetId}, but that target is not committed`,
4761
- });
4762
- }
4763
- }
4764
- }
4765
- return missing;
4766
- }
4767
- /** Completeness checks for phases whose facts are committed incrementally. */
4768
- export function collectFrontendPlanPhaseMissingFacts(input) {
4769
- const facts = input.committedFacts
4770
- .map(committedFactFromPlanRecord)
4771
- .filter((fact) => Boolean(fact && fact.origin === "plan"));
4772
- if (input.phase === "ux-registry") {
4773
- return facts.some((fact) => fact.kind === "state-registry")
4774
- ? []
4775
- : [
4776
- {
4777
- kind: "state-registry",
4778
- requirementIds: [...input.requirementIds],
4779
- reason: "global UX vocabulary phase has no committed state-registry fact",
4780
- },
4781
- ];
4782
- }
4783
- if (input.phase === "ux-local") {
4784
- const missing = [];
4785
- // Evaluate each behaviour requirement independently. A fact scoped to AC-1
4786
- // must not accidentally satisfy AC-2 merely because both ids share one
4787
- // UX session; shared facts remain valid when they explicitly list both ids.
4788
- for (const requirementId of input.requirementIds) {
4789
- if (!input.behaviorRequiredRequirementIds?.includes(requirementId))
4790
- continue;
4791
- const scopedFacts = facts.filter((fact) => planFactScopeIntersects(fact, new Set([requirementId])));
4792
- const hasChoice = scopedFacts.some((fact) => fact.kind === "component-choice" &&
4793
- Array.isArray(fact.uiComponentChoices) &&
4794
- fact.uiComponentChoices.length > 0);
4795
- const canonicalStateFlow = collectCanonicalStateFlowNames(scopedFacts);
4796
- const hasStateFlow = canonicalStateFlow.uiStateNames.size > 0 ||
4797
- canonicalStateFlow.interactionNames.size > 0;
4798
- if (!hasChoice) {
4799
- missing.push({
4800
- kind: "component-choice",
4801
- requirementIds: [requirementId],
4802
- reason: "behaviour-required UX slice has no committed component-choice fact",
4803
- });
4804
- }
4805
- if (!hasStateFlow) {
4806
- missing.push({
4807
- kind: "state-flow",
4808
- requirementIds: [requirementId],
4809
- reason: "behaviour-required UX slice has no committed state-flow fact",
4810
- });
4811
- }
4812
- }
4813
- return missing;
4814
- }
4815
- const hasMockApi = facts.some((fact) => fact.kind === "mock-api");
4816
- const allInteractions = collectCanonicalStateFlowNames(input.committedFacts).interactionNames;
4817
- const liveInteractions = new Set([...collectCanonicalStateFlowNames(facts.filter(f => !planFactStringList(f.scopeRequirementIds).length || planFactScopeIntersects(f, new Set(input.requirementIds)))).interactionNames].filter(name => allInteractions.has(name)));
4818
- const coveredInteractions = new Set(facts
4819
- .filter((fact) => fact.kind === "data-flow")
4820
- .flatMap((fact) => planFactStringList(fact.interactions)));
4821
- const missing = [];
4822
- if (!hasMockApi) {
4823
- missing.push({
4824
- kind: "mock-api",
4825
- requirementIds: [...input.requirementIds],
4826
- reason: "global Mock/data phase has no committed mock-api fact",
4827
- });
4828
- }
4829
- for (const interaction of liveInteractions) {
4830
- if (coveredInteractions.has(interaction))
4831
- continue;
4832
- missing.push({
4833
- kind: "data-flow",
4834
- id: interaction,
4835
- requirementIds: [...input.requirementIds],
4836
- reason: `interaction ${interaction} has no committed data-flow fact`,
4837
- });
4838
- }
4839
- return missing;
4840
- }
4841
2998
  /** Estimate calls conservatively: requirement + one VT, with a second VT
4842
2999
  * reserved for behaviour-required requirements. Explicit declarations win. */
4843
3000
  export function estimateFrontendPlanRequirementRecordCalls(fact) {