@tea-agent/loop-agent 0.51.0-next.1 → 0.51.0-next.3
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.
- package/CHANGELOG.md +33 -1
- package/dist/application/task-lifecycle/advance.js +6 -0
- package/dist/build-stamp.json +3 -3
- package/dist/commands/init.js +12 -3
- package/dist/executors/dag-pi/plan/facts.js +18 -4
- package/dist/executors/dag-pi/plan/record-tools.js +34 -3
- package/dist/executors/dag-pi/sessions/scout-parallel.js +11 -2
- package/dist/executors/dag-pi/sessions/segmented-plan.js +170 -16
- package/dist/executors/dag-pi/tools/contract-read-tool.js +34 -0
- package/dist/executors/dag-pi/tools/scout-evidence-tools.js +9 -7
- package/dist/executors/dag-pi-executor.js +82 -82
- package/dist/shared/pi-context-pressure/checkpoint.js +22 -4
- package/dist/shared/pi-context-pressure/compaction-policy.js +5 -1
- package/dist/shared/pi-context-pressure/extension.js +64 -5
- package/dist/shared/pi-context-pressure/sift-bridge.js +2 -1
- package/dist/shared/pi-context-pressure/telemetry.js +4 -0
- package/dist/shared/pi-context-pressure/tool-result-pruner.js +8 -3
- package/dist/task/source-prepare/completeness.js +2 -2
- package/dist/task/source-prepare/diagnostic.js +76 -0
- package/dist/task/source-prepare/ledger-reconciliation.js +65 -9
- package/dist/task/source-prepare/ledger-review.js +18 -2
- package/dist/task/source-prepare/ledger.js +3 -1
- package/dist/task/source-prepare/prepare.js +23 -3
- package/dist/task/source-prepare/source-fidelity-pi.js +12 -1
- package/dist/task/source-prepare/types.js +1 -1
- package/dist/worker/console/chat/chat-event-projection.js +13 -0
- package/dist/worker/console/chat/chat-event-store.js +1 -0
- package/dist/worker/console/chat/compaction-errors.js +1 -1
- package/dist/worker/console/chat/context-accounting.js +58 -0
- package/dist/worker/console/chat/context-insights.js +131 -22
- package/dist/worker/console/chat/context-usage.js +57 -1
- package/dist/worker/console/chat/pi-runtime/context-edit.js +91 -0
- package/dist/worker/console/chat/pi-runtime.js +36 -3
- package/dist/worker/console/chat/routes.js +3 -0
- package/dist/worker/console/chat/terminal-routes.js +12 -0
- package/dist/worker/console/chat/terminal-sessions.js +6 -0
- package/dist/worker/console/chat/vcp-prompt.js +28 -15
- package/dist/worker/console/recovery-error-copy.js +4 -1
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DUtUeeEa.js → abnfDiagram-N423BO3Z-GerMJfMU.js} +1 -1
- package/dist/worker/console/static/assets/{arc-Cs0DSwTY.js → arc-DHRoAcBA.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-C80FSNgl.js → architectureDiagram-T3A2C74G-Bna7kqEi.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DFgOZUzn.js → blockDiagram-VBNYF7ZC-B8yw7WTX.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-CB9nkTjT.js → c4Diagram-5PPSVZJV-BaUWiyqi.js} +1 -1
- package/dist/worker/console/static/assets/channel-CLhtAowh.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DbjpoOrh.js → chunk-2GRJ4B5K-D4iZ2ZNv.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BsWVWnWY.js → chunk-2Q5K7J3B-BtQpibwB.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BwwP_1AG.js → chunk-5RXB4S5H-ez-kfSyS.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DDEzW9MV.js → chunk-5VM5RSS4-6L4-OV-3.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D-fLZDni.js → chunk-6Q2QTUOP-CPUweABC.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DY9q3jMo.js → chunk-GF5L2VYU-6DTw-5Ov.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-rkUPkzPh.js → chunk-JWPE2WC7-DFAS-DH8.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Ci9ZksX4.js → chunk-KBJHAD2P-Du7LoER5.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DKU-3Ef6.js → chunk-RYQCIY6F-D9UugPlg.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-A-xOwXvl.js → chunk-XXDRQBXY-BLh5yptc.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DB7nfjpK.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DB7nfjpK.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Bfs1rphL.js → cose-bilkent-JH36ORCC-DjmHXa8h.js} +1 -1
- package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BTlXtGR2.js → cynefin-VYW2F7L2-D5jbf1gi.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-D8c9vCCr.js → cynefinDiagram-MW4NZA55-BudjeLTi.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B-e-tfgY.js → dagre-VZM6K2ZE-6YP-wMO0.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-CG_5dIVJ.js → diagram-7IWD3JNH-CA3LtUAB.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmP40HmK.js → diagram-B4RE2ZJO-BAjJeYaD.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-RFt8vi9Y.js → diagram-LBJQPF4R-Dh4zb-ds.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-CM5Sb2jB.js → diagram-Q27KOJAE-aMKj_Gkp.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-Bm4zh0WJ.js → diagram-UB23O5K3-D_0_rqQ6.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-b3GekSN4.js → ebnfDiagram-BXEA7PRR--C9HfGgB.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CFZh4C_o.js → erDiagram-JOGREHBK-BuqX0vmt.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CzxniD3z.js → flowDiagram-UKHOOZJN-IneEK8zO.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Czp6xUXj.js → ganttDiagram-PKOTCBZU-DK2RiNlb.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-B66oX4sn.js → gitGraphDiagram-DS77QQ5N-CuN5z0rP.js} +1 -1
- package/dist/worker/console/static/assets/{index-BVMJjujb.css → index-CzfumEW1.css} +1 -1
- package/dist/worker/console/static/assets/{index-Bq_vMDO3.js → index-DS6dteCl.js} +159 -147
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-rTveEtft.js → infoDiagram-6WML65LV-B6enpqSl.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-N2jiPnrD.js → ishikawaDiagram-WSZJBQD7-DepH_7eq.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DtnLwtAE.js → journeyDiagram-NVQOT4AX-BftlRwcR.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-t9D_2QMN.js → kanban-definition-27J2QSJJ-CEIZMo9g.js} +1 -1
- package/dist/worker/console/static/assets/{linear-BP6ZG0tB.js → linear-DkgtGbsw.js} +1 -1
- package/dist/worker/console/static/assets/{mermaid.core-Cc5_ZtUy.js → mermaid.core-CIMKKPgL.js} +5 -5
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zztwmHj8.js → mindmap-definition-FAOFIHXS-dzbp1VuW.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CmXQOyPH.js → pegDiagram-VL7TDLO6-C5b5i7KO.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BodwfpEp.js → pieDiagram-7S7Q4E2Y-Ugdko1lm.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DIgybsTM.js → quadrantDiagram-CIZ2JOQS-B2s1OZu8.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CZb_4Cv2.js → railroadDiagram-AXF67PYL-BVafp-Z6.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BvRNauBA.js → requirementDiagram-LRYGKXZP-BVxBjdbs.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BQ30kRWi.js → sankeyDiagram-W5VNT64P-CorSImxl.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-B7sGR3r3.js → sequenceDiagram-SI44F4Z6-eVj3geQV.js} +1 -1
- package/dist/worker/console/static/assets/{sheet-workbook-CK8pzw-q.js → sheet-workbook-DNnJDCal.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-1HZrTeyl.js → sizeCapture-X5ZJPWSS-OQWfzgrL.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-BKCXlJRS.js → stateDiagram-OKZ733FA-DJr_pPmG.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cr-50jJB.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BhT8u6Vm.js → swimlanes-SLNWSIFB-CQG0Q9vK.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-kZpEmem6.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Dnczuw3j.js → timeline-definition-Z64GVDOM-DxWuWIZ5.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-PgJCj-16.js → vennDiagram-T6HMQDX7-BJt03ecs.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BjuszbFn.js → wardleyDiagram-T6FBY63Y-BB3rPfNJ.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dhtjuxrn.js → xychartDiagram-ELKLHX3M-aVR9TCu0.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +99 -16
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +27 -5
- package/dist/worker/console/static-src/operator-chat/vcp-fonts.js +1 -6
- package/dist/worker/console/workspace-context.js +56 -1
- package/dist/worker/observe/static/dag-history-labels.js +2 -0
- package/dist/worker/observe/static/views/dag.js +28 -0
- package/dist/workflows/dag/frontend-durable-tools.js +5 -2
- package/dist/workflows/dag/frontend-implementation-contract.js +19 -6
- package/dist/workflows/dag/frontend-recovery-run.js +20 -1
- package/dist/workflows/dag/frontend-review-scopes.js +2 -2
- package/dist/workflows/dag/frontend-session-budget.js +1 -1
- package/dist/workflows/dag/frontend-writer-baseline-guard.js +11 -5
- package/dist/workflows/dag/hybrid/templates/frontend.js +35 -5
- package/dist/workflows/dag/prompt.js +8 -2
- package/dist/workflows/dag/rerun-plan.js +50 -3
- package/dist/workflows/dag/rerun-run.js +4 -0
- package/dist/workflows/dag/runner.js +11 -0
- package/package.json +6 -3
- package/dist/worker/console/static/assets/channel-BddnaJc4.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CqfGeesl.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CqfGeesl.js +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DzDcqZJM.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DgnnY3K8.js +0 -8
- package/dist/worker/console/static/vcp/fonts/Lanxi-GreatVibes.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-MaShanZheng.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-/347/202/271/351/273/221.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-/351/235/231/351/273/221/350/266/205/347/273/206.woff2 +0 -0
- package/dist/worker/console/static/vcp/fonts/Lanxi-/351/261/274/345/260/276/350/241/214/344/271/246.woff2 +0 -0
|
@@ -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
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
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
|
|
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 (
|
|
346
|
+
if (canonicalIds.has(id) || !id.startsWith(prefix))
|
|
315
347
|
return id;
|
|
316
348
|
const base = id.slice(prefix.length);
|
|
317
|
-
|
|
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
|
-
|
|
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}:
|
|
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
|
-
|
|
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,4 +1,21 @@
|
|
|
1
1
|
const CHECKPOINT_MAX_BYTES = 12 * 1024;
|
|
2
|
+
function truncateUtf8(value, maxBytes) {
|
|
3
|
+
if (Buffer.byteLength(value, "utf8") <= maxBytes)
|
|
4
|
+
return value;
|
|
5
|
+
const ellipsis = "…";
|
|
6
|
+
const ellipsisBytes = Buffer.byteLength(ellipsis, "utf8");
|
|
7
|
+
const budget = Math.max(0, maxBytes - ellipsisBytes);
|
|
8
|
+
let result = "";
|
|
9
|
+
let used = 0;
|
|
10
|
+
for (const character of Array.from(value)) {
|
|
11
|
+
const bytes = Buffer.byteLength(character, "utf8");
|
|
12
|
+
if (used + bytes > budget)
|
|
13
|
+
break;
|
|
14
|
+
result += character;
|
|
15
|
+
used += bytes;
|
|
16
|
+
}
|
|
17
|
+
return `${result}${ellipsis}`;
|
|
18
|
+
}
|
|
2
19
|
function boundText(value, maxChars) {
|
|
3
20
|
if (typeof value !== "string" || !value.trim())
|
|
4
21
|
return "";
|
|
@@ -92,10 +109,13 @@ export function buildOverflowCheckpoint(input) {
|
|
|
92
109
|
if (!firstKeptEntryId || tokensBefore === undefined)
|
|
93
110
|
return undefined;
|
|
94
111
|
const sections = [
|
|
95
|
-
"Deterministic
|
|
112
|
+
"Deterministic local compaction checkpoint (no extra summary request).",
|
|
96
113
|
boundText(preparation?.previousSummary, 2000)
|
|
97
114
|
? `Previous summary:\n${boundText(preparation?.previousSummary, 2000)}`
|
|
98
115
|
: "",
|
|
116
|
+
boundText(input.customInstructions, 800)
|
|
117
|
+
? `Compaction instructions:\n${boundText(input.customInstructions, 800)}`
|
|
118
|
+
: "",
|
|
99
119
|
extractLastUserGoal(preparation?.messagesToSummarize)
|
|
100
120
|
? `Latest user goal:\n${extractLastUserGoal(preparation?.messagesToSummarize)}`
|
|
101
121
|
: "",
|
|
@@ -109,8 +129,6 @@ export function buildOverflowCheckpoint(input) {
|
|
|
109
129
|
"Next step: continue the interrupted turn from the kept recent messages. Do not repeat completed file writes.",
|
|
110
130
|
].filter(Boolean);
|
|
111
131
|
let summary = sections.join("\n\n");
|
|
112
|
-
|
|
113
|
-
summary = `${summary.slice(0, CHECKPOINT_MAX_BYTES - 1)}…`;
|
|
114
|
-
}
|
|
132
|
+
summary = truncateUtf8(summary, CHECKPOINT_MAX_BYTES);
|
|
115
133
|
return { summary, firstKeptEntryId, tokensBefore };
|
|
116
134
|
}
|
|
@@ -118,9 +118,13 @@ export function applyProcessCompactionOverride(manager, input) {
|
|
|
118
118
|
? deriveEffectiveWindow(input.contextWindow, input.policy)
|
|
119
119
|
: undefined;
|
|
120
120
|
const compaction = { enabled };
|
|
121
|
+
if (enabled) {
|
|
122
|
+
compaction.keepRecentTokens = Number.isFinite(input.keepRecentTokens)
|
|
123
|
+
? Math.max(0, Math.floor(input.keepRecentTokens))
|
|
124
|
+
: DEFAULT_KEEP_RECENT_TOKENS;
|
|
125
|
+
}
|
|
121
126
|
if (window && enabled) {
|
|
122
127
|
compaction.reserveTokens = window.recommendedReserve;
|
|
123
|
-
compaction.keepRecentTokens = DEFAULT_KEEP_RECENT_TOKENS;
|
|
124
128
|
}
|
|
125
129
|
manager.applyOverrides({ compaction });
|
|
126
130
|
return {
|
|
@@ -1,13 +1,17 @@
|
|
|
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";
|
|
4
|
-
import { shouldRewriteAssistantOverflow } from "./overflow.js";
|
|
5
|
+
import { isContextOverflow, shouldRewriteAssistantOverflow } from "./overflow.js";
|
|
5
6
|
import { clearRetrieveBypass, compressProviderPayload, createSiftRetrieveToolDefinition, SIFT_RETRIEVE_TOOL_NAME, } from "./sift-bridge.js";
|
|
6
7
|
import { emptyContextPressureCounters, incrementCounter, } from "./telemetry.js";
|
|
7
8
|
export function createCompactionController() {
|
|
8
9
|
return {
|
|
9
10
|
proactiveCompaction: false,
|
|
11
|
+
manualCheckpointFallbackArmed: false,
|
|
10
12
|
pruneArmed: false,
|
|
13
|
+
pruneStatus: undefined,
|
|
14
|
+
pruneDiagnostic: undefined,
|
|
11
15
|
counters: emptyContextPressureCounters(),
|
|
12
16
|
};
|
|
13
17
|
}
|
|
@@ -53,6 +57,14 @@ export function createContextPressureExtension(options) {
|
|
|
53
57
|
});
|
|
54
58
|
}
|
|
55
59
|
if (l2) {
|
|
60
|
+
api.on("session_compact_failed", (event) => {
|
|
61
|
+
if (event.reason === "manual" &&
|
|
62
|
+
!event.aborted &&
|
|
63
|
+
isContextOverflow(event.errorMessage)) {
|
|
64
|
+
options.controller.manualCheckpointFallbackArmed = true;
|
|
65
|
+
}
|
|
66
|
+
return undefined;
|
|
67
|
+
});
|
|
56
68
|
api.on("session_before_compact", (event) => {
|
|
57
69
|
const reason = event.reason;
|
|
58
70
|
if (reason === "overflow") {
|
|
@@ -63,13 +75,17 @@ export function createContextPressureExtension(options) {
|
|
|
63
75
|
if (reason === "manual") {
|
|
64
76
|
incrementCounter(options.controller.counters, "manual");
|
|
65
77
|
}
|
|
66
|
-
const useCheckpoint =
|
|
67
|
-
(reason === "
|
|
68
|
-
|
|
78
|
+
const useCheckpoint = reason === "overflow" ||
|
|
79
|
+
(reason === "manual" &&
|
|
80
|
+
options.controller.manualCheckpointFallbackArmed);
|
|
69
81
|
if (!useCheckpoint)
|
|
70
82
|
return undefined;
|
|
83
|
+
if (reason === "manual") {
|
|
84
|
+
options.controller.manualCheckpointFallbackArmed = false;
|
|
85
|
+
}
|
|
71
86
|
const checkpoint = buildOverflowCheckpoint({
|
|
72
87
|
preparation: event.preparation,
|
|
88
|
+
customInstructions: event.customInstructions,
|
|
73
89
|
todos: options.controller.todos,
|
|
74
90
|
lastError: options.controller.lastError,
|
|
75
91
|
});
|
|
@@ -92,8 +108,51 @@ export function createContextPressureExtension(options) {
|
|
|
92
108
|
const messages = Array.isArray(event.messages) ? event.messages : [];
|
|
93
109
|
try {
|
|
94
110
|
const result = prunePiToolResultMessages(messages, options.prune);
|
|
95
|
-
if (!result.changed)
|
|
111
|
+
if (!result.changed) {
|
|
112
|
+
options.controller.pruneStatus = "armed-but-no-candidate";
|
|
113
|
+
options.controller.pruneDiagnostic = "已达到压缩条件,但没有可清理的工具结果";
|
|
96
114
|
return undefined;
|
|
115
|
+
}
|
|
116
|
+
let durableCount = 0;
|
|
117
|
+
const adapter = options.contextEdit?.();
|
|
118
|
+
if (adapter) {
|
|
119
|
+
for (const change of result.changes) {
|
|
120
|
+
try {
|
|
121
|
+
const applied = adapter.replaceToolResult(change.sourceMessage, change.replacementMessage);
|
|
122
|
+
if (!applied)
|
|
123
|
+
continue;
|
|
124
|
+
options.onPrune?.({
|
|
125
|
+
pruneId: randomUUID(),
|
|
126
|
+
replacementId: randomUUID(),
|
|
127
|
+
sourcePiEntryId: applied.sourcePiEntryId,
|
|
128
|
+
contextEditEntryId: applied.contextEditEntryId,
|
|
129
|
+
...(applied.toolCallId ? { toolCallId: applied.toolCallId } : {}),
|
|
130
|
+
replacementMessage: change.replacementMessage,
|
|
131
|
+
charsBefore: change.charsBefore,
|
|
132
|
+
charsAfter: change.charsAfter,
|
|
133
|
+
accounting: "estimated-chars",
|
|
134
|
+
});
|
|
135
|
+
durableCount += 1;
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// Durable editing is fail-open; keep the in-memory replacement.
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (durableCount === 0) {
|
|
143
|
+
options.controller.pruneStatus = adapter ? "candidate-but-no-pi-binding" : "in-memory-only";
|
|
144
|
+
options.controller.pruneDiagnostic = adapter
|
|
145
|
+
? "找到可清理内容,但当前 Pi 会话没有可用的稳定绑定"
|
|
146
|
+
: "已在本次请求中清理,当前 Pi 会话不支持持久化编辑";
|
|
147
|
+
}
|
|
148
|
+
else if (durableCount === result.changes.length) {
|
|
149
|
+
options.controller.pruneStatus = "durable-completed";
|
|
150
|
+
options.controller.pruneDiagnostic = undefined;
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
options.controller.pruneStatus = "durable-pending";
|
|
154
|
+
options.controller.pruneDiagnostic = "部分内容已清理,剩余关系等待恢复";
|
|
155
|
+
}
|
|
97
156
|
options.controller.counters.toolResultPruned += result.messagesPruned;
|
|
98
157
|
options.controller.counters.charsPrunedEstimate += result.charsRemoved;
|
|
99
158
|
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
|
-
|
|
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
|
}
|
|
@@ -11,6 +11,8 @@ export function emptyContextPressureCounters() {
|
|
|
11
11
|
blocksCompressed: 0,
|
|
12
12
|
toolResultPruned: 0,
|
|
13
13
|
charsPrunedEstimate: 0,
|
|
14
|
+
pruneStatus: undefined,
|
|
15
|
+
pruneDiagnostic: undefined,
|
|
14
16
|
};
|
|
15
17
|
}
|
|
16
18
|
export function incrementCounter(counters, reason, amount = 1) {
|
|
@@ -51,5 +53,7 @@ export function projectSafeTelemetry(counters) {
|
|
|
51
53
|
blocksCompressed: counters.blocksCompressed,
|
|
52
54
|
toolResultPruned: counters.toolResultPruned,
|
|
53
55
|
charsPrunedEstimate: counters.charsPrunedEstimate,
|
|
56
|
+
...(counters.pruneStatus ? { pruneStatus: counters.pruneStatus } : {}),
|
|
57
|
+
...(counters.pruneDiagnostic ? { pruneDiagnostic: counters.pruneDiagnostic } : {}),
|
|
54
58
|
};
|
|
55
59
|
}
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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) =>
|
|
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.
|
|
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
|
+
}
|