@tea-agent/loop-agent 0.52.0 → 0.53.0-next.1

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 (34) hide show
  1. package/CHANGELOG.md +97 -5
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/dag-pi/plan/finalize-tools.js +13 -0
  4. package/dist/executors/dag-pi/plan/record-tools.js +37 -11
  5. package/dist/executors/dag-pi/sessions/plan-batches.js +1 -1
  6. package/dist/executors/dag-pi/sessions/segmented-plan.js +28 -20
  7. package/dist/executors/dag-pi/tools/plan-decision-tools.js +2 -1
  8. package/dist/executors/dag-pi-executor.js +50 -5
  9. package/dist/executors/pi-executor.js +12 -0
  10. package/dist/executors/pi-sdk-executor.js +2 -2
  11. package/dist/shared/frontend-execution-policy.js +28 -2
  12. package/dist/task/config-types.js +2 -2
  13. package/dist/task/source-prepare/prepare.js +1 -1
  14. package/dist/task/source-prepare/semantic-intake.js +2 -2
  15. package/dist/task/source-prepare/source-fidelity-pi.js +2 -1
  16. package/dist/workflows/dag/checkpoint.js +6 -1
  17. package/dist/workflows/dag/frontend-committed-facts.js +38 -5
  18. package/dist/workflows/dag/frontend-design-policy.js +22 -0
  19. package/dist/workflows/dag/frontend-implementation-contract.js +39 -12
  20. package/dist/workflows/dag/frontend-imported-run-artifacts.js +126 -0
  21. package/dist/workflows/dag/frontend-recovery-run.js +7 -110
  22. package/dist/workflows/dag/frontend-test-framework-adapters.js +14 -0
  23. package/dist/workflows/dag/frontend-verification-trace.js +20 -8
  24. package/dist/workflows/dag/frontend-writer-reuse.js +104 -0
  25. package/dist/workflows/dag/frontend-writer-status.js +0 -4
  26. package/dist/workflows/dag/hybrid/templates/frontend.js +15 -8
  27. package/dist/workflows/dag/init-hybrid.js +1 -1
  28. package/dist/workflows/dag/reconcile-run.js +11 -1
  29. package/dist/workflows/dag/recovery-lease.js +23 -0
  30. package/dist/workflows/dag/rerun-feedback.js +4 -2
  31. package/dist/workflows/dag/rerun-run.js +40 -0
  32. package/dist/workflows/dag/runner.js +11 -0
  33. package/dist/workflows/dag/terminal-status.js +2 -1
  34. package/package.json +3 -3
@@ -0,0 +1,104 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, readFile, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
5
+ export async function captureFrontendReuseSnapshot(workspaceRoot, contract) {
6
+ const files = {};
7
+ const root = await realpath(workspaceRoot);
8
+ const targets = [...new Set([
9
+ ...contract.requirements.flatMap(r => r.implementationTargets),
10
+ ...contract.verificationTargets.map(t => t.file),
11
+ ])].sort();
12
+ for (const target of targets) {
13
+ try {
14
+ const resolved = path.resolve(root, target);
15
+ const relative = path.relative(root, await realpath(resolved));
16
+ if (relative.startsWith("..") || path.isAbsolute(relative) || !(await lstat(resolved)).isFile())
17
+ continue;
18
+ files[target] = hash(await readFile(resolved));
19
+ }
20
+ catch { /* Missing/unreadable targets cannot be reused. */ }
21
+ }
22
+ return { contractSha256: hash(JSON.stringify(contract)), files };
23
+ }
24
+ export function deriveFrontendReuseEvidence(input) {
25
+ const { baseline, current, contract } = input;
26
+ if (!baseline || !input.guardOk || !input.checksComplete ||
27
+ baseline.contractSha256 !== current.contractSha256 ||
28
+ current.contractSha256 !== hash(JSON.stringify(contract)))
29
+ return;
30
+ const passes = (checks, id) => {
31
+ const found = (checks ?? []).filter(c => c.commandId === id);
32
+ return found.length === 1 && found[0].exitCode === 0 &&
33
+ found[0].failureCategory === "success" && Boolean(found[0].command.trim());
34
+ };
35
+ const unchanged = (file) => Boolean(baseline.files[file]) &&
36
+ baseline.files[file] === current.files[file] && !input.writtenPaths.includes(file);
37
+ // Keep verification inputs unchanged: changing tests cannot certify baseline reuse.
38
+ for (const target of contract.verificationTargets) {
39
+ if (!unchanged(target.file) || !passes(input.baselineChecks, target.commandId) ||
40
+ !passes(input.currentChecks, target.commandId))
41
+ return;
42
+ const before = input.baselineChecks.find(c => c.commandId === target.commandId);
43
+ const after = input.currentChecks.find(c => c.commandId === target.commandId);
44
+ if (before.command !== after.command)
45
+ return;
46
+ }
47
+ if (!contract.verificationTargets.length)
48
+ return;
49
+ const requirementTargets = [...new Set(contract.requirements.flatMap(r => r.implementationTargets))]
50
+ .filter(file => unchanged(file) && contract.requirements.filter(r => r.implementationTargets.includes(file))
51
+ .every(r => r.verificationTargetIds.length > 0 && r.verificationTargetIds.every(id => contract.verificationTargets.some(t => t.id === id && t.requirementIds.includes(r.id)))))
52
+ .sort();
53
+ if (!requirementTargets.length)
54
+ return;
55
+ const proofSha256 = hash(JSON.stringify({ baseline, current, requirementTargets,
56
+ baselineChecks: input.baselineChecks, currentChecks: input.currentChecks }));
57
+ return { requirementTargets, proofSha256 };
58
+ }
59
+ /**
60
+ * Presence/identity evidence for untouched files during a genuine partial repair.
61
+ * Changed verification inputs are recorded, not used to certify a no-op. This
62
+ * evidence may satisfy slice omissions/dependencies, NEVER alreadySatisfied.
63
+ */
64
+ export function deriveFrontendRetainedTargetEvidence(input) {
65
+ const { baseline, current, contract } = input;
66
+ if (!baseline || !input.guardOk || !input.checksComplete ||
67
+ baseline.contractSha256 !== current.contractSha256 ||
68
+ current.contractSha256 !== hash(JSON.stringify(contract)) ||
69
+ !contract.verificationTargets.length)
70
+ return;
71
+ // Every frozen check must be unambiguous and green, with the same command
72
+ // bytes before/after. Trace preflight is separately included in checksComplete.
73
+ const commandIds = [...new Set(contract.verificationTargets.map(target => target.commandId))];
74
+ for (const id of commandIds) {
75
+ const before = input.baselineChecks?.filter(check => check.commandId === id) ?? [];
76
+ const after = input.currentChecks?.filter(check => check.commandId === id) ?? [];
77
+ if (before.length !== 1 || after.length !== 1)
78
+ return;
79
+ const a = before[0];
80
+ const b = after[0];
81
+ if (!a.command.trim() || a.command !== b.command || a.exitCode !== 0 || b.exitCode !== 0 ||
82
+ a.failureCategory !== "success" || b.failureCategory !== "success")
83
+ return;
84
+ }
85
+ const written = new Set(input.writtenPaths);
86
+ const changed = input.writerChangedPaths.filter(file => written.has(file) &&
87
+ Boolean(current.files[file]) && baseline.files[file] !== current.files[file]);
88
+ // A shell side effect, failed/reverted edit, or model claim is not a repair.
89
+ if (!changed.length)
90
+ return;
91
+ const retainedTargets = [...new Set(contract.requirements.flatMap(r => r.implementationTargets))]
92
+ .filter(file => Boolean(baseline.files[file]) && baseline.files[file] === current.files[file] &&
93
+ !written.has(file) && contract.requirements.filter(r => r.implementationTargets.includes(file))
94
+ .every(r => r.verificationTargetIds.length > 0 && r.verificationTargetIds.every(id => contract.verificationTargets.some(t => t.id === id && t.requirementIds.includes(r.id)))))
95
+ .sort();
96
+ if (!retainedTargets.length)
97
+ return;
98
+ const verificationInputChanges = [...new Set(contract.verificationTargets.map(target => target.file))]
99
+ .filter(file => baseline.files[file] !== current.files[file] || written.has(file)).sort();
100
+ const proofSha256 = hash(JSON.stringify({ baseline, current, retainedTargets, verificationInputChanges,
101
+ writerChangedPaths: changed.sort(), writtenPaths: [...written].sort(),
102
+ baselineChecks: input.baselineChecks, currentChecks: input.currentChecks }));
103
+ return { retainedTargets, verificationInputChanges, proofSha256 };
104
+ }
@@ -115,7 +115,6 @@ export const DEFAULT_FRONTEND_MICRO_LOOP_BUDGET = {
115
115
  maxFocusedCheckRounds: 2,
116
116
  maxWriteAttempts: 5,
117
117
  maxWallTimeMs: 15 * 60 * 1000,
118
- maxTokens: 200_000,
119
118
  maxRepeatedFingerprints: 2,
120
119
  };
121
120
  /**
@@ -151,9 +150,6 @@ export function evaluateMicroLoopContinuation(budget, history, startWallTimeMs,
151
150
  if (last.writeAttempts >= budget.maxWriteAttempts) {
152
151
  return { continue: false, reason: "budget-write-attempts" };
153
152
  }
154
- if (last.tokensUsed >= budget.maxTokens) {
155
- return { continue: false, reason: "budget-tokens" };
156
- }
157
153
  const repeatCount = history.filter((round) => round.fingerprint === last.fingerprint).length;
158
154
  if (repeatCount >= budget.maxRepeatedFingerprints) {
159
155
  return { continue: false, reason: "budget-repeated-fingerprint" };
@@ -337,10 +337,12 @@ export async function buildFrontendHybridDagFromTask(sources) {
337
337
  riskLevel: frontendRisk.selectedRisk,
338
338
  targetFiles: implementPaths.writeSet,
339
339
  });
340
+ const sourceScopeInstruction = "Source expectedOutcome outranks derived state/interaction prose. Keep human resolutions within named operations/ACs; shared retries do not share snapshot semantics. Report scope expansion as a plan gap, never a new implementation requirement.";
340
341
  const frontendContractFieldSummary = [
341
342
  "## Contract field summary (authoritative JSON; no plan prose)",
342
- "frontend-plan-pi records typed facts; frontend-design-policy-shell applies the runtime skeleton, validates, and materializes the canonical full contract JSON supplied here. There is no separate plan prose authority. Review these fields:",
343
+ "Typed Plan facts + runtime skeleton produce the canonical contract JSON. Fields:",
343
344
  "- requirements[]: id, expectedOutcome, implementationTargets, verificationTargetIds, evidenceGap",
345
+ sourceScopeInstruction,
344
346
  "- uiStates[]: name, applicable, expectedBehavior, implementationTargets, verificationTargetIds, notApplicableReason",
345
347
  "- interactions[]: name, trigger, expectedBehavior, implementationTargets, verificationTargetIds",
346
348
  "- targets: routes, publicApiChanges (files are runtime-owned)",
@@ -349,7 +351,7 @@ export async function buildFrontendHybridDagFromTask(sources) {
349
351
  "- designEvidence: source, paths, conflicts; evidenceGaps[] (optional)",
350
352
  "- optional: stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
351
353
  "- uiComponentChoices[]: purpose, component, decision (specified|reuse-existing|new), specReference { path, section, line } | null, rationale",
352
- "Do not require or read a separate plan prose section; the contract JSON is the only plan surface.",
354
+ "Only contract JSON is authoritative; no separate plan prose.",
353
355
  ].join("\n");
354
356
  // Do not carry every attachment through the whole frontend pipeline. The
355
357
  // contract node is the sole requirements/materials synthesis point; scout
@@ -805,7 +807,7 @@ export async function buildFrontendHybridDagFromTask(sources) {
805
807
  },
806
808
  outputContract: "Typed decision patch only: map frozen requirements to implementation/verification targets and select the needed component, state, data/Mock, styling, and dependency decisions. Use only the record_* tools needed to express those decisions, then call finalize_plan; correct rejected facts until one successful terminal. Contract owns requirement semantics; Scout owns repository discovery; deterministic runtime owns schema, protected fields, path containment, and command validation. No Markdown narrative or file writes.",
807
809
  subtask_prompt: [
808
- "Plan only the delta between the frozen frontend-contract-pi facts and frontend-scout-pi target surface. Do not reinterpret the task, repeat requirements, or search the repository.",
810
+ "Plan only the delta from frozen Contract facts and Scout targets; no reinterpretation, repeated requirements, or repository search.",
809
811
  "Record only: requirement-to-file/verification coverage; component/styling choices; applicable UI state and interaction behavior; data/Mock strategy; and a dependency policy or genuine evidence gap. Reuse Scout paths. If scope is missing, record a blocking gap instead of inventing a path.",
810
812
  "Use the typed tool schemas as the field contract. Runtime owns schemaVersion, sourceBinding, riskLevel, targets.files, mockApi.productionDefaultOff, aliases, command allowlisting, path containment, and final validation; do not restate those rules or emit a full JSON contract.",
811
813
  `Cover each frozen requirement ID exactly once: ${requirementIds.join(", ") || "(none)"}. Bind every verification target to a frozen commandId from the directory above plus a Scout-confirmed file. Behavior commands prove observable behavior: one target may cover multiple related requirementIds when one test behavior proves them together; do not mechanically create one target per requirement. A behavior target id is the stable machine trace token and its file must be a test file. Static commands are project-wide checks traced by file and command only.`,
@@ -909,6 +911,7 @@ export async function buildFrontendHybridDagFromTask(sources) {
909
911
  subtask_prompt: [
910
912
  "Submit findings individually with record_design_finding and stable IDs; terminal tools aggregate saved findings. Correct rejected calls, stop after a successful terminal. Check execution groups against every member source outcome, including permission, threshold and failure-path differences; shared verification is valid only when it proves each independent AC.",
911
913
  "After the typed design terminal succeeds, stop immediately; do not emit a Markdown recap.",
914
+ sourceScopeInstruction,
912
915
  "Audit the frontend plan before implementation. frontend-plan-pi is emitted to you as canonical full-contract JSON after the runtime applied and validated the planner's editable patch against its protected skeleton; there is no separate plan prose.",
913
916
  "Your authoritative terminal verdict is exactly one committed typed tool call: approve_design or request_design_changes. Call exactly one of them; after calling one, do not call the other.",
914
917
  "request_design_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
@@ -986,16 +989,16 @@ export async function buildFrontendHybridDagFromTask(sources) {
986
989
  outputContract: "The implementation status is derived by the executor from mechanical facts (write-tool events, run delta, write guard, requirement coverage, focused-check), not from any IMPLEMENTATION_OUTCOME first line. Deliver a Markdown summary with Contract Ref (path/schema/hash), Changed Files, Requirements Implemented, UI States, Tests Changed, Verification Attempts, Deviations, and Residual Risks. When implementationSlices exist, report work in dependency order with tests/checks kept in each slice. Otherwise report the fixed stages: contract confirm → tests → component/state → API/Mock → focused checks → diff cleanup.",
987
990
  subtask_prompt: [
988
991
  "Implement against the validated run-owned Frontend Implementation Contract materialized by frontend-design-policy-shell (path/schema/hash) and authorized by frontend-writer-admission-shell. Do not rebuild the contract from Markdown alone.",
989
- "WRITER TOOL PROTOCOL (hard): the response text is not delivery. Never paste source code, test code, or full file contents into chat. After reading the canonical contract, make the first implementation change with the structured write/edit tool (one file per call); continue writing through those tools until the writeSet is complete. If a write/edit tool is unavailable, stop and report the blocked capability instead of drafting code in the response.",
992
+ "WRITER TOOL PROTOCOL (hard): the response text is not delivery. Never paste source code, test code, or full file contents into chat. Read the canonical contract and assess its target files before editing. For each necessary change, identify the concrete requirement gap and use the structured write/edit tool (one file per call). If no concrete requirement gap is found, make no edits and report the existing implementation evidence. Never manufacture edits merely to touch every writeSet path. A no-op requires runtime proof: matching pre/post fingerprints, unchanged verification inputs, passing frozen checks before and after the session, and passing guard/trace checks. Formal Verify and final review still decide acceptance. If a necessary edit cannot be made because the write/edit tool is unavailable, report the blocked capability instead of drafting code in the response.",
990
993
  "The canonical contract already contains the approved requirement, target-file, UI-state, verification, design, and Mock/API decisions. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, or design-review prose, and do not repeat broad repository research. Inspect only contract target files and directly related local code needed to implement them.",
991
994
  "When the contract has no implementationSlices, execute and report these fixed stages: (1) Contract confirm, (2) Tests sync, (3) Component/UI state implementation, (4) API/Mock wiring per contract.mockApi, (5) Focused checks behind frozen entrypoints only, (6) Diff cleanup. When slices exist, follow their dependency order and keep each slice's tests/checks with its implementation.",
992
- "SLICE ORDER (when the contract carries implementationSlices): the slices ARE the execution order, not a suggestion. Work one slice at a time in the contract's order (prerequisites first), finish every targetPath of the current slice before starting the next, and keep its tests/checks with its own slice instead of deferring all tests to the end. A slice is complete when its own targetPaths are written and its requirements are covered; then move to the next slice. Do not reorder slices, skip a slice, or widen a slice beyond its own targetPaths. If a slice turns out to be impossible, stop and report which slice and why rather than silently implementing a different order. When the contract has no implementationSlices, keep the fixed stages above.",
995
+ "SLICE ORDER (when the contract carries implementationSlices): the slices ARE the execution order, not a suggestion. Work one slice at a time in the contract's order (prerequisites first), assess every targetPath of the current slice and finish its necessary edits before starting the next, and keep its tests/checks with its own slice instead of deferring all tests to the end. A slice is complete when its requirements are covered and its targetPaths have either successful writes or runtime-verified reuse evidence; then move to the next slice. Do not reorder slices, skip a slice, or widen a slice beyond its own targetPaths. If a slice turns out to be impossible, stop and report which slice and why rather than silently implementing a different order. When the contract has no implementationSlices, keep the fixed stages above.",
993
996
  "Map every requirement id, expectedOutcome, interaction trigger/expectedBehavior, and applicable UI state from the contract to concrete files. Do not invent shell verification commands; only frozen static/behavior entrypoints will run.",
994
997
  "A behavior verification target's target.id is only the contract's identifier for that entry; it does not need to appear in test titles. Never add tests, rename describe/it/test titles, or restructure files just to carry generated ids — reuse affected existing test files and their names. The requirement ↔ verification-target association lives in the contract (requirementIds / verificationTargetIds), not in title strings.",
995
- "Begin implementation after the contract and its target files are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, stop and state the blocking reason in the summary instead of reopening broad discovery.",
998
+ "Begin necessary implementation changes only after the contract, its target files, and concrete requirement gaps are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, stop and state the blocking reason in the summary instead of reopening broad discovery.",
996
999
  "Your implementation status is derived by the executor from mechanical facts (persisted write-tool events, run delta, write guard, requirement coverage, focused-check failures), never from any IMPLEMENTATION_OUTCOME first line. Do not emit an IMPLEMENTATION_OUTCOME first line.",
997
1000
  "After the write session the executor re-runs the frozen trace preflight against the contract AND runs the frozen commands bound to its verification targets from the generation-time command directory, recording each command's id and exit code plus a per-round diff checkpoint (changed files, write guard verdict, failure fingerprint, budget); the write guard stays active for the whole session. A target whose declared file merely exists is not a passing check. Repair only local issues attributable to your current diff (syntax/type/import/format/unit-assert/obvious omission). Never change requirements, design, writeSet, or verification strictness. The full frozen command set remains frontend-verify-shell's authority — a green local check is not proof of behavior.",
998
- "When the contract declares implementationSlices, the executor derives slice progress from the write tools you actually called (order, per-slice completion, omitted targets, out-of-slice paths) and records it as writer-slice-progress.json. Implementing a slice before its declared prerequisite, or never writing a declared slice target, is a local failure that triggers a bounded repair round — the SLICE ORDER constraint above is checked against observed writes, not trusted from your summary.",
1001
+ "When the contract declares implementationSlices, the executor derives slice progress from the write tools you actually called (order, per-slice completion, omitted targets, out-of-slice paths) and records it as writer-slice-progress.json. Implementing a slice before its declared prerequisite, or leaving a declared slice target without successful writes or runtime-verified reuse evidence, is a local failure that triggers a bounded repair round — the SLICE ORDER constraint above is checked against observed writes, not trusted from your summary.",
999
1002
  "Implement only the approved Mock strategy carried by the validated contract. Preserve the real request path as the default, require explicit test/dev activation, and never comment out or replace the real request with inline data.",
1000
1003
  "frontend-design-policy-shell materialized and validated the canonical contract; frontend-writer-admission-shell authorized the writeSet. Stay within writeSet and preserve unrelated files.",
1001
1004
  "For native, browser-intercept, or request-adapter, implement contract-aligned fixtures/states and a dev/test-only activation boundary in this same writer. For not-needed, do not add Mock files or a framework and state the positive reason.",
@@ -1080,6 +1083,8 @@ export async function buildFrontendHybridDagFromTask(sources) {
1080
1083
  "Submit findings individually with record_review_finding and stable IDs; terminal tools aggregate saved findings. Correct rejected calls, stop after a successful terminal. Check execution groups against every member source outcome, including permission, threshold and failure-path differences; shared verification is valid only when it proves each independent AC.",
1081
1084
  "After the typed review terminal succeeds, stop immediately; do not emit a Markdown recap.",
1082
1085
  "Review the frontend implementation and verification evidence.",
1086
+ "Before claiming a missing guard, trace the caller through the state-changing branch; cite a reachable failing path, not an isolated API helper or fixture.",
1087
+ sourceScopeInstruction,
1083
1088
  "Your authoritative terminal verdict is exactly one committed typed tool call: approve_review or request_review_changes. Call it once and do not call the other afterwards.",
1084
1089
  "approve_review means the implementation passes; it must not carry Critical or Important findings. request_review_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
1085
1090
  "Do NOT emit an equivalent JSON verdict in the response text: the committed typed terminal fact is the only authority and no branch or gate reads response-text JSON verdicts.",
@@ -1199,7 +1204,9 @@ export async function buildFrontendHybridDagFromTask(sources) {
1199
1204
  const frontendMaxContinuations = sources.taskConfig.frontendRecovery?.maxContinuations ?? 1;
1200
1205
  spec.frontendRecovery = { maxContinuations: frontendMaxContinuations };
1201
1206
  // Configurable execution safety quota, independent of model context/output capacity.
1202
- spec.budget = { schemaVersion: 1, mode: "hard", limits: { maxProviderRequests: sources.taskConfig.frontendRecovery?.maxProviderRequests ?? 1024 } };
1207
+ if (sources.taskConfig.frontendRecovery?.maxProviderRequests !== null) {
1208
+ spec.budget = { schemaVersion: 1, mode: "hard", limits: { maxProviderRequests: sources.taskConfig.frontendRecovery?.maxProviderRequests ?? 1024 } };
1209
+ }
1203
1210
  spec.frontendExecutionPolicy = frontendExecutionPolicySchema.parse(sources.taskConfig.frontendExecutionPolicy ?? {});
1204
1211
  applyDefaultReadOnlyRetryPolicy(spec);
1205
1212
  stampGeneratedArtifactBindings(spec);
@@ -382,7 +382,7 @@ async function buildHybridDagForTemplate(sources, template, options = {}) {
382
382
  spec.runtimeContract = GENERATED_DAG_RUNTIME_CONTRACT;
383
383
  }
384
384
  spec.sourceBinding = buildDagSourceBinding(sources, template === "frontend-implementation" ? "frontend-implementation" : undefined);
385
- if (template === "frontend-implementation" && sources.repoRoot) {
385
+ if (template === "frontend-implementation" && sources.repoRoot && spec.budget?.limits.maxProviderRequests !== undefined) {
386
386
  const ledger = await readTaskSourceProviderBudget({ repoRoot: sources.repoRoot, taskId: sources.taskId, maxProviderRequests: spec.budget.limits.maxProviderRequests });
387
387
  if (ledger)
388
388
  spec.sourceProviderBudget = { ledger, contract: sourceBudgetContractIdentity(taskContractBinding), sourceBindingSha256: sha256OfCanonicalJson(spec.sourceBinding), evidence: await freezeTaskSourceUsage({ repoRoot: sources.repoRoot, taskId: sources.taskId, maxProviderRequests: ledger.maxProviderRequests }, ledger) };
@@ -1,4 +1,5 @@
1
1
  import path from "node:path";
2
+ import { readDeadContinuationOwner } from "./recovery-lease.js";
2
3
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
3
4
  import { assessDagRunLiveness, assessDagRunRecoveryEligibility, assertDagRunTransferTargetAvailable, getDagRunDir, locateDagRun, readDagRunState, transferDagRunDir, writeDagRunState, } from "./lifecycle.js";
4
5
  export function parseDagReconcileRunArgs(args) {
@@ -48,7 +49,14 @@ export async function executeDagReconcileRun(repoRoot, rawArgs) {
48
49
  if (!located)
49
50
  throw new Error(`dag run not found: ${parsed.runId}`);
50
51
  const state = await readDagRunState(located.runDir);
51
- const liveness = assessDagRunLiveness({ state });
52
+ const continuation = state.continuation;
53
+ const neverStarted = !state.runner && state.status === "running" &&
54
+ continuation?.kind === "rerun-from-node" && Object.values(state.nodes).every((node) => (node.status === "FINISHED" && node.origin?.kind === "imported" && node.origin.parentRunId === continuation.parentRunId) ||
55
+ (node.status === "PENDING" && !node.startedAt && !node.attempts?.length));
56
+ const recoveryOwnerEvidence = neverStarted && continuation
57
+ ? await readDeadContinuationOwner({ cwd: repoRoot, parentRunId: continuation.parentRunId, runId: state.runId, requestId: continuation.requestId })
58
+ : undefined;
59
+ const liveness = recoveryOwnerEvidence ? { status: "orphaned" } : assessDagRunLiveness({ state });
52
60
  const eligibility = assessDagRunRecoveryEligibility({
53
61
  lifecycle: located.lifecycle,
54
62
  state,
@@ -62,6 +70,7 @@ export async function executeDagReconcileRun(repoRoot, rawArgs) {
62
70
  status: state.status,
63
71
  liveness: liveness.status,
64
72
  eligibility,
73
+ ...(recoveryOwnerEvidence ? { recoveryOwnerEvidence } : {}),
65
74
  nextRecommendedAction: eligibility.canReconcile
66
75
  ? "Re-run with --action supersede|abandon and --reason <text>."
67
76
  : "Do not reconcile this run; inspect runner and lifecycle evidence first.",
@@ -86,6 +95,7 @@ export async function executeDagReconcileRun(repoRoot, rawArgs) {
86
95
  previousStatus: state.status,
87
96
  liveness: liveness.status,
88
97
  originalState: state,
98
+ ...(recoveryOwnerEvidence ? { recoveryOwnerEvidence } : {}),
89
99
  });
90
100
  const previousStatus = state.status;
91
101
  for (const node of Object.values(state.nodes)) {
@@ -5,6 +5,29 @@ import path from "node:path";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
7
7
  import { DAG_RUNS_DIR } from "./lifecycle.js";
8
+ /** Read-only evidence for a continuation that failed before runner startup. */
9
+ export async function readDeadContinuationOwner(input) {
10
+ let lease;
11
+ try {
12
+ lease = parseLease(JSON.parse(await readFile(recoveryLeasePath(input.cwd, input.parentRunId), "utf8")), input.parentRunId);
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ if (lease.kind !== "rerun-from-node" || lease.executionRef !== input.runId ||
18
+ lease.requestId !== input.requestId || lease.ownerHostname !== localHostname())
19
+ return undefined;
20
+ try {
21
+ process.kill(lease.ownerPid, 0);
22
+ return undefined;
23
+ }
24
+ catch (error) {
25
+ if (error.code !== "ESRCH")
26
+ return undefined;
27
+ }
28
+ const { leaseToken: _token, ...evidence } = lease;
29
+ return evidence;
30
+ }
8
31
  function recoveryLeasePath(cwd, parentRunId) {
9
32
  // Never derive a filesystem name directly from an externally supplied legacy
10
33
  // run id. The content remains auditable while the filename is traversal-safe.
@@ -385,9 +385,11 @@ export async function deriveDagRerunFeedback(input) {
385
385
  // A committed approval is a resolution barrier and prevents older
386
386
  // findings from being resurrected.
387
387
  const current = await readCurrentFrontendRepairFindings(input.runDir);
388
- if (current?.verdict === "approve")
388
+ // Design approval resolves design findings only. The writer runs after
389
+ // that gate and can still fail; do not discard its recovery feedback.
390
+ if (current?.verdict === "approve" && current.sourceNodeId === FRONTEND_REVIEW_NODE_ID)
389
391
  return undefined;
390
- const typedFact = current ? { nodeId: current.sourceNodeId, fact: current.fact } : await readAncestorTypedRequestFact(input.runDir);
392
+ const typedFact = current?.verdict === "request" ? { nodeId: current.sourceNodeId, fact: current.fact } : await readAncestorTypedRequestFact(input.runDir);
391
393
  if (typedFact) {
392
394
  const parentSourceBindingHash = sourceBindingHash(input.spec);
393
395
  return withDigest({
@@ -1,4 +1,7 @@
1
1
  import { validateCumulativeBudgetSuccessor } from "./budget-enforcement.js";
2
+ import { buildFrontendTopologyBinding } from "./frontend-shape.js";
3
+ import { FRONTEND_SHAPE_BOUNDARIES, isCanonicalFrontendShapeDag } from "./frontend-shape-facts.js";
4
+ import { importFrontendRunArtifacts, prepareFrontendRunArtifacts } from "./frontend-imported-run-artifacts.js";
2
5
  import { createHash, timingSafeEqual } from "node:crypto";
3
6
  import { access, copyFile, lstat, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
4
7
  import path from "node:path";
@@ -741,6 +744,9 @@ async function finalizeContinuationWriterTransaction(input) {
741
744
  return { state: "rolled-back" };
742
745
  }
743
746
  async function stageContinuationRun(input) {
747
+ const preparedFrontendArtifacts = input.preparedFrontendArtifacts ?? await prepareFrontendRunArtifacts({
748
+ parentRunDir: input.parentRunDir, spec: input.parentSpec, importedNodeIds: input.plan.importedNodeIds,
749
+ });
744
750
  const promptAdjustedSpec = input.promptOverrides !== undefined && input.promptOverrides.length > 0
745
751
  ? applyPromptOverridesToSpec({
746
752
  spec: input.parentSpec,
@@ -811,6 +817,21 @@ async function stageContinuationRun(input) {
811
817
  }
812
818
  nodes[nodeId] = buildPendingNodeRecord(task);
813
819
  }
820
+ const frontendArtifacts = await importFrontendRunArtifacts({
821
+ parentRunDir: input.parentRunDir,
822
+ newRunDir: runDir,
823
+ spec: specForRun,
824
+ importedNodeIds: input.plan.importedNodeIds,
825
+ prepared: preparedFrontendArtifacts,
826
+ });
827
+ for (const { nodeId, ...artifact } of frontendArtifacts.nodeArtifacts) {
828
+ const owner = importManifestNodes.find(node => node.nodeId === nodeId);
829
+ if (!owner)
830
+ throw new Error(`frontend imported artifact owner missing: ${nodeId}`);
831
+ if (!owner.importedArtifacts.some(entry => entry.destinationRelativePath === artifact.destinationRelativePath)) {
832
+ owner.importedArtifacts.push(artifact);
833
+ }
834
+ }
814
835
  for (const task of input.parentSpec.tasks) {
815
836
  if (materializedDynamicChildIds.has(task.id))
816
837
  continue;
@@ -867,6 +888,21 @@ async function stageContinuationRun(input) {
867
888
  ranks,
868
889
  nodes,
869
890
  continuation,
891
+ ...(isCanonicalFrontendShapeDag(tasksById)
892
+ ? {
893
+ frontendShapeState: {
894
+ frozenTopology: buildFrontendTopologyBinding(specForRun.tasks.map((task) => task.id)),
895
+ revision: 0,
896
+ // Imported boundary sources will not run again. Preserve their
897
+ // committed evidence; reset sources must produce fresh facts.
898
+ committedFacts: Object.fromEntries(FRONTEND_SHAPE_BOUNDARIES.flatMap((entry) => {
899
+ const fact = input.parentState.frontendShapeState?.committedFacts[entry.boundary];
900
+ return importedSet.has(entry.sourceNodeId) && fact
901
+ ? [[entry.boundary, structuredClone(fact)]] : [];
902
+ })),
903
+ },
904
+ }
905
+ : {}),
870
906
  ...(input.parentState.convergence
871
907
  ? { convergence: structuredClone(input.parentState.convergence) }
872
908
  : {}),
@@ -997,6 +1033,9 @@ export async function executeDagRerun(input) {
997
1033
  }
998
1034
  const parentSpec = await readDagRunSpec(located.runDir);
999
1035
  const parentState = await readDagRunState(located.runDir);
1036
+ const preparedFrontendArtifacts = await prepareFrontendRunArtifacts({
1037
+ parentRunDir: located.runDir, spec: parentSpec, importedNodeIds: plan.importedNodeIds,
1038
+ });
1000
1039
  const recoveryLease = await acquireDagRecoveryLease({
1001
1040
  cwd: input.cwd,
1002
1041
  parentRunId: input.parentRunId,
@@ -1021,6 +1060,7 @@ export async function executeDagRerun(input) {
1021
1060
  reason: input.reason,
1022
1061
  requestId: input.requestId,
1023
1062
  promptOverrides: input.promptOverrides,
1063
+ preparedFrontendArtifacts,
1024
1064
  });
1025
1065
  // Stage is non-executing; bind the child identity immediately before handing
1026
1066
  // it to the runner so no recovery DAG can start without durable parent
@@ -366,6 +366,17 @@ export async function runDagContinuation(opts) {
366
366
  if (state.frontendShapeState?.terminalOutcome) {
367
367
  throw new Error(`dag run ${state.runId} is terminal due to frontend shape ${state.frontendShapeState.terminalOutcome}`);
368
368
  }
369
+ // A staged recovery child has not passed runDag's creation path. Capture
370
+ // the executing controller before starting it, so interrupt identity is
371
+ // complete and never borrowed from the parent controller.
372
+ const continuationIdentity = resolveRunningControllerIdentity();
373
+ if (!continuationIdentity) {
374
+ throw new Error("running controller identity could not be resolved; refuse to execute an unpinned DAG continuation");
375
+ }
376
+ state.controllerIdentityRef = await captureControllerIdentity({
377
+ runDir: opts.runDir,
378
+ identity: continuationIdentity,
379
+ });
369
380
  state.status = "running";
370
381
  const resumedAt = new Date().toISOString();
371
382
  state.runner = {
@@ -343,7 +343,8 @@ export async function finalizeTerminalRunStatus(state, taskCount, runDir, cwd, f
343
343
  // rejected the implementation; the run must never surface as finished
344
344
  // even though every node technically FINISHED.
345
345
  state.status =
346
- state.terminalReason === "review-request-changes"
346
+ state.terminalReason === "review-request-changes" ||
347
+ state.failureCategory === "controller-interrupted"
347
348
  ? "partial_failed"
348
349
  : "finished";
349
350
  }