@tea-agent/loop-agent 0.51.0-next.1 → 0.51.0-next.2

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 (114) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/application/task-lifecycle/advance.js +6 -0
  3. package/dist/build-stamp.json +3 -3
  4. package/dist/commands/init.js +12 -3
  5. package/dist/executors/dag-pi/plan/facts.js +18 -4
  6. package/dist/executors/dag-pi/plan/record-tools.js +34 -3
  7. package/dist/executors/dag-pi/sessions/scout-parallel.js +11 -2
  8. package/dist/executors/dag-pi/sessions/segmented-plan.js +170 -16
  9. package/dist/executors/dag-pi/tools/contract-read-tool.js +34 -0
  10. package/dist/executors/dag-pi/tools/scout-evidence-tools.js +9 -7
  11. package/dist/executors/dag-pi-executor.js +82 -82
  12. package/dist/shared/pi-context-pressure/extension.js +24 -0
  13. package/dist/shared/pi-context-pressure/sift-bridge.js +2 -1
  14. package/dist/shared/pi-context-pressure/tool-result-pruner.js +8 -3
  15. package/dist/task/source-prepare/completeness.js +2 -2
  16. package/dist/task/source-prepare/diagnostic.js +76 -0
  17. package/dist/task/source-prepare/ledger-reconciliation.js +65 -9
  18. package/dist/task/source-prepare/ledger-review.js +18 -2
  19. package/dist/task/source-prepare/ledger.js +3 -1
  20. package/dist/task/source-prepare/prepare.js +23 -3
  21. package/dist/task/source-prepare/source-fidelity-pi.js +12 -1
  22. package/dist/task/source-prepare/types.js +1 -1
  23. package/dist/worker/console/chat/chat-event-projection.js +8 -0
  24. package/dist/worker/console/chat/chat-event-store.js +1 -0
  25. package/dist/worker/console/chat/context-insights.js +52 -3
  26. package/dist/worker/console/chat/context-usage.js +54 -0
  27. package/dist/worker/console/chat/pi-runtime/context-edit.js +83 -0
  28. package/dist/worker/console/chat/pi-runtime.js +17 -0
  29. package/dist/worker/console/chat/vcp-prompt.js +20 -13
  30. package/dist/worker/console/recovery-error-copy.js +4 -1
  31. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DUtUeeEa.js → abnfDiagram-N423BO3Z-BDoJuIJc.js} +1 -1
  32. package/dist/worker/console/static/assets/{arc-Cs0DSwTY.js → arc-BIcO0B1H.js} +1 -1
  33. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-C80FSNgl.js → architectureDiagram-T3A2C74G-DbxnPcOI.js} +1 -1
  34. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DFgOZUzn.js → blockDiagram-VBNYF7ZC-BG4tXH7C.js} +1 -1
  35. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-CB9nkTjT.js → c4Diagram-5PPSVZJV-BaNxGG9H.js} +1 -1
  36. package/dist/worker/console/static/assets/channel-DigIZ6M1.js +1 -0
  37. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DbjpoOrh.js → chunk-2GRJ4B5K-BYr2qNac.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BsWVWnWY.js → chunk-2Q5K7J3B-D3q2b9W9.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BwwP_1AG.js → chunk-5RXB4S5H-BFsAsJ8z.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DDEzW9MV.js → chunk-5VM5RSS4-Bnp6GtE7.js} +1 -1
  41. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D-fLZDni.js → chunk-6Q2QTUOP-CzDChmU1.js} +1 -1
  42. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DY9q3jMo.js → chunk-GF5L2VYU-kgZTzZlf.js} +1 -1
  43. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-rkUPkzPh.js → chunk-JWPE2WC7-Vnt5nEN_.js} +1 -1
  44. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Ci9ZksX4.js → chunk-KBJHAD2P-CENlGfou.js} +1 -1
  45. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DKU-3Ef6.js → chunk-RYQCIY6F-DS1bOotT.js} +1 -1
  46. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-A-xOwXvl.js → chunk-XXDRQBXY-SkFJspnw.js} +1 -1
  47. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-AY-sL87U.js +1 -0
  48. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-AY-sL87U.js +1 -0
  49. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Bfs1rphL.js → cose-bilkent-JH36ORCC-BE1OAnpP.js} +1 -1
  50. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BTlXtGR2.js → cynefin-VYW2F7L2-BaTDZwL-.js} +1 -1
  51. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-D8c9vCCr.js → cynefinDiagram-MW4NZA55-BRrIdbbw.js} +1 -1
  52. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B-e-tfgY.js → dagre-VZM6K2ZE-B4pDil_r.js} +1 -1
  53. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-CG_5dIVJ.js → diagram-7IWD3JNH-DvqFh-9w.js} +1 -1
  54. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmP40HmK.js → diagram-B4RE2ZJO-D7me-QwT.js} +1 -1
  55. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-RFt8vi9Y.js → diagram-LBJQPF4R-EahLHu6K.js} +1 -1
  56. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-CM5Sb2jB.js → diagram-Q27KOJAE--S6g2rQZ.js} +1 -1
  57. package/dist/worker/console/static/assets/{diagram-UB23O5K3-Bm4zh0WJ.js → diagram-UB23O5K3-BwqA9gGp.js} +1 -1
  58. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-b3GekSN4.js → ebnfDiagram-BXEA7PRR-Bdj6kj6x.js} +1 -1
  59. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CFZh4C_o.js → erDiagram-JOGREHBK-_Ii2v364.js} +1 -1
  60. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CzxniD3z.js → flowDiagram-UKHOOZJN-LM1yby4D.js} +1 -1
  61. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Czp6xUXj.js → ganttDiagram-PKOTCBZU-_MmByUIz.js} +1 -1
  62. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-B66oX4sn.js → gitGraphDiagram-DS77QQ5N-Be4J6q3D.js} +1 -1
  63. package/dist/worker/console/static/assets/{index-Bq_vMDO3.js → index-CpugPRcA.js} +120 -120
  64. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-rTveEtft.js → infoDiagram-6WML65LV-CFRi5O36.js} +1 -1
  65. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-N2jiPnrD.js → ishikawaDiagram-WSZJBQD7-B2OnsVXe.js} +1 -1
  66. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DtnLwtAE.js → journeyDiagram-NVQOT4AX-Dnz8Ge36.js} +1 -1
  67. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-t9D_2QMN.js → kanban-definition-27J2QSJJ-DFPGjB3O.js} +1 -1
  68. package/dist/worker/console/static/assets/{linear-BP6ZG0tB.js → linear-DrKFn9ZE.js} +1 -1
  69. package/dist/worker/console/static/assets/{mermaid.core-Cc5_ZtUy.js → mermaid.core-C4__OfPT.js} +5 -5
  70. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zztwmHj8.js → mindmap-definition-FAOFIHXS-CMEMeYGS.js} +1 -1
  71. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CmXQOyPH.js → pegDiagram-VL7TDLO6-BDNDtN72.js} +1 -1
  72. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BodwfpEp.js → pieDiagram-7S7Q4E2Y-DX12wRku.js} +1 -1
  73. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DIgybsTM.js → quadrantDiagram-CIZ2JOQS-DEzotPpD.js} +1 -1
  74. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CZb_4Cv2.js → railroadDiagram-AXF67PYL-BGbCCVjx.js} +1 -1
  75. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BvRNauBA.js → requirementDiagram-LRYGKXZP-eClVYdkl.js} +1 -1
  76. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BQ30kRWi.js → sankeyDiagram-W5VNT64P-Hyw3eFyF.js} +1 -1
  77. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-B7sGR3r3.js → sequenceDiagram-SI44F4Z6-DwysyBPq.js} +1 -1
  78. package/dist/worker/console/static/assets/{sheet-workbook-CK8pzw-q.js → sheet-workbook-jLtIaGKt.js} +1 -1
  79. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-1HZrTeyl.js → sizeCapture-X5ZJPWSS-CsA3-7gH.js} +1 -1
  80. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-BKCXlJRS.js → stateDiagram-OKZ733FA-DkUPiKZ8.js} +1 -1
  81. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BiXtsN97.js +1 -0
  82. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BhT8u6Vm.js → swimlanes-SLNWSIFB-qfVo6Xay.js} +2 -2
  83. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-ImoXsndy.js +8 -0
  84. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Dnczuw3j.js → timeline-definition-Z64GVDOM-BRTsFNL5.js} +1 -1
  85. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-PgJCj-16.js → vennDiagram-T6HMQDX7-BI-btTm3.js} +1 -1
  86. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BjuszbFn.js → wardleyDiagram-T6FBY63Y-BYMVY4Ov.js} +1 -1
  87. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dhtjuxrn.js → xychartDiagram-ELKLHX3M-CvK7yNi0.js} +1 -1
  88. package/dist/worker/console/static/index.html +1 -1
  89. package/dist/worker/console/static-src/operator-chat/vcp-fonts.js +1 -6
  90. package/dist/worker/console/workspace-context.js +53 -1
  91. package/dist/worker/observe/static/dag-history-labels.js +2 -0
  92. package/dist/worker/observe/static/views/dag.js +28 -0
  93. package/dist/workflows/dag/frontend-durable-tools.js +5 -2
  94. package/dist/workflows/dag/frontend-implementation-contract.js +19 -6
  95. package/dist/workflows/dag/frontend-recovery-run.js +20 -1
  96. package/dist/workflows/dag/frontend-review-scopes.js +2 -2
  97. package/dist/workflows/dag/frontend-session-budget.js +1 -1
  98. package/dist/workflows/dag/frontend-writer-baseline-guard.js +11 -5
  99. package/dist/workflows/dag/hybrid/templates/frontend.js +35 -5
  100. package/dist/workflows/dag/prompt.js +8 -2
  101. package/dist/workflows/dag/rerun-plan.js +50 -3
  102. package/dist/workflows/dag/rerun-run.js +4 -0
  103. package/dist/workflows/dag/runner.js +11 -0
  104. package/package.json +3 -3
  105. package/dist/worker/console/static/assets/channel-BddnaJc4.js +0 -1
  106. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CqfGeesl.js +0 -1
  107. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CqfGeesl.js +0 -1
  108. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DzDcqZJM.js +0 -1
  109. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DgnnY3K8.js +0 -8
  110. package/dist/worker/console/static/vcp/fonts/Lanxi-GreatVibes.woff2 +0 -0
  111. package/dist/worker/console/static/vcp/fonts/Lanxi-MaShanZheng.woff2 +0 -0
  112. package/dist/worker/console/static/vcp/fonts/Lanxi-/347/202/271/351/273/221.woff2 +0 -0
  113. package/dist/worker/console/static/vcp/fonts/Lanxi-/351/235/231/351/273/221/350/266/205/347/273/206.woff2 +0 -0
  114. package/dist/worker/console/static/vcp/fonts/Lanxi-/351/261/274/345/260/276/350/241/214/344/271/246.woff2 +0 -0
@@ -0,0 +1,34 @@
1
+ /** Read only the frozen, hash-bound contract inventory, never arbitrary paths. */
2
+ export async function createFrontendContractReadTool(inventory) {
3
+ const [{ Type }, { defineTool }] = await Promise.all([
4
+ import("typebox"),
5
+ import("@earendil-works/pi-coding-agent"),
6
+ ]);
7
+ const readIds = new Set();
8
+ return defineTool({
9
+ name: "read_frontend_contract",
10
+ label: "read_frontend_contract",
11
+ description: "Read the frozen frontend contract. With no sectionId, list semantic sections and unread IDs. With an exact listed sectionId, return its complete JSON; no character fragments or manual reconstruction. Runtime checks hashes and canonical coverage. Read all sections before implementation.",
12
+ parameters: Type.Object({ sectionId: Type.Optional(Type.String()) }, { additionalProperties: false }),
13
+ async execute(_callId, params) {
14
+ await inventory.validate();
15
+ const section = params.sectionId === undefined ? undefined : inventory.scopes.find(scope => scope.id === params.sectionId);
16
+ if (params.sectionId !== undefined && !section)
17
+ throw new Error("FRONTEND_CONTRACT_SECTION_UNKNOWN: use an exact sectionId from the inventory");
18
+ if (section)
19
+ readIds.add(section.id);
20
+ const details = {
21
+ digest: inventory.digest,
22
+ unreadSectionIds: inventory.scopes.filter(scope => !readIds.has(scope.id)).map(scope => scope.id),
23
+ ...(section ? { sectionId: section.id, sha256: section.sha256 } : {}),
24
+ };
25
+ return {
26
+ content: [{ type: "text", text: section?.text ?? JSON.stringify({
27
+ ...details,
28
+ sections: inventory.scopes.map(scope => ({ sectionId: scope.id, sha256: scope.sha256, bytes: Buffer.byteLength(scope.text, "utf8"), fields: Object.keys(JSON.parse(scope.text).data ?? {}) })),
29
+ }) }],
30
+ details,
31
+ };
32
+ },
33
+ });
34
+ }
@@ -131,7 +131,7 @@ export async function createFrontendScoutEvidenceTools(input) {
131
131
  const recordTargetSurfaceTool = defineTool({
132
132
  name: "record_target_surface",
133
133
  label: "record_target_surface",
134
- 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\": []}",
134
+ description: "Commit an origin=scout target-surface fact with complete/blocked discovery status. entrypoint is one repository-relative file path; put route/mount relationships in routeOrMount. 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\": []}",
135
135
  promptSnippet: "Commit an origin=scout target-surface fact.",
136
136
  parameters: Type.Object({
137
137
  scopeId: Type.Optional(Type.String({ minLength: 1 })),
@@ -176,13 +176,15 @@ export async function createFrontendScoutEvidenceTools(input) {
176
176
  ...(hasSourceDeclarations ? { sourceDeclaredPaths } : {}),
177
177
  ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
178
178
  };
179
- if (activeScope) {
179
+ // Validate before acknowledging any complete surface, including parallel
180
+ // unscoped Scout. A rejected submission stays editable in this session.
181
+ if (surface.completeness === "complete") {
180
182
  const { readCompleteScoutTargetSurface } = await import("../../../workflows/dag/frontend-committed-facts.js");
181
- if (surface.completeness === "complete") {
182
- const check = readCompleteScoutTargetSurface([{ phase: "committed", fact: surface }]);
183
- if (!check.ok)
184
- return receipt({ ok: false, code: "SCOUT_SCOPE_INCOMPLETE", error: check.reason });
185
- }
183
+ const check = readCompleteScoutTargetSurface([{ phase: "committed", fact: surface }]);
184
+ if (!check.ok)
185
+ return receipt({ ok: false, code: activeScope ? "SCOUT_SCOPE_INCOMPLETE" : "SCOUT_TARGET_SURFACE_INCOMPLETE", error: check.reason });
186
+ }
187
+ if (activeScope) {
186
188
  const saved = await adoptScoutFact("scout-scope", { kind: "scout-scope", origin: "scout", id: params.scopeId, requirementIds: activeScope, surface });
187
189
  if (!saved.ok)
188
190
  return receipt(saved);
@@ -59,31 +59,62 @@ export { estimateFrontendPlanRequirementRecordCalls, batchFrontendPlanRequiremen
59
59
  * Legacy diagnostic label retained for artifact compatibility. New executions
60
60
  * classify this signal as output-limit and preserve committed typed facts.
61
61
  */
62
+ /** Rewrite only VT identities and typed references, including top-level state-flow facts. */
63
+ function rewritePlanVerificationTargetIds(record, rewriteId) {
64
+ const rewriteReferences = (value) => {
65
+ if (Array.isArray(value)) {
66
+ const next = value.map(rewriteReferences);
67
+ return next.some((item, index) => item !== value[index]) ? next : value;
68
+ }
69
+ if (!value || typeof value !== "object")
70
+ return value;
71
+ const source = value;
72
+ let changed = false;
73
+ const next = Object.fromEntries(Object.entries(source).map(([key, child]) => {
74
+ let rewritten = key === "verificationTargetIds" && Array.isArray(child)
75
+ ? child.map(id => typeof id === "string" ? rewriteId(id) : id)
76
+ : rewriteReferences(child);
77
+ if (Array.isArray(child) && Array.isArray(rewritten) && rewritten.every((item, index) => item === child[index]))
78
+ rewritten = child;
79
+ if (rewritten !== child)
80
+ changed = true;
81
+ return [key, rewritten];
82
+ }));
83
+ return changed ? next : value;
84
+ };
85
+ let fact = rewriteReferences(record.fact);
86
+ if (fact.kind === "plan-verification-target") {
87
+ const entry = fact.entry;
88
+ if (typeof entry?.id === "string") {
89
+ const id = rewriteId(entry.id);
90
+ const replaces = typeof fact.replaces === "string" ? rewriteId(fact.replaces) : fact.replaces;
91
+ if (id !== entry.id || replaces !== fact.replaces) {
92
+ fact = { ...fact, entry: { ...entry, id }, ...(replaces !== undefined ? { replaces } : {}) };
93
+ }
94
+ }
95
+ }
96
+ return fact === record.fact ? record : {
97
+ ...record,
98
+ fact,
99
+ payloadSha256: typedEventPayloadSha256(fact),
100
+ };
101
+ }
62
102
  /**
63
- * Parallel coverage shards namespace their verification target ids with
64
- * `VT-SHARD-<shard>-` so the reducer can detect cross-shard conflicts. Once
65
- * every shard's facts are known the namespace must be restored: the canonical
66
- * contract has to carry the exact ids the task source froze (a surviving
67
- * `VT-SHARD-N-…` id is a contract-requirement gap that design review
68
- * rejects). Stripping happens per shard before adoption — after the strip,
69
- * the existing identity-conflict check catches genuine cross-shard
70
- * duplicate base ids and fails the merge closed.
71
- */
72
- /**
73
- * Deterministic pre-reduce for parallel coverage shard facts. Shards partition
74
- * requirements, but a frozen verification target can legitimately be derived
75
- * by several shards (one VT covers multiple ACs across shard boundaries), so
76
- * same-id verification targets are MERGED: requirementIds and uiStates union,
77
- * while divergent file/commandId is a real conflict. Everything else passes
78
- * through unchanged.
103
+ * Frozen VT identities span shards and merge coverage only when their bindings
104
+ * agree. Model-chosen IDs are local references: namespace them by stable shard
105
+ * identity, never by a mutable file/command or by which shards finished first.
106
+ * A same-shard correction therefore retains its identity across partial replay.
79
107
  */
80
- export function reduceParallelCoverageShardRecords(records) {
108
+ export function reduceParallelCoverageShardRecords(records, canonicalVerificationTargetIds = []) {
109
+ const canonicalIds = new Set(canonicalVerificationTargetIds);
81
110
  // Resolve replacements inside each source shard before comparing shards.
82
111
  // A correction is an event-log operation, not a second independent target;
83
112
  // retaining both records makes a valid same-shard correction look like a
84
113
  // cross-shard conflict during the later reduction.
85
114
  const byShard = new Map();
86
- for (const record of records) {
115
+ for (const sourceRecord of records) {
116
+ const shardKey = createHash("sha256").update(sourceRecord.attemptId).digest("hex");
117
+ const record = rewritePlanVerificationTargetIds(sourceRecord, id => canonicalIds.has(id) ? id : `VT-LOCAL-${shardKey}-${id}`);
87
118
  const shard = byShard.get(record.attemptId) ?? [];
88
119
  shard.push(record);
89
120
  byShard.set(record.attemptId, shard);
@@ -143,7 +174,7 @@ export function reduceParallelCoverageShardRecords(records) {
143
174
  }
144
175
  const priorEntry = prior.fact.entry;
145
176
  if (sha256OfCanonicalJson(priorEntry) !== sha256OfCanonicalJson(entry)) {
146
- throw new Error(`frontend plan coverage shard reduce conflict: implementation slice ${entry.id} has divergent content`);
177
+ throw Object.assign(new Error(`frontend plan coverage shard reduce conflict: implementation slice ${entry.id} has divergent content`), { code: "FRONTEND_PLAN_COVERAGE_REDUCE_CONFLICT" });
147
178
  }
148
179
  continue;
149
180
  }
@@ -168,7 +199,7 @@ export function reduceParallelCoverageShardRecords(records) {
168
199
  const baseEntry = { ...existing.entry };
169
200
  for (const field of ["commandId", "commandLabel", "file", "scope"]) {
170
201
  if (entry[field] !== baseEntry[field]) {
171
- throw new Error(`frontend plan coverage shard reduce conflict: verification target ${entry.id} has divergent ${field} "${String(entry[field])}" vs "${String(baseEntry[field])}"`);
202
+ throw Object.assign(new Error(`frontend plan coverage shard reduce conflict: verification target ${entry.id} has divergent ${field} "${String(entry[field])}" vs "${String(baseEntry[field])}"`), { code: "FRONTEND_PLAN_COVERAGE_REDUCE_CONFLICT" });
172
203
  }
173
204
  }
174
205
  const unionSorted = (a, b) => {
@@ -305,73 +336,22 @@ export function validateParallelImplementationSliceDependencies(records) {
305
336
  for (const id of [...slices.keys()].sort())
306
337
  visit(id);
307
338
  }
308
- export function normalizeParallelCoverageShardRecords(records, shardNumber) {
339
+ export function normalizeParallelCoverageShardRecords(records, shardNumber, canonicalVerificationTargetIds = []) {
309
340
  const prefix = `VT-SHARD-${shardNumber}-`;
341
+ const canonicalIds = new Set(canonicalVerificationTargetIds);
310
342
  // Models sometimes drop the `VT-` stem when applying the shard namespace
311
343
  // (observed: frozen `VT-X` became `VT-SHARD-2-X`), so restoring the
312
344
  // canonical id requires re-adding the stem after the strip.
313
345
  const stripId = (id) => {
314
- if (typeof id !== "string" || !id.startsWith(prefix))
346
+ if (canonicalIds.has(id) || !id.startsWith(prefix))
315
347
  return id;
316
348
  const base = id.slice(prefix.length);
317
- return base.startsWith("VT-") ? base : `VT-${base}`;
349
+ const restored = base.startsWith("VT-") ? base : `VT-${base}`;
350
+ // Only frozen identities authorize stripping. A model-chosen local id
351
+ // may legitimately contain this prefix and must remain a distinct id.
352
+ return canonicalIds.has(restored) ? restored : id;
318
353
  };
319
- const stripIdList = (ids) => Array.isArray(ids) ? ids.map((id) => stripId(id)) : ids;
320
- return records.map((record) => {
321
- const fact = record.fact;
322
- if (!fact || typeof fact !== "object")
323
- return record;
324
- const kind = fact.kind;
325
- const entry = fact.entry;
326
- if (!entry || typeof entry !== "object")
327
- return record;
328
- let rewritten;
329
- const replaces = kind === "plan-verification-target" ? stripId(fact.replaces) : fact.replaces;
330
- if (kind === "plan-verification-target") {
331
- const id = stripId(entry.id);
332
- if (id !== entry.id || replaces !== fact.replaces)
333
- rewritten = { ...entry, id };
334
- }
335
- else if (kind === "plan-requirement") {
336
- const verificationTargetIds = stripIdList(entry.verificationTargetIds);
337
- if (verificationTargetIds !== entry.verificationTargetIds) {
338
- rewritten = { ...entry, verificationTargetIds };
339
- }
340
- }
341
- else if (kind === "state-flow") {
342
- const rewriteBoundTargets = (item) => {
343
- if (!item || typeof item !== "object")
344
- return item;
345
- return {
346
- ...item,
347
- verificationTargetIds: stripIdList(item.verificationTargetIds),
348
- };
349
- };
350
- const uiStates = Array.isArray(entry.uiStates)
351
- ? entry.uiStates.map(rewriteBoundTargets)
352
- : entry.uiStates;
353
- const interactions = Array.isArray(entry.interactions)
354
- ? entry.interactions.map(rewriteBoundTargets)
355
- : entry.interactions;
356
- if (uiStates !== entry.uiStates || interactions !== entry.interactions) {
357
- rewritten = { ...entry, uiStates, interactions };
358
- }
359
- }
360
- return rewritten
361
- ? {
362
- ...record,
363
- fact: { ...fact, ...(replaces !== undefined ? { replaces } : {}), entry: rewritten },
364
- // Keep the integrity hash consistent with the rewritten
365
- // payload, or the adoption replay check reports the
366
- // normalized record as a tampered source event.
367
- payloadSha256: typedEventPayloadSha256({
368
- ...fact,
369
- ...(replaces !== undefined ? { replaces } : {}),
370
- entry: rewritten,
371
- }),
372
- }
373
- : record;
374
- });
354
+ return records.map(record => rewritePlanVerificationTargetIds(record, stripId));
375
355
  }
376
356
  /**
377
357
  * The writer session burned an excessive token budget (a read-edit-test loop
@@ -2354,6 +2334,16 @@ clock = Date.now) {
2354
2334
  }
2355
2335
  }
2356
2336
  }
2337
+ if (isWriteTask && ["frontend-implement-pi", "frontend-repair-pi"].includes(input.task.id)) {
2338
+ const hasIndex = await stat(path.join(meta.runDir, "contracts/frontend-implementation-contract.index.json"))
2339
+ .then(() => true, error => { if (error.code === "ENOENT")
2340
+ return false; throw error; });
2341
+ const inventory = hasIndex ? await loadFrontendReviewScopes(meta.runDir, "design", 0) : undefined;
2342
+ if (inventory) {
2343
+ const { createFrontendContractReadTool } = await import("./dag-pi/tools/contract-read-tool.js");
2344
+ customTools.push(await createFrontendContractReadTool(inventory));
2345
+ }
2346
+ }
2357
2347
  if (customTools.length > 0) {
2358
2348
  writerToolPolicy = { requireSdk: true, customTools };
2359
2349
  }
@@ -3040,6 +3030,9 @@ clock = Date.now) {
3040
3030
  : undefined;
3041
3031
  const modelConfig = resolveDagPiModelConfig(input.model, input.thinking ? { thinking: input.thinking } : undefined);
3042
3032
  const toolNames = resolveDagPiToolNames(input.task);
3033
+ if (writerToolPolicy?.customTools?.some(tool => tool.name === "read_frontend_contract")) {
3034
+ toolNames.push("read_frontend_contract");
3035
+ }
3043
3036
  const userMessage = buildDagPiUserMessage(input.task, persona, step);
3044
3037
  await writeEffectiveContextReceipt({
3045
3038
  runDir: meta.runDir,
@@ -3388,7 +3381,7 @@ clock = Date.now) {
3388
3381
  ledgerTools: shardTools,
3389
3382
  sessionOptions: shardSessionOptions,
3390
3383
  requirementIds: slice,
3391
- basePrompt: `${input.prompt}\n\nPARALLEL COVERAGE SHARD ${index + 1}: use the frozen canonical behavior verification-target ids listed in the record_plan_verification_target tool description — do not prefix ids with a shard namespace or invent variant ids; identical cross-shard targets are deduped, divergent ones fail the merge.`,
3384
+ basePrompt: `${input.prompt}\n\nPARALLEL COVERAGE SHARD ${index + 1}: preserve the exact frozen canonical behavior verification-target ids listed in the tool description. Other target ids are local to this shard; runtime assigns their global identity. Do not add a shard prefix yourself. Reuse a local id only for the same target, and use replace:true for corrections.`,
3392
3385
  parallelCoverageOnly: true,
3393
3386
  observation: {
3394
3387
  artifactPath: path.join(meta.runDir, input.task.id, "parallel", `coverage-${index + 1}`, "session-budget", `attempt-${input.attempt ?? 1}`),
@@ -3442,13 +3435,14 @@ clock = Date.now) {
3442
3435
  const coverageResult = aggregateParallelPiResults(shardResults.map((shard) => shard.result));
3443
3436
  let mergeFailure;
3444
3437
  try {
3438
+ const canonicalVerificationTargetIds = await resolveFrontendCanonicalVerificationTargetIds({ runDir: meta.runDir });
3445
3439
  // Flatten every shard's facts FIRST, then pre-reduce: shards
3446
3440
  // partition requirements but a frozen verification target can
3447
3441
  // span shards, so same-id targets must merge across shards
3448
3442
  // before adoption, not per shard.
3449
3443
  const reducedCoverageFacts = reduceParallelCoverageShardRecords(shardResults
3450
3444
  .filter((item) => item.result.ok && item.tools)
3451
- .flatMap((shard) => normalizeParallelCoverageShardRecords(shard.tools.committedFacts(), shard.index + 1)));
3445
+ .flatMap((shard) => normalizeParallelCoverageShardRecords(shard.tools.committedFacts(), shard.index + 1, canonicalVerificationTargetIds)), canonicalVerificationTargetIds);
3452
3446
  validateParallelCoverageFacts({
3453
3447
  records: reducedCoverageFacts,
3454
3448
  requirementIds: planRequirementIds,
@@ -3465,7 +3459,13 @@ clock = Date.now) {
3465
3459
  result = {
3466
3460
  ...coverageResult,
3467
3461
  ok: false,
3468
- failureCategory: "invalid-output",
3462
+ // Completed shards replay the same durable facts on retry, so a
3463
+ // deterministic reducer conflict cannot be repaired by another
3464
+ // model attempt. Preserve it outside the provider retry ladder.
3465
+ failureCategory: mergeFailure?.code ===
3466
+ "FRONTEND_PLAN_COVERAGE_REDUCE_CONFLICT"
3467
+ ? "tool-policy"
3468
+ : "invalid-output",
3469
3469
  stderr: [
3470
3470
  coverageResult.stderr,
3471
3471
  `frontend plan coverage shard merge failed: ${mergeFailure instanceof Error ? mergeFailure.message : String(mergeFailure)}`,
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { shouldRewriteAssistantTransientProviderError } from "../pi-provider-recovery.js";
2
3
  import { buildOverflowCheckpoint } from "./checkpoint.js";
3
4
  import { prunePiToolResultMessages, } from "./tool-result-pruner.js";
@@ -94,6 +95,29 @@ export function createContextPressureExtension(options) {
94
95
  const result = prunePiToolResultMessages(messages, options.prune);
95
96
  if (!result.changed)
96
97
  return undefined;
98
+ const adapter = options.contextEdit?.();
99
+ if (adapter) {
100
+ for (const change of result.changes) {
101
+ try {
102
+ const applied = adapter.replaceToolResult(change.sourceMessage, change.replacementMessage);
103
+ if (!applied)
104
+ continue;
105
+ options.onPrune?.({
106
+ pruneId: randomUUID(),
107
+ replacementId: randomUUID(),
108
+ sourcePiEntryId: applied.sourcePiEntryId,
109
+ contextEditEntryId: applied.contextEditEntryId,
110
+ ...(applied.toolCallId ? { toolCallId: applied.toolCallId } : {}),
111
+ replacementMessage: change.replacementMessage,
112
+ charsBefore: change.charsBefore,
113
+ charsAfter: change.charsAfter,
114
+ });
115
+ }
116
+ catch {
117
+ // Durable editing is fail-open; keep the in-memory replacement.
118
+ }
119
+ }
120
+ }
97
121
  options.controller.counters.toolResultPruned += result.messagesPruned;
98
122
  options.controller.counters.charsPrunedEstimate += result.charsRemoved;
99
123
  return { messages: result.messages };
@@ -197,7 +197,8 @@ function restoreInResponsesInput(original, next, protectedIds) {
197
197
  if (!isRecord(origItem))
198
198
  continue;
199
199
  const callId = typeof origItem.call_id === "string" ? origItem.call_id : undefined;
200
- if (callId && protectedIds.has(callId)) {
200
+ // Pi Responses tool IDs include the provider item ID; the wire call_id does not.
201
+ if (callId && [...protectedIds].some((id) => id.split("|")[0] === callId)) {
201
202
  next.input[index] = origItem;
202
203
  }
203
204
  }
@@ -72,6 +72,7 @@ export function prunePiToolResultMessages(messages, config) {
72
72
  const cfg = resolvePiToolResultPruneConfig(config);
73
73
  const output = messages.slice();
74
74
  let charsRemoved = 0, messagesPruned = 0;
75
+ const changes = [];
75
76
  for (let i = 0; i < output.length; i++) {
76
77
  const message = output[i];
77
78
  if (!message || !isToolResult(message))
@@ -79,9 +80,11 @@ export function prunePiToolResultMessages(messages, config) {
79
80
  if (typeof message.content === "string") {
80
81
  const r = pruneBlocks([{ type: "text", text: message.content }], cfg);
81
82
  if (r.blocks) {
82
- output[i] = { ...message, content: r.blocks[0].text };
83
+ const replacementMessage = { ...message, content: r.blocks[0].text };
84
+ output[i] = replacementMessage;
83
85
  charsRemoved += r.before - r.after;
84
86
  messagesPruned++;
87
+ changes.push({ index: i, sourceMessage: message, replacementMessage, charsBefore: r.before, charsAfter: r.after, charsRemoved: r.before - r.after, ...(typeof message.toolCallId === "string" ? { toolCallId: message.toolCallId } : {}) });
85
88
  }
86
89
  continue;
87
90
  }
@@ -89,10 +92,12 @@ export function prunePiToolResultMessages(messages, config) {
89
92
  continue;
90
93
  const r = pruneBlocks(message.content, cfg);
91
94
  if (r.blocks) {
92
- output[i] = { ...message, content: r.blocks };
95
+ const replacementMessage = { ...message, content: r.blocks };
96
+ output[i] = replacementMessage;
93
97
  charsRemoved += r.before - r.after;
94
98
  messagesPruned++;
99
+ changes.push({ index: i, sourceMessage: message, replacementMessage, charsBefore: r.before, charsAfter: r.after, charsRemoved: r.before - r.after, ...(typeof message.toolCallId === "string" ? { toolCallId: message.toolCallId } : {}) });
95
100
  }
96
101
  }
97
- return { messages: output, changed: messagesPruned > 0, charsRemoved, messagesPruned };
102
+ return { messages: output, changed: messagesPruned > 0, charsRemoved, messagesPruned, changes };
98
103
  }
@@ -347,7 +347,7 @@ export function appendLedgerGaps(input) {
347
347
  message: `ledger 有 ${summary.unresolvedCount} 个 unresolved fragment(需人工 sourceResolutions 确认后才可继续)`,
348
348
  details: {
349
349
  fragmentIds: summary.exclusions
350
- .filter((e) => /^REQ-SRC-/.test(e.fragmentId) || e.fragmentId.startsWith("AC-"))
350
+ .filter((e) => e.disposition === "unresolved")
351
351
  .slice(0, 10)
352
352
  .map((e) => e.fragmentId),
353
353
  },
@@ -476,7 +476,7 @@ export function appendLedgerGaps(input) {
476
476
  message: `ledger 有 ${summary.contextOnlyCount} 个 context-only fragment(低风险排除;frontend 任务需完整理由且独立 reviewer pass)`,
477
477
  details: {
478
478
  fragmentIds: summary.exclusions
479
- .filter((e) => e.fragmentId.startsWith("REQ-SRC-"))
479
+ .filter((e) => e.disposition === "context-only")
480
480
  .slice(0, 10)
481
481
  .map((e) => e.fragmentId),
482
482
  },
@@ -0,0 +1,76 @@
1
+ import { lstat, mkdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
4
+ import { assertRealPathInsideBoundary } from "../../shared/path-safety.js";
5
+ import { getTaskPaths } from "../runtime.js";
6
+ /** Failure evidence is diagnostic-only: it never replaces or feeds canonical source. */
7
+ export async function persistPrepareFailureDiagnostic(input) {
8
+ const { repoRoot, sourceExecutionId, result } = input;
9
+ if (result.ok || result.mode !== "apply" || !sourceExecutionId ||
10
+ (!result.draft && !result.ledger))
11
+ return result;
12
+ try {
13
+ const executionIdPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
14
+ if (!executionIdPattern.test(sourceExecutionId)) {
15
+ throw new Error("invalid source execution identity");
16
+ }
17
+ const taskDir = getTaskPaths(repoRoot, result.taskId).taskDir;
18
+ const artifactsDir = path.join(taskDir, "artifacts");
19
+ // The source execution receipt has already created artifacts. Validate all
20
+ // existing ancestors before creating a diagnostic directory beneath them.
21
+ await assertRealPathInsideBoundary({
22
+ boundaryRoot: repoRoot,
23
+ targetPath: artifactsDir,
24
+ label: "source prepare diagnostic",
25
+ });
26
+ const directory = path.join(artifactsDir, "source-prepare-diagnostics");
27
+ await mkdir(directory, { mode: 0o700 }).catch((error) => {
28
+ if (error.code !== "EEXIST")
29
+ throw error;
30
+ });
31
+ await assertRealPathInsideBoundary({
32
+ boundaryRoot: repoRoot,
33
+ targetPath: directory,
34
+ label: "source prepare diagnostic",
35
+ });
36
+ const file = path.join(directory, `${sourceExecutionId}.json`);
37
+ const existing = await lstat(file).catch((error) => {
38
+ if (error.code !== "ENOENT")
39
+ throw error;
40
+ return undefined;
41
+ });
42
+ if (existing)
43
+ throw new Error("source prepare diagnostic already exists");
44
+ await writeJsonAtomic(file, {
45
+ schemaVersion: 1,
46
+ kind: "source-prepare-failure",
47
+ taskId: result.taskId,
48
+ sourceExecutionId,
49
+ createdAt: new Date().toISOString(),
50
+ result,
51
+ }, { repoRoot, mode: 0o600, directoryMode: 0o700 });
52
+ return {
53
+ ...result,
54
+ diagnosticPath: path.relative(repoRoot, file).split(path.sep).join("/"),
55
+ diagnosticSummary: {
56
+ fragmentCount: result.ledger?.fragments.length ?? 0,
57
+ unresolvedCount: result.ledger?.unresolved.length ?? 0,
58
+ reviewedCount: result.review?.reviewed.length ?? 0,
59
+ blockingGapCodes: [...new Set(result.gaps
60
+ .filter((gap) => gap.level === "blocking")
61
+ .map((gap) => gap.code))],
62
+ },
63
+ };
64
+ }
65
+ catch {
66
+ // Preserve the original gate/error and make evidence loss explicit without
67
+ // leaking host paths from filesystem errors into the lifecycle response.
68
+ return {
69
+ ...result,
70
+ warnings: [...(result.warnings ?? []), {
71
+ code: "SOURCE_PREPARE_DIAGNOSTIC_WRITE_FAILED",
72
+ message: "failed to persist source prepare diagnostic; original prepare failure remains blocking",
73
+ }],
74
+ };
75
+ }
76
+ }
@@ -53,12 +53,7 @@ export async function reconcileLedgerFragments(input) {
53
53
  const canonicalById = new Map(canonicalRequirements.map((req) => [req.id, req.text]));
54
54
  const canonicalTexts = new Set(canonicalRequirements.map((req) => normalizeFragmentText(req.text)));
55
55
  const canonicalIds = new Set(canonicalById.keys());
56
- const reconciled = [];
57
- for (const fragment of input.fragments) {
58
- if (isStructuredMappableFragment(fragment, canonicalById, canonicalTexts)) {
59
- reconciled.push(fragment);
60
- continue;
61
- }
56
+ const reconcileFragment = async (fragment, contextFragments) => {
62
57
  const request = {
63
58
  fragment: {
64
59
  id: fragment.id,
@@ -69,6 +64,7 @@ export async function reconcileLedgerFragments(input) {
69
64
  },
70
65
  canonicalRequirements,
71
66
  budgetChars,
67
+ ...(contextFragments ? { contextFragments } : {}),
72
68
  };
73
69
  let result;
74
70
  try {
@@ -100,16 +96,76 @@ export async function reconcileLedgerFragments(input) {
100
96
  const risk = fragment.risk === "high" || derivedRisk === "high"
101
97
  ? "high"
102
98
  : "low";
103
- reconciled.push({
104
- ...fragment,
99
+ // The new decision owns its reason; an inventory exclusion reason must not
100
+ // survive when reconciliation changes the fragment into an obligation.
101
+ const { reason: _previousReason, ...fragmentIdentity } = fragment;
102
+ return {
103
+ ...fragmentIdentity,
105
104
  disposition: result.disposition,
106
105
  ...(result.reason ? { reason: result.reason } : {}),
107
106
  risk,
108
107
  canonicalRequirementIds: result.mappedIds,
109
- });
108
+ };
109
+ };
110
+ const reconciled = [];
111
+ for (const fragment of input.fragments) {
112
+ reconciled.push(isStructuredMappableFragment(fragment, canonicalById, canonicalTexts)
113
+ ? fragment
114
+ : await reconcileFragment(fragment));
115
+ }
116
+ // A responsibility lead-in can only be scoped once the neighboring evidence
117
+ // clauses have been mapped. Retry it once with those complete source clauses;
118
+ // an empty result still reaches the normal high-risk materialization path.
119
+ const firstPass = [...reconciled];
120
+ for (const [index, fragment] of firstPass.entries()) {
121
+ if (fragment.disposition !== "constraint" || fragment.canonicalRequirementIds.length > 0)
122
+ continue;
123
+ const contextFragments = constraintContext(firstPass, index, budgetChars);
124
+ if (!contextFragments.some((context) => context.canonicalRequirementIds.length > 0))
125
+ continue;
126
+ reconciled[index] = await reconcileFragment(fragment, contextFragments);
110
127
  }
111
128
  return { fragments: reconciled, calls };
112
129
  }
130
+ /** Take complete, contiguous neighbors from the same source section only. */
131
+ function constraintContext(fragments, index, budgetChars) {
132
+ const target = fragments[index];
133
+ let remaining = budgetChars - target.text.length;
134
+ const selected = [];
135
+ let before = index - 1;
136
+ let after = index + 1;
137
+ const inSection = (candidate) => candidate?.path === target.path && candidate.headingPath === target.headingPath;
138
+ while (before >= 0 || after < fragments.length) {
139
+ for (const direction of ["before", "after"]) {
140
+ const candidateIndex = direction === "before" ? before : after;
141
+ const candidate = fragments[candidateIndex];
142
+ if (!inSection(candidate) || !candidate || candidate.text.length > remaining) {
143
+ if (direction === "before")
144
+ before = -1;
145
+ else
146
+ after = fragments.length;
147
+ continue;
148
+ }
149
+ selected.push(candidateIndex);
150
+ remaining -= candidate.text.length;
151
+ if (direction === "before")
152
+ before--;
153
+ else
154
+ after++;
155
+ }
156
+ }
157
+ return selected.sort((left, right) => left - right).map((selectedIndex) => {
158
+ const fragment = fragments[selectedIndex];
159
+ return {
160
+ id: fragment.id,
161
+ path: fragment.path,
162
+ headingPath: fragment.headingPath,
163
+ lineRange: fragment.lineRange,
164
+ text: fragment.text,
165
+ canonicalRequirementIds: fragment.canonicalRequirementIds,
166
+ };
167
+ });
168
+ }
113
169
  /** 供 ledger.ts 接入:把 inventory records 与 raw fragments 合并为可 reconciliation 项。 */
114
170
  export function mergeInventoryItems(input) {
115
171
  const textById = new Map(input.fragments.map((fragment) => [fragment.id, fragment.text]));
@@ -12,9 +12,11 @@ export const LEDGER_REVIEW_DEFAULT_BUDGET_CHARS = 2000;
12
12
  export const LEDGER_REVIEW_MAX_REVISIONS = 1;
13
13
  /** review 失败(reviewer 异常/第二次不通过)统一稳定错误码。 */
14
14
  export class LedgerReviewError extends Error {
15
+ review;
15
16
  code = "SOURCE_FIDELITY_RECONCILIATION_FAILED";
16
- constructor(message, options) {
17
+ constructor(message, options, review) {
17
18
  super(message, options);
19
+ this.review = review;
18
20
  this.name = "LedgerReviewError";
19
21
  }
20
22
  }
@@ -77,6 +79,7 @@ export async function reviewLedgerFragments(input) {
77
79
  let approved = false;
78
80
  let revisionUsed = false;
79
81
  let revisionsRemaining = maxRevisions;
82
+ const decisions = [];
80
83
  for (;;) {
81
84
  const request = {
82
85
  kind,
@@ -89,9 +92,21 @@ export async function reviewLedgerFragments(input) {
89
92
  response = await reviewer(request);
90
93
  }
91
94
  catch (error) {
92
- throw new LedgerReviewError(`independent reviewer failed for ${kind} fragment ${fragment.id}: ${error instanceof Error ? error.message : String(error)}`);
95
+ const message = `independent reviewer failed for ${kind} fragment ${fragment.id}: ${error instanceof Error ? error.message : String(error)}`;
96
+ throw new LedgerReviewError(message, undefined, {
97
+ approved: false,
98
+ code: "SOURCE_FIDELITY_RECONCILIATION_FAILED",
99
+ reasons: [...reasons, message],
100
+ reviewed: [...reviewed, { fragmentId: fragment.id, kind, approved: false, revisionUsed, decisions }],
101
+ calls: [...calls],
102
+ });
93
103
  }
94
104
  calls.push(fragment.id);
105
+ decisions.push({
106
+ approved: response?.approved === true,
107
+ ...(response?.reason !== undefined ? { reason: response.reason } : {}),
108
+ ...(response?.revision ? { revision: { ...response.revision } } : {}),
109
+ });
95
110
  if (response?.approved === true) {
96
111
  approved = true;
97
112
  break;
@@ -119,6 +134,7 @@ export async function reviewLedgerFragments(input) {
119
134
  kind,
120
135
  approved,
121
136
  revisionUsed,
137
+ decisions,
122
138
  });
123
139
  if (approved)
124
140
  continue;