@deksden-com/dd-flow-cli 0.9.0-beta.8 → 0.9.0-beta.80

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 (136) hide show
  1. package/CHANGELOG.md +396 -0
  2. package/README.md +65 -0
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/command-inputs.js +300 -0
  5. package/dist/cli/help.js +81 -9
  6. package/dist/cli/hook-ingress.js +82 -0
  7. package/dist/cli/input-preparation.js +115 -0
  8. package/dist/cli/run-cli.js +1342 -375
  9. package/dist/cli.js +6 -2
  10. package/dist/harness-runtime/bin/dd-agy.mjs +37 -0
  11. package/dist/harness-runtime/bin/dd-codex.mjs +25 -0
  12. package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
  13. package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
  14. package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
  15. package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
  16. package/dist/harness-runtime/lib/daemon-operations.mjs +215 -0
  17. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +423 -0
  18. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  19. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  20. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +146 -0
  21. package/dist/harness-runtime/lib/dd-codex.mjs +562 -0
  22. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
  23. package/dist/harness-runtime/lib/dd-droid.mjs +471 -0
  24. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +274 -0
  25. package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
  26. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +198 -0
  27. package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
  28. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +644 -0
  29. package/dist/harness-runtime/lib/dd-zcode.mjs +910 -0
  30. package/dist/harness-runtime/lib/delegation-instructions.d.mts +10 -0
  31. package/dist/harness-runtime/lib/delegation-instructions.mjs +130 -0
  32. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  33. package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
  34. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  35. package/dist/harness-runtime/lib/managed-daemon.mjs +260 -0
  36. package/dist/harness-runtime/lib/model-observations.mjs +77 -0
  37. package/dist/harness-runtime/lib/native-hook-command.d.mts +1 -0
  38. package/dist/harness-runtime/lib/native-hook-command.mjs +34 -0
  39. package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
  40. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  41. package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
  42. package/dist/harness-runtime/lib/process-json.mjs +70 -0
  43. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  44. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  45. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  46. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  47. package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
  48. package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
  49. package/dist/schemas/agent-profile.schema.json +1 -1
  50. package/dist/schemas/code-review-result.schema.json +2 -2
  51. package/dist/schemas/code-work-batch.schema.json +4 -3
  52. package/dist/schemas/code-work-result.schema.json +4 -4
  53. package/dist/schemas/plan-review-result.schema.json +2 -2
  54. package/dist/schemas/run-control-receipt.schema.json +99 -0
  55. package/dist/schemas/run-control-request.schema.json +36 -0
  56. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  57. package/dist/services/canon.js +11 -8
  58. package/dist/services/cleanup.js +57 -13
  59. package/dist/services/cli-operation-classifier.js +22 -24
  60. package/dist/services/code-checks.js +543 -96
  61. package/dist/services/codex-hook-delivery.js +28 -0
  62. package/dist/services/config.js +11 -8
  63. package/dist/services/controller-fanout.js +116 -0
  64. package/dist/services/dashboard.js +103 -31
  65. package/dist/services/engines.js +121 -76
  66. package/dist/services/eval-snapshots.js +750 -73
  67. package/dist/services/execution-policy.js +170 -0
  68. package/dist/services/external-work-launch.js +110 -0
  69. package/dist/services/harness-adapter.js +147 -24
  70. package/dist/services/harness-config.js +2 -0
  71. package/dist/services/hooks.js +553 -285
  72. package/dist/services/lanes.js +61 -53
  73. package/dist/services/lifecycle-command.js +87 -7
  74. package/dist/services/lifecycle-invocations.js +828 -0
  75. package/dist/services/managed-daemon-binding.js +38 -0
  76. package/dist/services/managed-processes.js +283 -27
  77. package/dist/services/merge-queue.js +179 -104
  78. package/dist/services/merge-server.js +73 -28
  79. package/dist/services/migrations.js +14 -9
  80. package/dist/services/native-daemon-history.js +49 -0
  81. package/dist/services/native-session-control.js +39 -0
  82. package/dist/services/plan-runtime.js +19 -8
  83. package/dist/services/plans.js +28 -25
  84. package/dist/services/projects.js +18 -5
  85. package/dist/services/prompts.js +23 -16
  86. package/dist/services/protocols.js +64 -20
  87. package/dist/services/recovery-observation-budget.js +61 -0
  88. package/dist/services/recovery-snapshot-database.js +107 -0
  89. package/dist/services/run-control-receipt.js +56 -0
  90. package/dist/services/run-control-worker.js +363 -0
  91. package/dist/services/run-control.js +876 -0
  92. package/dist/services/run-controller-adapter.js +222 -0
  93. package/dist/services/run-controller-capture.js +134 -0
  94. package/dist/services/run-controller-process.js +189 -0
  95. package/dist/services/run-controller-recovery.js +222 -0
  96. package/dist/services/run-controller-state.js +36 -0
  97. package/dist/services/run-controller.js +779 -0
  98. package/dist/services/run-engine-bindings.js +1 -1
  99. package/dist/services/run-fork.js +138 -0
  100. package/dist/services/run-observations.js +112 -0
  101. package/dist/services/run-recovery-runtime.js +69 -0
  102. package/dist/services/run-recovery.js +342 -0
  103. package/dist/services/runs.js +368 -74
  104. package/dist/services/runtime-budget.js +434 -0
  105. package/dist/services/runtime-scope-capture.js +50 -0
  106. package/dist/services/runtime-scope-control.js +450 -0
  107. package/dist/services/runtime-scope-resume.js +565 -0
  108. package/dist/services/runtime-scope-stop.js +99 -0
  109. package/dist/services/runtime-scope-worker.js +243 -0
  110. package/dist/services/runtime-service.js +97 -0
  111. package/dist/services/schema-validation.js +10 -8
  112. package/dist/services/sessions.js +35 -69
  113. package/dist/services/stage-blocker.js +17 -7
  114. package/dist/services/stage-context.js +44 -18
  115. package/dist/services/stage-lifecycle.js +99 -102
  116. package/dist/services/stage-pause.js +65 -23
  117. package/dist/services/usage.js +37 -93
  118. package/dist/services/vnext-code-review.js +189 -85
  119. package/dist/services/vnext-code.js +257 -243
  120. package/dist/services/vnext-execution-profile.js +5 -3
  121. package/dist/services/vnext-fanout.js +134 -19
  122. package/dist/services/vnext-merge.js +285 -102
  123. package/dist/services/vnext-plan-review.js +148 -94
  124. package/dist/services/vnext-plan.js +141 -72
  125. package/dist/services/vnext-protocolize.js +129 -56
  126. package/dist/services/vnext-specify.js +87 -64
  127. package/dist/services/work-registry.js +707 -156
  128. package/dist/services/workspace-bootstrap.js +76 -0
  129. package/dist/services/worktrees.js +85 -35
  130. package/dist/shared/errors.js +12 -0
  131. package/dist/storage/database.js +444 -32
  132. package/dist/storage/paths.js +17 -4
  133. package/dist/storage/writer-contract.js +77 -0
  134. package/dist/storage/writer-migration.js +102 -0
  135. package/package.json +11 -4
  136. package/tools/repair-paused-run-status.mjs +59 -0
@@ -1,33 +1,117 @@
1
+ import { managedLifecycleCommand } from "./lifecycle-invocations.js";
1
2
  import crypto from "node:crypto";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
5
  import { AppError } from "../shared/errors.js";
5
- import { findRecentMatchingHookEvent, claimStageStartHookEvent, claimWorkStartHookEvent, hookSessionIdentity, workStartMatchKey } from "./hooks.js";
6
+ import { findRecentMatchingHookEvent, claimStageLifecycleHookEvent, claimStageStartHookEvent, claimWorkLifecycleHookEvent, claimWorkStartHookEvent, hookSessionIdentity, workStartMatchKey } from "./hooks.js";
6
7
  import { validateSchema } from "./schema-validation.js";
7
8
  import { resolveProjectRoot, resolveRunReferences } from "../storage/paths.js";
8
9
  import { refreshRunSessionProjection } from "./run-projection.js";
9
- import { readCodeCheckProfile, runCodeChecks, workspaceFingerprint } from "./code-checks.js";
10
+ import { ignoredWorkspacePaths, normalizeWorkspacePath, readCodeCheckProfile, runCodeChecks, validateFailedCheckRetry, workspaceFingerprint } from "./code-checks.js";
10
11
  import { nextWorkId, nextWorkIds } from "./ids.js";
11
12
  import { appendFlowRunTimelineEvent } from "./runs.js";
13
+ import { resolveStageTransition } from "./execution-policy.js";
14
+ import { appendAudit } from "./audit.js";
12
15
  import { flowCommand } from "./stage-pause.js";
13
16
  import { assertPortableArtifactRef } from "./portable-refs.js";
14
17
  import { publicSessionIdentity } from "./session-identity.js";
18
+ import { activateRecoveryWork, assertRecoveryHookCurrent, assertRunMutationAllowed, assertWorkSettlementAllowed, recoveryGuard, recoveryPromptForWork, settleRecoveryWork } from "./run-recovery.js";
19
+ import { runControlDirective } from "./run-control.js";
20
+ import { prepareError, prepareJsonFile } from "../cli/input-preparation.js";
15
21
  const workColumns = "work_id, project_id, run_id, parent_work_id, task, launch_policy, result_schema, payload_json, depends_on_json, status, result, created_at, started_at, updated_at, completed_at";
16
22
  export function ensureWorkRegistry(context) { context.db.exec("SELECT 1 FROM works LIMIT 1"); context.db.exec("SELECT 1 FROM work_sessions LIMIT 1"); }
23
+ function ownsPhysicalWorkSession(context, projectId, owner, identity) {
24
+ if (identity.sessionId !== owner.session_id)
25
+ return false;
26
+ const binding = owner.hook_event_id ? context.db.get("SELECT daemon_id FROM hook_events WHERE project_id = ? AND event_key = ?", [projectId, owner.hook_event_id]) : undefined;
27
+ // Legacy non-daemon sessions remain usable. Once a physical daemon was
28
+ // captured, another process cannot inherit authority merely by resuming
29
+ // the same provider Session ID.
30
+ return !binding?.daemon_id || binding.daemon_id === identity.daemonId;
31
+ }
32
+ /**
33
+ * A Stage terminal command is allowed only from the Session that owns its
34
+ * running coordinator Work. A hook receipt proves the caller; a WorkSession
35
+ * proves the owner. Either fact alone is insufficient.
36
+ */
37
+ export function assertStageLifecycleOwner(context, input) {
38
+ ensureWorkRegistry(context);
39
+ const projectRoot = resolveProjectRoot(input.projectRoot);
40
+ const project = context.db.get("SELECT id FROM projects WHERE root = ?", [projectRoot]);
41
+ if (!project)
42
+ throw new AppError("not_found", "Project is not registered", 1, { project_root: projectRoot });
43
+ requireRun(context, project.id, input.runId);
44
+ let owner = context.db.get(`SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id
45
+ FROM work_sessions ws
46
+ JOIN works w ON w.work_id = ws.work_id
47
+ JOIN sessions s ON s.project_id = w.project_id AND s.session_id = ws.session_id
48
+ WHERE w.project_id = ? AND w.run_id = ? AND ws.status = 'running'
49
+ AND w.status IN ('running', 'paused') AND (w.parent_work_id IS NULL OR s.current_stage = ?)
50
+ ${input.workId ? "AND w.work_id = ?" : ""}
51
+ ORDER BY ws.created_at DESC LIMIT 1`, input.workId ? [project.id, input.runId, input.stage, input.workId] : [project.id, input.runId, input.stage]);
52
+ if (!owner && input.operation === "stage_finish" && ["code", "code-review"].includes(input.stage)) {
53
+ const row = context.db.get("SELECT run_root, index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
54
+ const index = row ? JSON.parse(row.index_json) : null;
55
+ const completed = index?.stage_runs.find(entry => entry.stage === input.stage && entry.status === "done");
56
+ if (row && completed && (index?.current_stage ?? index?.stage_runs.at(-1)?.stage) === input.stage)
57
+ owner = context.db.get("SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE w.project_id = ? AND w.run_id = ? AND w.parent_work_id IS NULL AND w.status = 'completed' AND ws.status = 'completed' AND ws.result_path = ? ORDER BY ws.created_at DESC LIMIT 1", [project.id, input.runId, path.join(row.run_root, completed.dir, "stage-report.json")]);
58
+ }
59
+ if (!owner)
60
+ throw new AppError("trusted_session_binding_required", "Stage lifecycle command has no running coordinator Work/Session binding", 1, { run_id: input.runId, stage: input.stage, ...(input.workId ? { work_id: input.workId } : {}) });
61
+ const identity = claimStageLifecycleHookEvent(context, {
62
+ projectId: project.id, ...(input.hookEventId ? { eventKey: input.hookEventId } : {}), operation: input.operation,
63
+ runId: input.runId, stage: input.stage, projectRoot, ...(input.operation === "stage_pause" ? { workId: owner.work_id } : {})
64
+ });
65
+ if (ownsPhysicalWorkSession(context, project.id, owner, identity))
66
+ return identity;
67
+ context.db.run("UPDATE hook_events SET status = 'rejected', claimed_at = ? WHERE id = ?", [context.now(), identity.hookEventId]);
68
+ const payload = { run_id: input.runId, stage: input.stage, work_id: owner.work_id, operation: input.operation, expected_session_id: owner.session_id, observed_session_id: identity.sessionId, hook_event_id: identity.hookEventId };
69
+ appendFlowRunTimelineEvent(context, project.id, input.runId, { type: "lifecycle_caller_mismatch", ...payload });
70
+ appendAudit(context, { projectId: project.id, eventType: "stage.lifecycle_caller_rejected", payload });
71
+ throw new AppError("lifecycle_caller_mismatch", "Stage lifecycle command was issued by a Session that does not own the running Work", 1, payload);
72
+ }
73
+ /** A Work terminal command belongs to the Session that started that Work.
74
+ * Controllers can still use their explicit non-agent operations; they cannot
75
+ * borrow a native worker's authority by naming its Work id. */
76
+ export function assertWorkLifecycleOwner(context, input) {
77
+ ensureWorkRegistry(context);
78
+ const work = requireWork(context, input.workId);
79
+ const run = requireRun(context, work.project_id, work.run_id);
80
+ if (resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
81
+ throw new AppError("project_mismatch", "Work lifecycle project root does not match its RUN", 1, { work_id: work.work_id });
82
+ const owner = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
83
+ if (!owner)
84
+ throw new AppError("trusted_session_binding_required", "Work lifecycle command has no running Work/Session binding", 1, { work_id: work.work_id });
85
+ const identity = claimWorkLifecycleHookEvent(context, { projectId: work.project_id, ...(input.hookEventId ? { eventKey: input.hookEventId } : {}), operation: input.operation, workId: work.work_id, projectRoot: run.project_root });
86
+ if (ownsPhysicalWorkSession(context, work.project_id, owner, identity))
87
+ return identity;
88
+ context.db.run("UPDATE hook_events SET status = 'rejected', claimed_at = ? WHERE id = ?", [context.now(), identity.hookEventId]);
89
+ const payload = { run_id: work.run_id, work_id: work.work_id, operation: input.operation, expected_session_id: owner.session_id, observed_session_id: identity.sessionId, hook_event_id: identity.hookEventId };
90
+ appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_lifecycle_caller_mismatch", ...payload });
91
+ appendAudit(context, { projectId: work.project_id, eventType: "work.lifecycle_caller_rejected", payload });
92
+ throw new AppError("lifecycle_caller_mismatch", "Work lifecycle command was issued by a Session that does not own the running Work", 1, payload);
93
+ }
17
94
  export function createChildWork(context, input) {
18
- const parent = requireWork(context, input.parentWorkId);
19
- if (parent.status !== "running")
20
- throw new AppError("invalid_work_state", "Child Work requires a running parent", 2, { parent_work_id: parent.work_id, status: parent.status });
21
- const id = nextWorkId(context, parent.project_id, input.slug);
22
- const now = context.now();
23
- context.db.run(`INSERT INTO works (${workColumns}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '[]', 'created', NULL, ?, NULL, ?, NULL)`, [id, parent.project_id, parent.run_id, parent.work_id, input.task, input.launchPolicy, input.resultSchema ?? null, input.payload ? JSON.stringify(input.payload) : null, now, now]);
24
- refreshRunWorkProjection(context, parent.project_id, parent.run_id);
25
- return requireWork(context, id);
95
+ return context.db.writeTransaction(() => {
96
+ const parent = requireWork(context, input.parentWorkId);
97
+ assertRunMutationAllowed(context, parent.project_id, parent.run_id);
98
+ if (parent.status !== "running")
99
+ throw new AppError("invalid_work_state", "Child Work requires a running parent", 2, { parent_work_id: parent.work_id, status: parent.status });
100
+ const id = nextWorkId(context, parent.project_id, input.slug);
101
+ const now = context.now();
102
+ context.db.run(`INSERT INTO works (${workColumns}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '[]', 'created', NULL, ?, NULL, ?, NULL)`, [id, parent.project_id, parent.run_id, parent.work_id, input.task, input.launchPolicy, input.resultSchema ?? null, input.payload ? JSON.stringify(input.payload) : null, now, now]);
103
+ refreshRunWorkProjection(context, parent.project_id, parent.run_id);
104
+ return requireWork(context, id);
105
+ });
26
106
  }
27
107
  /** Validate a proposed batch before PLAN accepts it, without registering Work. */
28
108
  export function validateWorkBatchFile(file) {
29
- const parsed = readJson(file);
30
- if (!Array.isArray(parsed.works) || parsed.works.length === 0)
109
+ validateWorkBatch(prepareJsonFile(file, "work batch").value);
110
+ }
111
+ /** Validate an already prepared batch without reopening its source file. */
112
+ export function validateWorkBatch(value) {
113
+ const parsed = value;
114
+ if (!parsed || !Array.isArray(parsed.works) || parsed.works.length === 0)
31
115
  throw new AppError("validation", "work batch requires non-empty works", 2);
32
116
  const items = parsed.works.map((item) => validateItem(item, true));
33
117
  const keys = new Set(items.map((item) => item.key));
@@ -43,18 +127,29 @@ export function validateWorkBatchFile(file) {
43
127
  assertNoCycles(items.map((item) => ({ id: item.key, dependencies: item.depends_on ?? [] })));
44
128
  assertNoParentCycles(items.filter((item) => Boolean(item.parent)).map((item) => ({ id: item.key, parent: item.parent })));
45
129
  }
46
- export function addWorkBatch(context, input) {
47
- ensureWorkRegistry(context);
48
- const parent = requireWork(context, input.parentWorkId);
49
- if (parent.status !== "running")
50
- throw new AppError("invalid_work_state", "Batch parent must be running", 2, { work_id: parent.work_id, status: parent.status });
51
- const parsed = readJson(input.file);
52
- if (!Array.isArray(parsed.works) || parsed.works.length === 0)
130
+ export function prepareWorkBatch(context, input) {
131
+ if (input.file !== undefined && input.value !== undefined)
132
+ throw new AppError("usage", "Work batch accepts either file or value, not both", 2);
133
+ if (input.file === undefined && input.value === undefined)
134
+ throw new AppError("usage", "Work batch input is required", 2);
135
+ const parsed = (input.file !== undefined ? prepareJsonFile(input.file, "work batch").value : input.value);
136
+ if (!parsed || !Array.isArray(parsed.works) || parsed.works.length === 0)
53
137
  throw new AppError("validation", "work batch requires non-empty works", 2);
54
138
  const items = parsed.works.map((item) => validateItem(item));
55
139
  const keys = new Set(items.map((item) => item.key));
56
140
  if (keys.size !== items.length)
57
141
  throw new AppError("validation", "work batch keys must be unique", 2);
142
+ assertNoCycles(items.map(item => ({ id: item.key, dependencies: item.depends_on ?? [] })));
143
+ assertNoParentCycles(items.filter((item) => Boolean(item.parent)).map(item => ({ id: item.key, parent: item.parent })));
144
+ prepareBatchParent(context, input.parentWorkId, items);
145
+ return items;
146
+ }
147
+ function prepareBatchParent(context, parentWorkId, items) {
148
+ const keys = new Set(items.map(item => item.key));
149
+ const parent = requireWork(context, parentWorkId);
150
+ assertRunMutationAllowed(context, parent.project_id, parent.run_id);
151
+ if (parent.status !== "running")
152
+ throw new AppError("invalid_work_state", "Batch parent must be running", 2, { work_id: parent.work_id, status: parent.status });
58
153
  const existing = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ?`, [parent.project_id, parent.run_id]);
59
154
  const existingIds = new Set(existing.map((row) => row.work_id));
60
155
  for (const item of items)
@@ -64,9 +159,15 @@ export function addWorkBatch(context, input) {
64
159
  for (const item of items)
65
160
  if (item.parent && !keys.has(item.parent) && !existingIds.has(item.parent))
66
161
  throw new AppError("validation", "work parent is unknown", 2, { key: item.key, parent: item.parent });
67
- const now = context.now();
68
- context.db.exec("BEGIN IMMEDIATE");
69
- try {
162
+ return parent;
163
+ }
164
+ export function addWorkBatch(context, input) {
165
+ const items = input.prepared ?? prepareWorkBatch(context, input);
166
+ return context.db.writeTransaction(() => {
167
+ // Only mutable authority/references are rechecked under the write lock.
168
+ // Caller bytes were read once, before admission, and are never reopened.
169
+ const parent = prepareBatchParent(context, input.parentWorkId, items);
170
+ const now = context.now();
70
171
  const allocated = nextWorkIds(context, parent.project_id, items.map((item) => item.key));
71
172
  const ids = new Map(items.map((item, index) => [item.key, allocated[index]]));
72
173
  const resolve = (value) => ids.get(value) ?? value;
@@ -76,16 +177,11 @@ export function addWorkBatch(context, input) {
76
177
  for (const item of proposed)
77
178
  context.db.run(`INSERT INTO works (work_id, project_id, run_id, parent_work_id, task, launch_policy, result_schema, payload_json, depends_on_json, status, result, started_at, created_at, updated_at, completed_at)
78
179
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'created', NULL, NULL, ?, ?, NULL)`, [item.id, parent.project_id, parent.run_id, item.parentId, item.task, item.launch_policy ?? "reuse_allowed", item.result_schema ?? null, item.payload ? JSON.stringify(item.payload) : null, JSON.stringify(item.dependencies), now, now]);
79
- context.db.exec("COMMIT");
80
180
  for (const item of proposed)
81
181
  appendFlowRunTimelineEvent(context, parent.project_id, parent.run_id, { type: "work_materialized", work_id: item.id, parent_work_id: item.parentId, depends_on: item.dependencies, launch_policy: item.launch_policy ?? "reuse_allowed" });
82
182
  refreshRunWorkProjection(context, parent.project_id, parent.run_id);
83
183
  return { ok: true, work_ids: Object.fromEntries(ids) };
84
- }
85
- catch (error) {
86
- context.db.exec("ROLLBACK");
87
- throw error;
88
- }
184
+ });
89
185
  }
90
186
  export function listWorks(context, input) {
91
187
  ensureWorkRegistry(context);
@@ -114,10 +210,137 @@ export function listWorks(context, input) {
114
210
  }) };
115
211
  }
116
212
  export function showWork(context, id) { const work = requireWork(context, id); const sessions = context.db.all("SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id, ws.status, ws.prompt_path, ws.result_path, ws.created_at, ws.completed_at, s.harness AS harness_id, COALESCE(s.provider_session_id, s.session_id) AS native_session_id FROM work_sessions ws LEFT JOIN sessions s ON s.project_id = ? AND s.session_id = ws.session_id WHERE ws.work_id = ? ORDER BY ws.created_at", [work.project_id, work.work_id]); return { work: { ...work, short_id: shortWorkId(work.work_id), payload: parsePayload(work), payload_json: undefined, depends_on: parseDependencies(work), sessions: sessions.map(({ session_id, harness_id, native_session_id, ...session }) => ({ ...session, ...(harness_id && native_session_id ? { session: publicSessionIdentity({ harness: harness_id, provider_session_id: native_session_id, session_id }) } : {}) })) } }; }
213
+ function receiptIntentPath(resultPath, sessionId) {
214
+ return `${resultPath}.pending-${crypto.createHash("sha256").update(sessionId).digest("hex")}`;
215
+ }
216
+ function receiptFileHash(file) {
217
+ return fs.existsSync(file) ? crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex") : null;
218
+ }
219
+ function sha256(contents) { return crypto.createHash("sha256").update(contents).digest("hex"); }
220
+ function publishReceiptFile(file, contents) {
221
+ const temporary = `${file}.tmp-${crypto.randomUUID()}`;
222
+ try {
223
+ fs.writeFileSync(temporary, contents);
224
+ const descriptor = fs.openSync(temporary, "r");
225
+ try {
226
+ fs.fsyncSync(descriptor);
227
+ }
228
+ finally {
229
+ fs.closeSync(descriptor);
230
+ }
231
+ fs.renameSync(temporary, file);
232
+ const directory = fs.openSync(path.dirname(file), "r");
233
+ try {
234
+ fs.fsyncSync(directory);
235
+ }
236
+ finally {
237
+ fs.closeSync(directory);
238
+ }
239
+ }
240
+ finally {
241
+ fs.rmSync(temporary, { force: true });
242
+ }
243
+ }
244
+ /** Rebuild prompt/context projections from a committed Work-start receipt. */
245
+ export function materializePendingWorkStarts(context, projectId, runId) {
246
+ const runHome = requireRunHome(requireRun(context, projectId, runId));
247
+ context.db.writeTransaction(() => {
248
+ const rows = context.db.all("SELECT ws.id, ws.work_id, ws.prompt_path, ws.start_receipt_json FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE w.project_id = ? AND w.run_id = ? AND ws.status = 'running' AND ws.start_receipt_json IS NOT NULL", [projectId, runId]);
249
+ for (const row of rows) {
250
+ // The same coordinator Session can move on to a different stage packet.
251
+ // A start receipt is not authority to overwrite that later packet.
252
+ let receipt;
253
+ try {
254
+ receipt = JSON.parse(row.start_receipt_json);
255
+ }
256
+ catch {
257
+ throw new AppError("work_start_receipt_invalid", "Committed Work start receipt is not valid JSON", 1, { work_id: row.work_id });
258
+ }
259
+ const originalPromptPath = path.join(runHome, "works", row.work_id, ...(receipt.generation && receipt.generation > 0 ? ["starts", row.id] : []), "prompt.md");
260
+ if (path.resolve(row.prompt_path) !== path.resolve(originalPromptPath))
261
+ continue;
262
+ if (receipt.version !== 1 || typeof receipt.prompt !== "string" || typeof receipt.context !== "string" || receipt.prompt_sha256 !== sha256(receipt.prompt) || receipt.context_sha256 !== sha256(receipt.context))
263
+ throw new AppError("work_start_receipt_invalid", "Committed Work start receipt does not match its retained bytes", 1, { work_id: row.work_id });
264
+ publishStartReceiptFile(row.prompt_path, receipt.prompt, String(receipt.prompt_sha256));
265
+ publishStartReceiptFile(path.join(path.dirname(row.prompt_path), "context.json"), receipt.context, String(receipt.context_sha256));
266
+ }
267
+ });
268
+ }
269
+ function publishStartReceiptFile(file, contents, expectedHash) {
270
+ const actual = receiptFileHash(file);
271
+ if (actual === expectedHash)
272
+ return;
273
+ if (actual !== null) {
274
+ throw new AppError("work_start_projection_conflict", "Work start packet differs from its committed receipt; preserve it for recovery", 1, { path: file, expected_sha256: expectedHash, actual_sha256: actual });
275
+ }
276
+ fs.mkdirSync(path.dirname(file), { recursive: true });
277
+ publishReceiptFile(file, contents);
278
+ }
279
+ /** Replay only a prepared publication whose exact receipt was committed in SQLite. */
280
+ export function materializePendingWorkResults(context, projectId, runId) {
281
+ context.db.beginWriteTransaction();
282
+ try {
283
+ const rows = context.db.all(`SELECT w.work_id, w.result, w.status, ws.id, ws.result_path FROM works w JOIN work_sessions ws ON ws.work_id = w.work_id AND ws.status = w.status WHERE w.project_id = ? AND w.run_id = ? AND w.parent_work_id IS NOT NULL AND w.result IS NOT NULL AND w.status IN ('completed', 'failed', 'cancelled') AND ws.result_path IS NOT NULL`, [projectId, runId]);
284
+ for (const row of rows) {
285
+ const intentPath = receiptIntentPath(row.result_path, row.id);
286
+ if (!fs.existsSync(intentPath))
287
+ continue;
288
+ const intent = JSON.parse(fs.readFileSync(intentPath, "utf8"));
289
+ const digest = crypto.createHash("sha256").update(row.result).digest("hex");
290
+ if (intent.work_id !== row.work_id || intent.work_session_id !== row.id || intent.status !== row.status || intent.result_sha256 !== digest)
291
+ throw new AppError("work_result_publication_conflict", "Pending result publication does not identify the committed receipt", 1, { work_id: row.work_id, intent_path: intentPath });
292
+ const actual = receiptFileHash(row.result_path);
293
+ if (actual !== digest && actual !== intent.previous_sha256)
294
+ throw new AppError("work_result_artifact_drift", "Result changed after its publication was prepared; preserve it for diagnosis", 1, { work_id: row.work_id, actual_sha256: actual, expected_sha256: digest });
295
+ if (fs.existsSync(row.result_path)) {
296
+ const previous = fs.readFileSync(row.result_path);
297
+ if (!previous.equals(Buffer.from(row.result))) {
298
+ const retained = `${row.result_path}.conflict-${crypto.createHash("sha256").update(previous).digest("hex")}`;
299
+ try {
300
+ fs.writeFileSync(retained, previous, { flag: "wx", flush: true });
301
+ }
302
+ catch (error) {
303
+ if (error.code !== "EEXIST" || !fs.readFileSync(retained).equals(previous))
304
+ throw error;
305
+ }
306
+ }
307
+ }
308
+ publishReceiptFile(row.result_path, row.result);
309
+ fs.unlinkSync(intentPath);
310
+ }
311
+ context.db.exec("COMMIT");
312
+ }
313
+ catch (error) {
314
+ context.db.exec("ROLLBACK");
315
+ throw error;
316
+ }
317
+ }
117
318
  export function mutateWorkDeps(context, input) {
319
+ if (input.action === "list") {
320
+ const { work, dependencies } = prepareWorkDeps(context, input);
321
+ return { work_id: work.work_id, depends_on: dependencies };
322
+ }
323
+ prepareWorkDeps(context, input);
324
+ return context.db.writeTransaction(() => {
325
+ const { work, dependencies } = prepareWorkDeps(context, input);
326
+ context.db.run("UPDATE works SET depends_on_json = ?, updated_at = ? WHERE work_id = ?", [JSON.stringify(dependencies), context.now(), work.work_id]);
327
+ refreshRunWorkProjection(context, work.project_id, work.run_id);
328
+ return { work_id: work.work_id, depends_on: dependencies };
329
+ });
330
+ }
331
+ export function prepareWorkDeps(context, input) {
332
+ if (!["list", "add", "remove", "clear"].includes(input.action) || (input.on !== undefined && (!Array.isArray(input.on) || input.on.some(id => typeof id !== "string" || !id.trim()))))
333
+ throw new AppError("usage", "Invalid Work dependency action or --on target", 2);
334
+ if (["add", "remove"].includes(input.action) && !input.on?.length)
335
+ throw new AppError("usage", "Dependency add/remove requires at least one --on target", 2);
336
+ if (["list", "clear"].includes(input.action) && input.on?.length)
337
+ throw new AppError("usage", "Dependency list/clear does not accept --on targets", 2);
338
+ if (input.action === "list") {
339
+ const work = requireWork(context, input.workId);
340
+ return { work, dependencies: parseDependencies(work) };
341
+ }
118
342
  const work = requireWork(context, input.workId);
119
- if (input.action === "list")
120
- return { work_id: work.work_id, depends_on: parseDependencies(work) };
343
+ assertRunMutationAllowed(context, work.project_id, work.run_id);
121
344
  if (work.status !== "created")
122
345
  throw new AppError("invalid_work_state", "Dependencies change only while Work is created", 2);
123
346
  const dependencies = new Set(parseDependencies(work));
@@ -125,8 +348,8 @@ export function mutateWorkDeps(context, input) {
125
348
  dependencies.clear();
126
349
  for (const id of input.on ?? []) {
127
350
  const dependency = requireWork(context, id);
128
- if (dependency.run_id !== work.run_id)
129
- throw new AppError("validation", "Dependencies must stay in one RUN", 2);
351
+ if (dependency.project_id !== work.project_id || dependency.run_id !== work.run_id)
352
+ throw new AppError("validation", "Dependencies must stay in one project and RUN", 2);
130
353
  if (input.action === "add")
131
354
  dependencies.add(dependency.work_id);
132
355
  else
@@ -135,12 +358,19 @@ export function mutateWorkDeps(context, input) {
135
358
  if (dependencies.has(work.work_id))
136
359
  throw new AppError("validation", "Work cannot depend on itself", 2);
137
360
  assertNoCycles(context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ?`, [work.project_id, work.run_id]).map((row) => ({ id: row.work_id, dependencies: row.work_id === work.work_id ? [...dependencies] : parseDependencies(row) })));
138
- context.db.run("UPDATE works SET depends_on_json = ?, updated_at = ? WHERE work_id = ?", [JSON.stringify([...dependencies]), context.now(), work.work_id]);
139
- refreshRunWorkProjection(context, work.project_id, work.run_id);
140
- return { work_id: work.work_id, depends_on: [...dependencies] };
361
+ return { work, dependencies: [...dependencies] };
362
+ }
363
+ export function prepareWorkDelete(context, id) {
364
+ const work = requireWork(context, id);
365
+ assertRunMutationAllowed(context, work.project_id, work.run_id);
366
+ if (work.status !== "created" || work.started_at || context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? LIMIT 1", [work.work_id]) || context.db.get("SELECT 1 FROM works WHERE depends_on_json LIKE ? LIMIT 1", [`%${work.work_id}%`]))
367
+ throw new AppError("invalid_work_state", "Only an unstarted unreferenced Work may be deleted", 2);
368
+ return work;
369
+ }
370
+ export function deleteWork(context, id) {
371
+ prepareWorkDelete(context, id);
372
+ return context.db.writeTransaction(() => { const work = prepareWorkDelete(context, id); context.db.run("DELETE FROM works WHERE work_id = ?", [work.work_id]); refreshRunWorkProjection(context, work.project_id, work.run_id); return { ok: true, deleted: work.work_id }; });
141
373
  }
142
- export function deleteWork(context, id) { const work = requireWork(context, id); const canonical = work.work_id; if (work.status !== "created" || work.started_at || context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? LIMIT 1", [canonical]) || context.db.get("SELECT 1 FROM works WHERE depends_on_json LIKE ? LIMIT 1", [`%${canonical}%`]))
143
- throw new AppError("invalid_work_state", "Only an unstarted unreferenced Work may be deleted", 2); context.db.run("DELETE FROM works WHERE work_id = ?", [canonical]); refreshRunWorkProjection(context, work.project_id, work.run_id); return { ok: true, deleted: canonical }; }
144
374
  export function shortWorkId(id) { return /^WRK-\d{3,}(?:-|$)/.exec(id)?.[0]?.replace(/-$/, "") ?? id; }
145
375
  /**
146
376
  * Return the engine-bound command, never a PATH-dependent `dd-flow` token.
@@ -148,10 +378,11 @@ export function shortWorkId(id) { return /^WRK-\d{3,}(?:-|$)/.exec(id)?.[0]?.rep
148
378
  * PATH is not inherited; using the shared lifecycle command keeps them on the
149
379
  * same captured runtime as their parent stage.
150
380
  */
151
- export function workStartCommand(context, work) { const run = requireRun(context, work.project_id, work.run_id); return `${flowCommand(context)} work start ${work.work_id} --project-root ${JSON.stringify(run.project_root)} --json`; }
152
- export function startWork(context, id, input) {
381
+ export function workStartCommand(context, work) { const run = requireRun(context, work.project_id, work.run_id); const recovery = recoveryGuard(context, work.project_id, work.run_id); return managedLifecycleCommand(context, `${flowCommand(context)} work start ${work.work_id} --project-root ${JSON.stringify(run.project_root)}${recovery ? ` --recovery-id ${JSON.stringify(recovery.recovery_id)}` : ""} --json`); }
382
+ export function assertWorkLaunchReady(context, id) {
153
383
  ensureWorkRegistry(context);
154
384
  const work = requireWork(context, id);
385
+ assertRunMutationAllowed(context, work.project_id, work.run_id);
155
386
  if (work.status !== "created")
156
387
  throw new AppError("invalid_work_state", "Work is not created", 2, { work_id: id, status: work.status });
157
388
  if (!isReady(context, work)) {
@@ -159,32 +390,52 @@ export function startWork(context, id, input) {
159
390
  const ready = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? AND status = 'created' ORDER BY created_at, work_id`, [work.project_id, work.run_id]).filter((candidate) => isReady(context, candidate)).map((candidate) => ({ work_id: candidate.work_id, start_command: workStartCommand(context, candidate) }));
160
391
  throw new AppError("work_not_ready", "Work cannot start until dependencies complete and overlapping planned coordination areas are free", 2, { work_id: id, blockers, ready });
161
392
  }
393
+ return work;
394
+ }
395
+ export function startWork(context, id, input) {
396
+ if (input.hookEventId && !context.env.DD_FLOW_CURRENT_INVOCATION) {
397
+ const retainedWork = requireWork(context, id);
398
+ const retainedRun = requireRun(context, retainedWork.project_id, retainedWork.run_id);
399
+ if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(retainedRun.project_root))
400
+ throw new AppError("project_mismatch", "Work start belongs to another project", 1);
401
+ const reply = recoverCommittedWorkStart(context, null, input.hookEventId, recoveryGuard(context, retainedWork.project_id, retainedWork.run_id)?.generation ?? 0, retainedWork.work_id);
402
+ if (reply)
403
+ return reply;
404
+ }
405
+ const work = assertWorkLaunchReady(context, id);
162
406
  const run = requireRun(context, work.project_id, work.run_id);
163
407
  if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
164
408
  throw new AppError("project_mismatch", "work start project root does not match its RUN", 1, { work_id: id });
409
+ const recoveryId = recoveryGuard(context, work.project_id, work.run_id)?.recovery_id;
410
+ if (input.recoveryId !== recoveryId)
411
+ throw new AppError("run_recovery_generation_stale", "Work launch must use the exact current recovery packet", 1, { work_id: id, recovery_id: recoveryId ?? null });
165
412
  let hookEventId = input.hookEventId;
166
413
  if (!hookEventId) {
167
414
  try {
168
- hookEventId = findRecentMatchingHookEvent(context, { projectId: work.project_id, matchKey: workStartMatchKey(shortWorkId(work.work_id), run.project_root), errorCode: "trusted_session_binding_required", operation: "work start" }).eventKey;
415
+ hookEventId = findRecentMatchingHookEvent(context, { projectId: work.project_id, matchKey: workStartMatchKey(shortWorkId(work.work_id), run.project_root, recoveryId), errorCode: "trusted_session_binding_required", operation: "work start" }).eventKey;
169
416
  }
170
417
  catch {
171
- hookEventId = findRecentMatchingHookEvent(context, { projectId: work.project_id, matchKey: workStartMatchKey(work.work_id, run.project_root), errorCode: "trusted_session_binding_required", operation: "work start" }).eventKey;
418
+ hookEventId = findRecentMatchingHookEvent(context, { projectId: work.project_id, matchKey: workStartMatchKey(work.work_id, run.project_root, recoveryId), errorCode: "trusted_session_binding_required", operation: "work start" }).eventKey;
172
419
  }
173
420
  }
174
- const identity = claimWorkStartHookEvent(context, { projectId: work.project_id, eventKey: hookEventId, workId: work.work_id, projectRoot: run.project_root });
175
- const started = startBoundWork(context, work, run, identity, hookEventId);
176
- appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_started", work_id: work.work_id, session_id: identity.sessionId, agent_id: identity.agentId });
421
+ const eventKey = hookEventId;
422
+ const started = startBoundWork(context, work, run, () => claimWorkStartHookEvent(context, { projectId: work.project_id, eventKey, workId: work.work_id, projectRoot: run.project_root, ...(recoveryId ? { recoveryId } : {}) }), eventKey);
423
+ appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_started", work_id: work.work_id, work_session_id: started.work_session_id });
177
424
  return started;
178
425
  }
179
426
  /** Binds the already-running coordinator of a stage to its trusted hook Session. */
180
427
  export function bindRunningWorkSession(context, input) {
181
428
  const work = requireWork(context, input.workId);
429
+ assertRunMutationAllowed(context, work.project_id, work.run_id);
182
430
  if (work.status !== "running")
183
431
  throw new AppError("invalid_work_state", "Stage coordinator Work must be running", 1, { work_id: work.work_id, status: work.status });
184
432
  const run = requireRun(context, work.project_id, work.run_id);
185
433
  const identity = hookSessionIdentity(context, work.project_id, input.hookEventId);
434
+ assertRecoveryHookCurrent(context, work.project_id, work.run_id, identity);
186
435
  const active = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
187
436
  if (active) {
437
+ if (active.session_id === identity.sessionId && !ownsPhysicalWorkSession(context, work.project_id, active, identity))
438
+ throw new AppError("handoff_session_mismatch", "The active Work belongs to another physical daemon", 1, { work_id: work.work_id });
188
439
  if (active.session_id !== identity.sessionId) {
189
440
  // A frozen `new_session` policy may transfer the same coordinator Work
190
441
  // only to its next stage. Repeating the same stage from another Session
@@ -193,7 +444,7 @@ export function bindRunningWorkSession(context, input) {
193
444
  throw new AppError("handoff_session_mismatch", "The active Work is already bound to a different Session", 1, { work_id: work.work_id });
194
445
  const now = context.now();
195
446
  const id = `WS-${crypto.randomUUID()}`;
196
- context.db.exec("BEGIN IMMEDIATE");
447
+ context.db.beginWriteTransaction();
197
448
  try {
198
449
  context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = ?, updated_at = ? WHERE id = ?", [now, now, active.id]);
199
450
  const stillRunning = context.db.get("SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running' LIMIT 1", [active.session_id]);
@@ -215,7 +466,7 @@ export function bindRunningWorkSession(context, input) {
215
466
  }
216
467
  const now = context.now();
217
468
  const id = `WS-${crypto.randomUUID()}`;
218
- context.db.exec("BEGIN IMMEDIATE");
469
+ context.db.beginWriteTransaction();
219
470
  try {
220
471
  bindSession(context, work, run, identity, now);
221
472
  context.db.run("INSERT INTO work_sessions (id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, NULL)", [id, work.work_id, identity.sessionId, input.hookEventId, input.promptPath, input.resultPath ?? null, now, now]);
@@ -231,10 +482,22 @@ export function bindRunningWorkSession(context, input) {
231
482
  /** A stage coordinator is launched by `stage start`, not by an invented nested `work start`. */
232
483
  export function bindStageCoordinatorWork(context, input) {
233
484
  const work = requireWork(context, input.workId);
485
+ assertRunMutationAllowed(context, work.project_id, work.run_id);
234
486
  const run = requireRun(context, work.project_id, work.run_id);
235
- claimStageStartHookEvent(context, { projectId: work.project_id, eventKey: input.hookEventId, runId: work.run_id, stage: input.stage, projectRoot: run.project_root, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
236
487
  const snapshot = JSON.parse((context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id])?.index_json) ?? "{}");
237
- const binding = bindRunningWorkSession(context, { ...input, allowStageHandoff: snapshot.execution_profile?.settings?.stage_session_mode === "new_session" });
488
+ const profile = snapshot.execution_profile;
489
+ const previous = context.db.get("SELECT ws.session_id, s.current_stage FROM work_sessions ws JOIN sessions s ON s.project_id = ? AND s.session_id = ws.session_id WHERE ws.work_id = ? AND ws.status = 'running' ORDER BY ws.created_at DESC LIMIT 1", [work.project_id, work.work_id]);
490
+ let sessionMode = profile?.settings.stage_session_mode ?? "same_session";
491
+ if (profile?.settings.execution) {
492
+ if (!profile.agent_profiles)
493
+ throw new AppError("execution_profile_not_frozen", "Stage handoff requires frozen RUN profiles", 1);
494
+ sessionMode = resolveStageTransition({ ddFlowHome: context.ddFlowHome, policy: profile.settings.execution, profiles: profile.agent_profiles, ...(previous?.current_stage ? { fromStage: previous.current_stage } : {}), stage: input.stage, stageSessionMode: sessionMode, mergeMode: profile.settings.merge_mode }).session_mode;
495
+ }
496
+ const identity = hookSessionIdentity(context, work.project_id, input.hookEventId);
497
+ if (previous?.current_stage && previous.current_stage !== input.stage && sessionMode === "new_session" && previous.session_id === identity.sessionId)
498
+ throw new AppError("stage_handoff_required", "This stage requires a fresh coordinator Session under its frozen execution policy", 1, { from_stage: previous.current_stage, stage: input.stage });
499
+ claimStageStartHookEvent(context, { projectId: work.project_id, eventKey: input.hookEventId, runId: work.run_id, stage: input.stage, projectRoot: run.project_root, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
500
+ const binding = bindRunningWorkSession(context, { ...input, allowStageHandoff: sessionMode === "new_session" });
238
501
  context.db.run("UPDATE sessions SET current_stage = ?, updated_at = ? WHERE project_id = ? AND session_id = ?", [input.stage, context.now(), work.project_id, binding.session_id]);
239
502
  refreshRunSessionProjection(context, work.project_id, work.run_id);
240
503
  return binding;
@@ -242,95 +505,293 @@ export function bindStageCoordinatorWork(context, input) {
242
505
  /** Starts a created coordinator Work from its trusted `stage start` event. */
243
506
  export function startStageCoordinatorWork(context, input) {
244
507
  const work = requireWork(context, input.workId);
508
+ assertRunMutationAllowed(context, work.project_id, work.run_id);
245
509
  if (work.status !== "created")
246
510
  throw new AppError("invalid_work_state", "Stage coordinator Work is not created", 2, { work_id: work.work_id, status: work.status });
247
511
  const run = requireRun(context, work.project_id, work.run_id);
248
512
  if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
249
513
  throw new AppError("project_mismatch", "stage coordinator project root does not match its RUN", 1, { work_id: work.work_id });
250
- const identity = claimStageStartHookEvent(context, { projectId: work.project_id, eventKey: input.hookEventId, runId: work.run_id, stage: input.stage, projectRoot: run.project_root, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
251
- const binding = startBoundWork(context, work, run, identity, input.hookEventId);
252
- const sessionId = String(binding.session_binding.session_id ?? "");
253
- context.db.run("UPDATE sessions SET current_stage = ?, updated_at = ? WHERE project_id = ? AND session_id = ?", [input.stage, context.now(), work.project_id, sessionId]);
514
+ const binding = startBoundWork(context, work, run, () => claimStageStartHookEvent(context, { projectId: work.project_id, eventKey: input.hookEventId, runId: work.run_id, stage: input.stage, projectRoot: run.project_root, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) }), input.hookEventId, input.stage);
254
515
  refreshRunSessionProjection(context, work.project_id, work.run_id);
255
516
  return binding;
256
517
  }
257
- /** Stage entry points call this only after their own trusted hook claim. */
258
- export function startBoundWork(context, work, run, identity, hookEventId) {
259
- if (work.status !== "created")
260
- throw new AppError("invalid_work_state", "Work is not created", 2, { work_id: work.work_id, status: work.status });
261
- const now = context.now();
262
- const linkId = `WS-${crypto.randomUUID()}`;
518
+ /** Claim, command authority and binding commit together; only packet projection follows. */
519
+ export function startBoundWork(context, work, run, claimIdentity, hookEventId, stage) {
520
+ const generation = assertRunMutationAllowed(context, work.project_id, work.run_id);
263
521
  const directory = path.join(requireRunHome(run), "works", work.work_id);
264
- fs.mkdirSync(directory, { recursive: true });
265
- const promptPath = path.join(directory, "prompt.md");
266
- const resultPath = path.join(directory, "result.json");
267
- const contextPath = path.join(directory, "context.json");
268
- const dependencyResults = parseDependencies(work).map((dependency) => context.db.get("SELECT work_id, result FROM works WHERE work_id = ?", [dependency])).filter(Boolean);
269
- const prompt = renderWorkerPrompt(context, work, run, dependencyResults);
270
- const payload = parsePayload(work);
271
- const readOnly = payload?.read_only === true;
272
- const workContext = { schema_id: "dd-flow/work-context@1", run_id: work.run_id, work_id: work.work_id, parent_work_id: work.parent_work_id, project_root: run.project_root, workspace_root: run.workspace_root, run_root: requireRunHome(run), depends_on: parseDependencies(work), launch_policy: work.launch_policy, result_schema: work.result_schema, read_only: readOnly, ...(readOnly ? { workspace_fingerprint: workspaceFingerprint(run.workspace_root) } : {}) };
273
- const token = crypto.randomUUID();
274
- const promptCandidate = `${promptPath}.${token}.tmp`;
275
- const contextCandidate = `${contextPath}.${token}.tmp`;
276
- fs.writeFileSync(promptCandidate, prompt);
277
- fs.writeFileSync(contextCandidate, `${JSON.stringify(workContext, null, 2)}\n`);
278
- context.db.exec("BEGIN IMMEDIATE");
522
+ const linkId = `WS-${crypto.randomUUID()}`;
523
+ // Recovery can reopen the same Work without retiring its historical packet.
524
+ // Give each new-generation start its own immutable publication destination.
525
+ const packetDirectory = generation > 0 ? path.join(directory, "starts", linkId) : directory;
526
+ const promptPath = path.join(packetDirectory, "prompt.md"), resultPath = path.join(directory, "result.json");
527
+ // The first reviewer freezes shared inputs in the same transaction as its claim.
528
+ const readOnly = parsePayload(work)?.read_only === true;
529
+ let fingerprint;
530
+ let binding;
279
531
  try {
280
- bindSession(context, work, run, identity, now);
281
- if (work.parent_work_id && work.launch_policy === "reuse_allowed")
282
- context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = ?, updated_at = ? WHERE session_id = ? AND status = 'running' AND work_id <> ?", [now, now, identity.sessionId, work.work_id]);
283
- const claimed = context.db.run("UPDATE works SET status = 'running', started_at = ?, updated_at = ? WHERE work_id = ? AND status = 'created'", [now, now, work.work_id]);
284
- if (claimed.changes !== 1)
285
- throw new AppError("conflict", "Work was claimed concurrently", 1, { work_id: work.work_id });
286
- context.db.run(`INSERT INTO work_sessions (id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, NULL)`, [linkId, work.work_id, identity.sessionId, hookEventId, promptPath, resultPath, now, now]);
287
- fs.renameSync(promptCandidate, promptPath);
288
- fs.renameSync(contextCandidate, contextPath);
289
- context.db.exec("COMMIT");
532
+ binding = context.db.writeTransaction(() => {
533
+ const current = requireWork(context, work.work_id);
534
+ assertRunMutationAllowed(context, current.project_id, current.run_id, generation);
535
+ if (current.status !== "created")
536
+ throw new AppError("conflict", "Work was claimed concurrently", 1, { work_id: current.work_id, status: current.status });
537
+ if (Object.keys(current).some(key => current[key] !== work[key]))
538
+ throw new AppError("work_not_ready", "Work inputs changed while preparing its start packet", 2, { work_id: current.work_id });
539
+ if (!isReady(context, current))
540
+ throw new AppError("work_not_ready", "Work dependencies are not ready", 2, { work_id: current.work_id, blockers: readinessBlockers(context, current) });
541
+ if (fs.existsSync(path.join(directory, ".retry.json")))
542
+ throw new AppError("work_retry_incomplete", "Complete the interrupted Work retry before starting its next attempt", 1, { work_id: work.work_id });
543
+ const identity = claimIdentity();
544
+ assertRecoveryHookCurrent(context, current.project_id, current.run_id, identity);
545
+ const dependencyResults = parseDependencies(current).map(dependency => context.db.get("SELECT work_id, result FROM works WHERE work_id = ?", [dependency])).filter(Boolean);
546
+ const recovery = recoveryPromptForWork(context, current.work_id);
547
+ let prompt = renderWorkerPrompt(context, current, run, dependencyResults);
548
+ if (recovery)
549
+ prompt = `${recoveryPrompt(recovery)}\n\n${prompt}`;
550
+ if (readOnly)
551
+ fingerprint = sharedReviewInput(work, run, true) ?? workspaceFingerprint(run.workspace_root);
552
+ const workContext = { schema_id: "dd-flow/work-context@1", run_id: current.run_id, work_id: current.work_id, parent_work_id: current.parent_work_id, project_root: run.project_root, workspace_root: run.workspace_root, run_root: requireRunHome(run), depends_on: parseDependencies(current), launch_policy: current.launch_policy, result_schema: current.result_schema, read_only: readOnly, ...(recovery ? { recovery } : {}), ...(readOnly ? { workspace_fingerprint: fingerprint } : {}) };
553
+ const contextBytes = `${JSON.stringify(workContext, null, 2)}\n`;
554
+ const response = { ok: true, work_id: current.work_id, work_session_id: linkId, worker_prompt_markdown: prompt, prompt_path: promptPath, ...(recovery ? { recovery } : {}), session_binding: { source: "PreToolUse", session: { harness_id: identity.harness, session_id: identity.nativeSessionId } } };
555
+ const receipt = JSON.stringify({ version: 1, prompt, context: contextBytes, prompt_sha256: sha256(prompt), context_sha256: sha256(contextBytes), response, response_sha256: sha256(JSON.stringify(response)), generation, invocation_id: context.env.DD_FLOW_CURRENT_INVOCATION ?? null });
556
+ const now = context.now();
557
+ bindSession(context, current, run, identity, now);
558
+ if (current.parent_work_id && current.launch_policy === "reuse_allowed")
559
+ context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = ?, updated_at = ? WHERE session_id = ? AND status = 'running' AND work_id <> ?", [now, now, identity.sessionId, current.work_id]);
560
+ if (context.db.run("UPDATE works SET status = 'running', started_at = COALESCE(started_at, ?), updated_at = ? WHERE work_id = ? AND status = 'created'", [now, now, current.work_id]).changes !== 1)
561
+ throw new AppError("conflict", "Work was claimed concurrently", 1, { work_id: current.work_id });
562
+ context.db.run("INSERT INTO work_sessions (id, work_id, session_id, hook_event_id, status, prompt_path, result_path, start_receipt_json, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, ?, NULL)", [linkId, current.work_id, identity.sessionId, hookEventId, promptPath, resultPath, receipt, now, now]);
563
+ if (stage)
564
+ context.db.run("UPDATE sessions SET current_stage = ?, updated_at = ? WHERE project_id = ? AND session_id = ?", [stage, now, current.project_id, identity.sessionId]);
565
+ if (recovery)
566
+ activateRecoveryWork(context, current.work_id);
567
+ return response;
568
+ });
290
569
  }
291
570
  catch (error) {
292
- context.db.exec("ROLLBACK");
293
- fs.rmSync(promptCandidate, { force: true });
294
- fs.rmSync(contextCandidate, { force: true });
571
+ // This transaction publishes only SQL authority, never files or provider calls.
572
+ if (error instanceof AppError && error.code === "storage_write_failed" && error.details.transaction_rolled_back === true)
573
+ error.details.effect = "no_effect";
574
+ if (error instanceof AppError && error.details.effect === "no_effect" && !context.env.DD_FLOW_CURRENT_INVOCATION) {
575
+ let retry = false;
576
+ try {
577
+ retry = context.db.writeTransaction(() => {
578
+ if (context.db.get("SELECT 1 FROM hook_events WHERE project_id = ? AND json_extract(outcome_json, '$.work_id') = ? AND json_extract(outcome_json, '$.generation') = ? AND json_extract(outcome_json, '$.storage_retry') = 1", [work.project_id, work.work_id, generation]))
579
+ return false;
580
+ return context.db.run("UPDATE hook_events SET outcome_json = ? WHERE project_id = ? AND event_key = ? AND status = 'observed' AND outcome_json IS NULL", [JSON.stringify({ work_id: work.work_id, run_id: work.run_id, generation, effect: "no_effect", disposition: "retrying", storage_retry: 1, deadline: Date.now() + 60000 }), work.project_id, hookEventId]).changes === 1;
581
+ });
582
+ }
583
+ catch (persistence) {
584
+ error.details.retry_persistence_error = String(persistence);
585
+ }
586
+ if (retry)
587
+ return startBoundWork(context, work, run, claimIdentity, hookEventId, stage);
588
+ }
295
589
  throw error;
296
590
  }
297
- refreshRunWorkProjection(context, work.project_id, work.run_id);
298
- return { ok: true, work_id: work.work_id, work_session_id: linkId, worker_prompt_markdown: prompt, prompt_path: promptPath, session_binding: { source: "PreToolUse", session: { harness_id: identity.harness, session_id: identity.nativeSessionId } } };
591
+ try {
592
+ materializePendingWorkStarts(context, work.project_id, work.run_id);
593
+ refreshRunWorkProjection(context, work.project_id, work.run_id);
594
+ }
595
+ catch (error) {
596
+ if (error instanceof AppError) {
597
+ error.details.effect = "committed";
598
+ throw error;
599
+ }
600
+ throw new AppError("work_start_publication_failed", error instanceof Error ? error.message : String(error), 1, { effect: "committed", work_id: work.work_id, hook_event_id: hookEventId, cause: { code: error?.code ?? null } });
601
+ }
602
+ return binding;
299
603
  }
300
- export function finishWork(context, id, result, progress) { return settle(context, id, "completed", result, progress); }
604
+ /** Read the exact committed reply, never bind another Session or regenerate a packet. */
605
+ export function recoverCommittedWorkStart(context, invocationId, eventKey, generation, workId) {
606
+ const row = context.db.get("SELECT ws.start_receipt_json, w.project_id, w.run_id FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE ws.start_receipt_json IS NOT NULL AND ws.hook_event_id = ? AND json_extract(ws.start_receipt_json, '$.invocation_id') IS ? AND (? IS NULL OR w.work_id = ?)", [eventKey, invocationId, workId ?? null, workId ?? null]);
607
+ if (!row)
608
+ return undefined;
609
+ const receipt = JSON.parse(row.start_receipt_json);
610
+ if (receipt.generation !== generation || !receipt.response || receipt.response_sha256 !== sha256(JSON.stringify(receipt.response)))
611
+ throw new AppError("work_start_receipt_invalid", "Committed reply identity or checksum differs", 1, { invocation_id: invocationId });
612
+ assertRunMutationAllowed(context, row.project_id, row.run_id, generation);
613
+ materializePendingWorkStarts(context, row.project_id, row.run_id);
614
+ return receipt.response;
615
+ }
616
+ /** Root coordinators have no worker checks: settle them inside the stage transaction. */
617
+ export function finishStageCoordinatorWork(context, id, result) {
618
+ const work = requireWork(context, id);
619
+ if (work.parent_work_id !== null || codePacket(work) || parsePayload(work)?.read_only)
620
+ throw new AppError("invalid_work_state", "Stage settlement requires a root coordinator", 2);
621
+ const run = requireRun(context, work.project_id, work.run_id);
622
+ const link = context.db.get("SELECT * FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [id]);
623
+ if (!link)
624
+ throw new AppError("runtime_missing", "Coordinator has no open Work/Session link", 1);
625
+ validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link.result_path);
626
+ finishFanInWork(context, id, result);
627
+ context.db.run("UPDATE sessions SET status = 'idle', updated_at = ? WHERE project_id = ? AND session_id = ? AND NOT EXISTS (SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running')", [context.now(), work.project_id, link.session_id, link.session_id]);
628
+ settleRecoveryWork(context, id, "completed");
629
+ }
630
+ export function finishWork(context, id, result, progress, retry) { return settle(context, id, "completed", result, progress, retry); }
301
631
  /** Structured fan-in closes a parent after its Session was handed to a child. */
302
- export function finishFanInWork(context, id, result) { const work = requireWork(context, id); if (work.status !== "running")
632
+ export function finishFanInWork(context, id, result) { const work = requireWork(context, id); assertRunMutationAllowed(context, work.project_id, work.run_id); if (work.status !== "running")
303
633
  throw new AppError("invalid_work_state", "Fan-in Work is not running", 2, { work_id: work.work_id, status: work.status }); if (context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? AND status IN ('created','running','paused') LIMIT 1", [work.work_id]))
304
634
  throw new AppError("active_child_work", "Fan-in Work still has active children", 2, { work_id: work.work_id }); const now = context.now(); context.db.run("UPDATE works SET status = 'completed', result = ?, completed_at = ?, updated_at = ? WHERE work_id = ?", [result, now, now, work.work_id]); context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = COALESCE(completed_at, ?), updated_at = ? WHERE work_id = ? AND status = 'running'", [now, now, work.work_id]); refreshRunWorkProjection(context, work.project_id, work.run_id); appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_completed", work_id: work.work_id, fan_in: true }); return { ok: true, work_id: work.work_id, status: "completed", fan_in: true }; }
305
635
  export function failWork(context, id, reason) { return settle(context, id, "failed", reason); }
306
636
  export function cancelWork(context, id, reason) { return settle(context, id, "cancelled", reason); }
307
- export function retryWork(context, id, reason) { const work = requireWork(context, id); id = work.work_id; if (work.status !== "failed")
308
- throw new AppError("invalid_work_state", "Only failed Work may be retried", 2); const run = requireRun(context, work.project_id, work.run_id); const directory = path.join(requireRunHome(run), "works", id); const attempts = path.join(directory, "attempts"); const number = fs.existsSync(attempts) ? fs.readdirSync(attempts).filter((entry) => /^ATT-\d{3}$/.test(entry)).length + 1 : 1; const archive = path.join(attempts, `ATT-${String(number).padStart(3, "0")}`); fs.mkdirSync(archive, { recursive: true }); for (const file of ["prompt.md", "result.json", "context.json"]) {
309
- const source = path.join(directory, file);
310
- if (fs.existsSync(source))
311
- fs.renameSync(source, path.join(archive, file));
312
- } context.db.run("UPDATE works SET status = 'created', result = NULL, started_at = NULL, completed_at = NULL, updated_at = ? WHERE work_id = ?", [context.now(), id]); refreshRunWorkProjection(context, work.project_id, work.run_id); return { ok: true, work_id: id, archived_attempt: path.relative(requireRunHome(run), archive).split(path.sep).join("/"), reason }; }
313
- async function settle(context, id, status, result, progress) {
637
+ export function prepareWorkSettlement(context, id, status, result) {
638
+ if (status !== "completed" && (typeof result !== "string" || !result.trim()))
639
+ throw new AppError("usage", "Work settlement requires a nonempty --reason", 2);
314
640
  const work = requireWork(context, id);
315
- id = work.work_id;
641
+ assertWorkSettlementAllowed(context, work.project_id, work.run_id, work.work_id);
316
642
  if (work.status !== "running" && !(status === "cancelled" && work.status === "created"))
317
643
  throw new AppError("invalid_work_state", "Work is not running", 2, { status: work.status });
318
- if (status === "completed" && context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? AND status IN ('created', 'running', 'paused') LIMIT 1", [id]))
319
- throw new AppError("active_child_work", "Work cannot complete while a child Work is active", 2, { work_id: id });
644
+ if (status === "completed" && context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? AND status IN ('created', 'running', 'paused') LIMIT 1", [work.work_id]))
645
+ throw new AppError("active_child_work", "Work cannot complete while a child Work is active", 2, { work_id: work.work_id });
320
646
  const run = requireRun(context, work.project_id, work.run_id);
321
- const link = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [id]);
647
+ const link = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
322
648
  if (work.status === "running" && !link)
323
- throw new AppError("runtime_missing", "Running Work has no open Work/Session link", 1, { work_id: id });
649
+ throw new AppError("runtime_missing", "Running Work has no open Work/Session link", 1, { work_id: work.work_id });
650
+ return { work, run, link };
651
+ }
652
+ export function prepareWorkRetry(context, id, reason) {
653
+ if (typeof reason !== "string" || !reason.trim())
654
+ throw new AppError("usage", "Work retry requires a nonempty --reason", 2);
655
+ const work = requireWork(context, id);
656
+ assertRunMutationAllowed(context, work.project_id, work.run_id);
657
+ const run = requireRun(context, work.project_id, work.run_id);
658
+ const directory = path.join(requireRunHome(run), "works", work.work_id);
659
+ const journal = path.join(directory, ".retry.json");
660
+ let pending = null;
661
+ if (fs.existsSync(journal)) {
662
+ let value;
663
+ try {
664
+ value = JSON.parse(fs.readFileSync(journal, "utf8"));
665
+ }
666
+ catch (error) {
667
+ if (!(error instanceof SyntaxError))
668
+ throw error;
669
+ throw new AppError("work_retry_invalid", "Retry journal is not valid JSON", 1);
670
+ }
671
+ const item = value;
672
+ if (!item || typeof item !== "object" || item.work_id !== work.work_id || typeof item.archive !== "string" || !/^ATT-\d{3,}$/.test(item.archive) || !Array.isArray(item.entries) || item.entries.some(file => !["prompt.md", "result.json", "context.json"].includes(file)) || new Set(item.entries).size !== item.entries.length || !(item.result_sha256 === null || typeof item.result_sha256 === "string" && /^[a-f0-9]{64}$/.test(item.result_sha256)))
673
+ throw new AppError("work_retry_invalid", "Retry journal does not identify this Work", 1);
674
+ pending = item;
675
+ }
676
+ if (work.status !== "failed" && !(pending && work.status === "created"))
677
+ throw new AppError("invalid_work_state", "Only failed Work may be retried", 2);
678
+ const attempts = path.join(directory, "attempts");
679
+ let number = 1;
680
+ while (fs.existsSync(path.join(attempts, `ATT-${String(number).padStart(3, "0")}`)))
681
+ number += 1;
682
+ const prepared = pending ?? { work_id: work.work_id, archive: `ATT-${String(number).padStart(3, "0")}`, entries: ["prompt.md", "result.json", "context.json"].filter(file => fs.existsSync(path.join(directory, file))), result_sha256: work.result === null ? null : crypto.createHash("sha256").update(work.result).digest("hex") };
683
+ const archive = path.join(attempts, prepared.archive);
684
+ if (work.status === "failed") {
685
+ if (prepared.result_sha256 !== (work.result === null ? null : crypto.createHash("sha256").update(work.result).digest("hex")))
686
+ throw new AppError("work_retry_conflict", "Failed Work receipt changed during retry", 1);
687
+ const receipt = path.join(archive, "accepted-receipt.json");
688
+ if (fs.existsSync(receipt) && fs.readFileSync(receipt, "utf8") !== JSON.stringify({ work_id: work.work_id, status: work.status, result: work.result, result_sha256: prepared.result_sha256 }))
689
+ throw new AppError("work_retry_conflict", "Archived receipt differs from failed Work", 1);
690
+ for (const file of prepared.entries) {
691
+ const source = path.join(directory, file), target = path.join(archive, file);
692
+ if (fs.existsSync(source) && fs.existsSync(target))
693
+ throw new AppError("archive_conflict", "Both live and archived Work artifact exist; preserve both", 1, { source, target });
694
+ if (!fs.existsSync(source) && !fs.existsSync(target))
695
+ throw new AppError("archive_artifact_missing", "Work artifact is absent from both retry locations", 1, { source, target });
696
+ }
697
+ }
698
+ return { work, run, directory, journal, pending, prepared, archive };
699
+ }
700
+ export function retryWork(context, id, reason) {
701
+ const { work, run, directory, journal } = prepareWorkRetry(context, id, reason);
702
+ let archive = "";
703
+ context.db.beginWriteTransaction();
704
+ try {
705
+ const { work: current, pending, prepared, archive: targetArchive } = prepareWorkRetry(context, work.work_id, reason);
706
+ archive = targetArchive;
707
+ if (current.status === "failed") {
708
+ if (prepared.result_sha256 !== (current.result === null ? null : crypto.createHash("sha256").update(current.result).digest("hex")))
709
+ throw new AppError("work_retry_conflict", "Failed Work receipt changed during retry", 1);
710
+ fs.mkdirSync(archive, { recursive: true });
711
+ if (!pending)
712
+ publishReceiptFile(journal, JSON.stringify(prepared));
713
+ const receipt = path.join(archive, "accepted-receipt.json");
714
+ const receiptBytes = JSON.stringify({ work_id: current.work_id, status: current.status, result: current.result, result_sha256: prepared.result_sha256 });
715
+ if (fs.existsSync(receipt) && fs.readFileSync(receipt, "utf8") !== receiptBytes)
716
+ throw new AppError("work_retry_conflict", "Archived receipt differs from failed Work", 1);
717
+ if (!fs.existsSync(receipt))
718
+ publishReceiptFile(receipt, receiptBytes);
719
+ for (const file of prepared.entries) {
720
+ const source = path.join(directory, file), target = path.join(archive, file);
721
+ if (fs.existsSync(source)) {
722
+ if (fs.existsSync(target))
723
+ throw new AppError("archive_conflict", "Both live and archived Work artifact exist; preserve both", 1, { source, target });
724
+ fs.renameSync(source, target);
725
+ }
726
+ else if (!fs.existsSync(target))
727
+ throw new AppError("archive_artifact_missing", "Work artifact is absent from both retry locations", 1, { source, target });
728
+ }
729
+ for (const folder of [archive, directory]) {
730
+ const descriptor = fs.openSync(folder, "r");
731
+ try {
732
+ fs.fsyncSync(descriptor);
733
+ }
734
+ finally {
735
+ fs.closeSync(descriptor);
736
+ }
737
+ }
738
+ for (const column of ["prompt_path", "result_path"]) {
739
+ const file = column === "prompt_path" ? "prompt.md" : "result.json";
740
+ context.db.run(`UPDATE work_sessions SET ${column} = ? WHERE work_id = ? AND ${column} = ?`, [path.join(archive, file), work.work_id, path.join(directory, file)]);
741
+ }
742
+ context.db.run("UPDATE works SET status = 'created', result = NULL, started_at = NULL, completed_at = NULL, updated_at = ? WHERE work_id = ? AND status = 'failed'", [context.now(), work.work_id]);
743
+ }
744
+ context.db.exec("COMMIT");
745
+ }
746
+ catch (error) {
747
+ context.db.exec("ROLLBACK");
748
+ throw error;
749
+ }
750
+ fs.rmSync(journal, { force: true });
751
+ refreshRunWorkProjection(context, work.project_id, work.run_id);
752
+ return { ok: true, work_id: work.work_id, archived_attempt: path.relative(requireRunHome(run), archive).split(path.sep).join("/"), reason };
753
+ }
754
+ function sharedReviewInput(work, run, initialize = false) {
755
+ const kind = parsePayload(work)?.kind;
756
+ const relative = kind === "code-review" ? "06-code-review/review-context.json" : kind === "plan-review" ? "04-plan-review/work-context.json" : null;
757
+ if (!relative || !work.parent_work_id)
758
+ return null;
759
+ const file = path.join(requireRunHome(run), relative);
760
+ if (!fs.existsSync(file))
761
+ return null;
762
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
763
+ if (value.read_only_input?.parent_work_id !== work.parent_work_id)
764
+ return null;
765
+ if (!value.read_only_input.fingerprint && initialize) {
766
+ // Called under the Work-start writer reservation, after stage setup has
767
+ // finished. The first reviewer accepts the input shared by this group.
768
+ value.read_only_input.fingerprint = workspaceFingerprint(run.workspace_root);
769
+ const temporary = `${file}.tmp-${crypto.randomUUID()}`;
770
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`);
771
+ fs.renameSync(temporary, file);
772
+ }
773
+ return typeof value.read_only_input.fingerprint === "string" ? value.read_only_input.fingerprint : null;
774
+ }
775
+ async function settle(context, id, status, result, progress, retry) {
776
+ const { work, run, link } = prepareWorkSettlement(context, id, status, result);
777
+ id = work.work_id;
324
778
  let receipts = [];
325
779
  let coordinationDrift = [];
326
- if (status === "completed") {
327
- if (parsePayload(work)?.read_only === true) {
780
+ const assertReadOnlyInput = () => {
781
+ if (status === "completed" && parsePayload(work)?.read_only === true) {
782
+ const shared = sharedReviewInput(work, run);
783
+ // The final reviewer commits the shared input boundary under the writer
784
+ // reservation. Concurrent finishes cannot both skip this verification.
785
+ if (shared && context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND parent_work_id = ? AND work_id <> ? AND status IN ('created','running','paused') AND json_extract(payload_json, '$.read_only') = 1 AND json_extract(payload_json, '$.kind') = ? LIMIT 1", [work.project_id, work.run_id, work.parent_work_id, work.work_id, parsePayload(work)?.kind]))
786
+ return;
328
787
  const contextFile = link ? path.join(path.dirname(link.prompt_path), "context.json") : "";
329
- const baseline = contextFile && fs.existsSync(contextFile) ? JSON.parse(fs.readFileSync(contextFile, "utf8")).workspace_fingerprint : null;
788
+ const baseline = shared ?? (contextFile && fs.existsSync(contextFile) ? JSON.parse(fs.readFileSync(contextFile, "utf8")).workspace_fingerprint : null);
330
789
  const current = workspaceFingerprint(run.workspace_root);
331
790
  if (typeof baseline !== "string" || baseline !== current)
332
- throw new AppError("read_only_work_mutated_workspace", "Read-only Work changed the accepted workspace", 2, { work_id: work.work_id, baseline, current });
791
+ throw new AppError("read_only_input_changed", "The workspace changed during read-only Work; its review input is stale (the writer is unknown)", 2, { work_id: work.work_id, baseline, current });
333
792
  }
793
+ };
794
+ if (status === "completed") {
334
795
  validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link?.result_path ?? null);
335
796
  const packet = codePacket(work);
336
797
  if (packet) {
@@ -340,19 +801,28 @@ async function settle(context, id, status, result, progress) {
340
801
  readCodeCheckProfile(run.workspace_root);
341
802
  coordinationDrift = plannedAreaDrift(packet, result);
342
803
  const artifactDir = path.relative(requireRunHome(run), path.dirname(link.result_path));
343
- receipts = await runCodeChecks(context, { projectId: work.project_id, runId: work.run_id, runHome: requireRunHome(run), workspaceRoot: run.workspace_root, workId: work.work_id, artifactDir, scope: "work", checks: packet.checks.filter((check) => check.run_at === "work"), ...(progress ? { progress } : {}) });
804
+ const requiredChecks = packet.repair?.verification_check_refs?.length
805
+ ? uniqueChecks([...packet.checks.filter((check) => check.run_at === "work"), ...packet.repair.verification_check_refs])
806
+ : packet.checks.filter((check) => check.run_at === "work");
807
+ if (retry)
808
+ validateFailedCheckRetry(context, { projectId: work.project_id, runId: work.run_id, receiptId: retry.receiptId, declarations: requiredChecks, reason: retry.reason });
809
+ receipts = await runCodeChecks(context, { projectId: work.project_id, runId: work.run_id, runHome: requireRunHome(run), workspaceRoot: run.workspace_root, workId: work.work_id, artifactDir, scope: "work", checks: requiredChecks, ...(retry ? { retryReceiptId: retry.receiptId, retryReason: retry.reason } : {}), ...(progress ? { progress } : {}) });
344
810
  const failed = receipts.filter((receipt) => receipt.status !== "passed");
345
811
  if (failed.length)
346
812
  throw new AppError("work_checks_failed", "Work remains running because required checks failed", 2, { work_id: id, failures: failed, all_receipts: receipts });
347
813
  }
348
814
  }
349
815
  const now = context.now();
350
- context.db.exec("BEGIN IMMEDIATE");
816
+ context.db.beginWriteTransaction();
351
817
  try {
818
+ assertReadOnlyInput();
819
+ assertWorkSettlementAllowed(context, work.project_id, work.run_id, work.work_id);
820
+ if (link && !context.db.get("SELECT 1 FROM work_sessions WHERE id = ? AND status = 'running'", [link.id]))
821
+ throw new AppError("work_generation_stale", "Work Session was interrupted or superseded while checks ran", 1, { work_id: id });
822
+ if (link?.result_path && work.parent_work_id !== null)
823
+ publishReceiptFile(receiptIntentPath(link.result_path, link.id), JSON.stringify({ work_id: work.work_id, work_session_id: link.id, status, result_sha256: crypto.createHash("sha256").update(result).digest("hex"), previous_sha256: receiptFileHash(link.result_path) }));
352
824
  context.db.run("UPDATE works SET status = ?, result = ?, completed_at = ?, updated_at = ? WHERE work_id = ?", [status, result, now, now, id]);
353
825
  if (link) {
354
- if (link.result_path && work.parent_work_id !== null)
355
- fs.writeFileSync(link.result_path, result);
356
826
  context.db.run("UPDATE work_sessions SET status = ?, completed_at = ?, updated_at = ? WHERE id = ?", [status, now, now, link.id]);
357
827
  const stillRunning = context.db.get("SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running' LIMIT 1", [link.session_id]);
358
828
  if (!stillRunning)
@@ -364,18 +834,25 @@ async function settle(context, id, status, result, progress) {
364
834
  context.db.exec("ROLLBACK");
365
835
  throw error;
366
836
  }
837
+ materializePendingWorkResults(context, work.project_id, work.run_id);
838
+ settleRecoveryWork(context, work.work_id, status);
367
839
  refreshRunWorkProjection(context, work.project_id, work.run_id);
368
- const newlyReady = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? AND status = 'created' ORDER BY created_at, work_id`, [work.project_id, work.run_id]).filter((candidate) => isReady(context, candidate)).map((candidate) => ({ work_id: candidate.work_id, start_command: workStartCommand(context, candidate) }));
840
+ const control = runControlDirective(context, work.project_id, work.run_id);
841
+ const newlyReady = control ? [] : context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? AND status = 'created' ORDER BY created_at, work_id`, [work.project_id, work.run_id]).filter((candidate) => isReady(context, candidate)).map((candidate) => ({ work_id: candidate.work_id, launch_policy: candidate.launch_policy, start_command: workStartCommand(context, candidate) }));
369
842
  appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: `work_${status}`, work_id: work.work_id, session_id: link?.session_id ?? null, ...(coordinationDrift.length ? { coordination_drift: coordinationDrift } : {}) });
370
843
  for (const ready of newlyReady)
371
844
  appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_dependency_unblocked", work_id: ready.work_id, completed_dependency: work.work_id });
372
- return { ok: true, work_id: id, status, checks: receipts, coordination: { planned_write_areas: codePacket(work)?.planned_write_areas ?? [], drift: coordinationDrift }, newly_ready: newlyReady, graph: codeWorkGraph(context, work.project_id, work.run_id), usage: { status: "provisional", reason: "final usage is controller-owned" } };
845
+ return { ok: true, ...(control ? { control } : {}), work_id: id, status, checks: receipts, coordination: { planned_write_areas: codePacket(work)?.planned_write_areas ?? [], drift: coordinationDrift }, newly_ready: newlyReady, graph: codeWorkGraph(context, work.project_id, work.run_id), usage: { status: "provisional", reason: "final usage is controller-owned" } };
373
846
  }
847
+ function recoveryPrompt(recovery) { return ["<recovery_identity>", `- recovery_id: ${recovery.recoveryId}`, `- execution_generation: ${recovery.generation}`, "This Work was interrupted and is now an authorized recovery segment of the same assignment.", "</recovery_identity>", "", "<recovery_instructions>", `Read the retained pre-interruption evidence at ${recovery.evidencePath}.`, "Before changing files or rerunning a command, inspect the workspace, receipts, logs, and partial artifacts. Do not assume the last command succeeded or failed merely because its reply was lost.", "Preserve accepted work. Do not repeat completed Work, create undeclared Work, alter the original requirements, or edit dd-flow runtime state/evidence.", "Observe an existing check or finish instead of duplicating it. Retry only through an exact runtime retry command after establishing that its prior outcome permits it.", "Record the concrete unresolved operation rather than guessing if an external effect cannot be reconciled.", "</recovery_instructions>"].join("\n"); }
374
848
  function plannedAreaDrift(packet, result) {
375
849
  const changed = JSON.parse(result).changed_paths;
376
850
  if (!Array.isArray(changed) || packet.planned_write_areas.length === 0)
377
851
  return [];
378
- return changed.filter((item) => typeof item === "string" && !packet.planned_write_areas.some((area) => item === area || item.startsWith(`${area}/`)));
852
+ return changed.filter((item) => typeof item === "string" && !packet.planned_write_areas.some((area) => {
853
+ const normalized = area.replace(/[\\/]+$/, "");
854
+ return item === normalized || item.startsWith(`${normalized}/`);
855
+ }));
379
856
  }
380
857
  function bindSession(context, work, run, identity, now) {
381
858
  const priorWorkSession = context.db.get("SELECT session_id FROM work_sessions WHERE work_id = ? ORDER BY created_at DESC LIMIT 1", [work.work_id])?.session_id ?? null;
@@ -385,16 +862,28 @@ function bindSession(context, work, run, identity, now) {
385
862
  // Work ancestry and provider-tree containment are different relations. An
386
863
  // isolated worker is logically a child Work but physically a provider root.
387
864
  const parentSession = inferredParentSession ?? identity.parentSessionId;
865
+ // Stored provider ancestry uses internal keys, just like hook_events.
866
+ // Resolve native IDs only when rendering diagnostics; changing storage here
867
+ // breaks existing bindings and usage ancestry joins.
388
868
  const providerParentSession = identity.parentSessionId;
869
+ const identityDetails = (sessionKey = identity.sessionId, parentKey = parentSession) => ({
870
+ internal_session_key: sessionKey,
871
+ native_session_id: sessionKey === identity.sessionId ? identity.nativeSessionId : context.db.get("SELECT provider_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, sessionKey])?.provider_session_id ?? null,
872
+ internal_parent_session_key: parentKey,
873
+ native_parent_session_id: parentKey ? context.db.get("SELECT provider_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, parentKey])?.provider_session_id ?? null : null,
874
+ harness: identity.harness
875
+ });
389
876
  if (work.parent_work_id && !parentSession)
390
877
  throw new AppError("parent_session_required", "Child Work requires a confirmed parent Work/Session link", 1, { work_id: work.work_id, parent_work_id: work.parent_work_id });
391
878
  if (work.launch_policy === "fresh_agent_required" && (identity.sessionId === parentSession || context.db.get("SELECT 1 FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE w.project_id = ? AND w.run_id = ? AND ws.session_id = ? LIMIT 1", [work.project_id, work.run_id, identity.sessionId])))
392
- throw new AppError("fresh_session_required", "This Work requires a fresh Session in this RUN", 1, { work_id: work.work_id, session_id: identity.sessionId });
879
+ throw new AppError("fresh_session_required", "This Work requires a fresh Session in this RUN", 1, { work_id: work.work_id, effect: "no_effect", recoverable: true, handoff_required: true, ...identityDetails() });
393
880
  const existing = context.db.get("SELECT session_id, parent_session_id, provider_parent_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, identity.sessionId]);
394
- if (existing && existing.parent_session_id && parentSession && existing.parent_session_id !== parentSession)
395
- throw new AppError("session_parent_conflict", "Observed Session already has a different immutable parent", 1, { session_id: identity.sessionId });
881
+ // A reuse-allowed Work can follow another Work in this same Session. Its
882
+ // Work predecessor is not a new physical/logical parent of the Session.
883
+ if (existing && existing.parent_session_id && parentSession && parentSession !== identity.sessionId && existing.parent_session_id !== parentSession)
884
+ throw new AppError("session_parent_conflict", "Observed Session already has a different immutable parent", 1, { work_id: work.work_id, ...identityDetails(existing.session_id, existing.parent_session_id), conflicting_internal_parent_session_key: parentSession });
396
885
  if (existing?.provider_parent_session_id && providerParentSession && existing.provider_parent_session_id !== providerParentSession)
397
- throw new AppError("provider_session_parent_conflict", "Observed provider Session already has a different immutable provider parent", 1, { session_id: identity.sessionId });
886
+ throw new AppError("provider_session_parent_conflict", "Observed provider Session already has a different immutable provider parent", 1, { work_id: work.work_id, ...identityDetails(existing.session_id, existing.parent_session_id), conflicting_internal_provider_parent_session_key: providerParentSession, conflicting_native_parent_session_id: context.db.get("SELECT provider_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, providerParentSession])?.provider_session_id ?? null });
398
887
  context.db.run(`INSERT INTO sessions (session_id, project_id, harness, provider_session_id, provider_parent_session_id, agent_id, parent_session_id, provider, model, reasoning, mode, agent_type, project_root, flow_kind, status, run_id, protocol_id, worker_id, workspace_path, continuation_policy, current_stage, next_action, last_action_hash, continuation_count, stop_reason, transcript_path, cwd, metadata_json, coverage_units_json, created_at, updated_at, stopped_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'vnext', 'active', ?, NULL, ?, ?, 'go_router', 'work', NULL, NULL, 0, NULL, ?, ?, '{}', '[]', ?, ?, NULL) ON CONFLICT(session_id, project_id) DO UPDATE SET harness = excluded.harness, provider_session_id = COALESCE(excluded.provider_session_id, provider_session_id), provider_parent_session_id = COALESCE(excluded.provider_parent_session_id, provider_parent_session_id), agent_id = COALESCE(excluded.agent_id, agent_id), parent_session_id = COALESCE(excluded.parent_session_id, parent_session_id), provider = COALESCE(excluded.provider, provider), model = COALESCE(excluded.model, model), reasoning = COALESCE(excluded.reasoning, reasoning), mode = COALESCE(excluded.mode, mode), agent_type = COALESCE(excluded.agent_type, agent_type), flow_kind = excluded.flow_kind, run_id = excluded.run_id, worker_id = excluded.worker_id, workspace_path = excluded.workspace_path, transcript_path = COALESCE(excluded.transcript_path, transcript_path), cwd = excluded.cwd, updated_at = excluded.updated_at`, [identity.sessionId, work.project_id, identity.harness, identity.providerSessionId, providerParentSession, identity.agentId, existing?.parent_session_id ?? (parentSession === identity.sessionId ? null : parentSession), identity.provider, identity.model, identity.reasoning, identity.mode, identity.agentType, run.project_root, work.run_id, work.work_id, run.workspace_root, identity.transcriptPath, run.workspace_root, now, now]);
399
888
  reactivateBoundSession(context, work.project_id, identity.sessionId, now);
400
889
  }
@@ -408,6 +897,15 @@ export function bindSessionForResume(context, workId, identity, now) {
408
897
  function reactivateBoundSession(context, projectId, sessionId, now) {
409
898
  context.db.run("UPDATE sessions SET status = 'active', stop_reason = NULL, stopped_at = NULL, updated_at = ? WHERE project_id = ? AND session_id = ?", [now, projectId, sessionId]);
410
899
  }
900
+ export function prepareWorkResult(context, id, result) {
901
+ try {
902
+ const { work, run, link } = prepareWorkSettlement(context, id, "completed", result);
903
+ validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link?.result_path ?? null);
904
+ }
905
+ catch (error) {
906
+ prepareError(error, { work_id: id });
907
+ }
908
+ }
411
909
  function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, runId, resultPath) {
412
910
  if (!work.result_schema)
413
911
  return;
@@ -420,15 +918,8 @@ function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, r
420
918
  catch {
421
919
  throw new AppError("validation", "Work result must be JSON for its declared result schema", 2, { work_id: work.work_id, result_schema: work.result_schema });
422
920
  }
423
- const candidate = `${resultPath}.candidate-${process.pid}`;
424
- fs.writeFileSync(candidate, result);
425
- try {
426
- validateSchema({ schemaName: work.result_schema.replace(/^dd-flow\//, "").replace(/@\d+$/, ""), file: candidate, projectRoot, runId, runRoot: runHome });
427
- }
428
- finally {
429
- fs.rmSync(candidate, { force: true });
430
- }
431
- if (work.result_schema === "dd-flow/code-work-result@2")
921
+ validateSchema({ schemaName: work.result_schema.replace(/^dd-flow\//, "").replace(/@\d+$/, ""), file: resultPath, data: parsed, projectRoot, runId, runRoot: runHome });
922
+ if (work.result_schema === "dd-flow/code-work-result@3")
432
923
  validateCodeWorkResult(work, parsed, workspaceRoot, runHome, runId);
433
924
  if (work.result_schema === "dd-flow/code-review-result@1")
434
925
  validateCodeReviewResult(work, parsed, { workspaceRoot, runHome, runId });
@@ -437,20 +928,29 @@ function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, r
437
928
  }
438
929
  function validateCodeWorkResult(work, value, projectRoot, runHome, runId) {
439
930
  const result = value;
931
+ const changedPaths = (result.changed_paths ?? []).map((item) => normalizeWorkspacePath(projectRoot, item));
932
+ const ignored = ignoredWorkspacePaths(projectRoot, changedPaths);
933
+ if (ignored.length)
934
+ throw new AppError("environment_repair_not_product_change", "CODE Work must record ignored environment repair separately, not as a product changed_path", 2, { work_id: work.work_id, paths: ignored });
440
935
  if ((result.deviations?.length ?? 0) > 0 || (result.blockers?.length ?? 0) > 0)
441
936
  throw new AppError("work_contract_incomplete", "CODE Work cannot complete with unresolved deviations or blockers; fail the Work and report the contract mismatch", 2, { work_id: work.work_id, deviations: result.deviations ?? [], blockers: result.blockers ?? [] });
442
937
  const packet = codePacket(work);
443
938
  if (!packet)
444
939
  return;
445
- const acceptedCriteria = new Set(packet.acceptance.map((item) => item.criterion_id).filter((item) => typeof item === "string"));
940
+ const acceptedObligations = new Set(packet.acceptance.map((item) => item.criterion_id).filter((item) => typeof item === "string"));
941
+ for (const check of packet.checks)
942
+ acceptedObligations.add(check.id);
943
+ for (const finding of packet.repair?.review_findings ?? [])
944
+ for (const ref of finding.obligation_refs ?? [])
945
+ acceptedObligations.add(ref);
446
946
  for (const item of result.evidence ?? []) {
447
- if (!item.criterion_id || !acceptedCriteria.has(item.criterion_id))
448
- throw new AppError("evidence_criterion_unknown", "CODE Work evidence must reference an acceptance criterion assigned to this Work", 2, { work_id: work.work_id, criterion_id: item.criterion_id ?? null });
947
+ if (!item.obligation_ref || !acceptedObligations.has(item.obligation_ref))
948
+ throw new AppError("evidence_obligation_unknown", "CODE Work evidence must reference an obligation assigned to this Work", 2, { work_id: work.work_id, obligation_ref: item.obligation_ref ?? null, accepted_obligation_refs: [...acceptedObligations] });
449
949
  for (const ref of item.refs ?? [])
450
950
  assertPortableArtifactRef(ref, { workspaceRoot: projectRoot, runHome, runId });
451
951
  }
452
952
  const documentUpdates = (packet.document_updates ?? []);
453
- const changed = new Set(result.changed_paths ?? []);
953
+ const changed = new Set(changedPaths);
454
954
  const missingDocuments = documentUpdates.map((entry) => entry.path).filter((entry) => !changed.has(entry));
455
955
  if (missingDocuments.length)
456
956
  throw new AppError("document_update_missing", "CODE Work did not materialize every document update assigned by PLAN", 2, { work_id: work.work_id, missing_paths: missingDocuments });
@@ -458,36 +958,72 @@ function validateCodeWorkResult(work, value, projectRoot, runHome, runId) {
458
958
  return true; const current = crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); return entry.action === "create" ? entry.baseline_sha256 !== null : current === entry.baseline_sha256; }).map((entry) => entry.path);
459
959
  if (unchangedDocuments.length)
460
960
  throw new AppError("document_update_not_materialized", "Assigned durable document updates must exist and differ from their PLAN baseline", 2, { work_id: work.work_id, unchanged_paths: unchangedDocuments });
461
- const assigned = packet.repair?.review_finding_ids ?? [];
961
+ const assigned = packet.repair?.review_findings?.map((finding) => finding.finding_ref) ?? [];
962
+ validateReviewResolutions(work.work_id, assigned, result.resolutions ?? []);
462
963
  if (assigned.length) {
463
- if ((result.changed_paths?.length ?? 0) === 0)
964
+ if (changedPaths.length === 0)
464
965
  throw new AppError("review_repair_no_change", "Review repair must materialize a project change; a no-op cannot resolve a finding", 2, { work_id: work.work_id, findings: assigned });
465
- const resolved = new Set(result.resolved_finding_refs ?? []);
466
- const missing = assigned.filter((finding) => !resolved.has(finding));
467
- const unexpected = [...resolved].filter((finding) => !assigned.includes(finding));
468
- if (missing.length || unexpected.length)
469
- throw new AppError("review_repair_incomplete", "Review repair must explicitly resolve exactly its assigned finding references", 2, { work_id: work.work_id, missing, unexpected });
966
+ for (const resolution of result.resolutions ?? [])
967
+ for (const ref of resolution.evidence_refs ?? [])
968
+ assertPortableArtifactRef(ref, { workspaceRoot: projectRoot, runHome, runId });
470
969
  }
471
970
  }
971
+ export function validateReviewResolutions(workId, assigned, resolutions) {
972
+ const resolved = new Set(resolutions.map((resolution) => resolution.finding_ref).filter((ref) => Boolean(ref)));
973
+ const missing = assigned.filter((finding) => !resolved.has(finding));
974
+ const unexpected = [...resolved].filter((finding) => !assigned.includes(finding));
975
+ const duplicate = resolutions.length !== resolved.size;
976
+ if (missing.length || unexpected.length || duplicate)
977
+ throw new AppError("review_repair_incomplete", "Review repair must include exactly one resolution for each assigned finding reference", 2, { work_id: workId, missing, unexpected, duplicate });
978
+ }
472
979
  function renderWorkerPrompt(context, work, run, dependencies) {
473
980
  const command = flowCommand(context);
474
981
  const packet = codePacket(work);
475
- const codeContext = packet ? ["<semantic_spine>", JSON.stringify(packet.semantic_spine, null, 2), "</semantic_spine>", "", ...(packet.repair ? ["<repair_context>", JSON.stringify(packet.repair, null, 2), "Read the failed receipt and its linked stdout/stderr before editing. Preserve the accepted origin context and fix only the evidenced failure.", "</repair_context>", ""] : []), "<accepted_requirements>", JSON.stringify(packet.requirements, null, 2), "</accepted_requirements>", "", "<write_boundary_invariant>", "For a mutation guarded by membership, ownership, authorization or parent lifecycle state, preserve that predicate in the write statement or make guard and write one explicit transaction with the needed lock. A prior read may diagnose an error but never proves a later write remains allowed. Apply this to create, update, delete and parent-state mutations.", "</write_boundary_invariant>", "", "<acceptance_context>", "The criteria below are end-to-end context. Complete this Work's semantic contribution and declared checks; another ordered Work may own a different acceptance surface.", JSON.stringify(packet.acceptance, null, 2), "</acceptance_context>", "", "<required_read>", "These are mandatory starting sources, not a read allowlist. Read any additional project files needed to implement the Work correctly.", ...packet.required_read.map((item) => `- ${resolveRunReferences(item, work.run_id, requireRunHome(run))}`), "</required_read>", "", "<discovery_boundary>", "These are likely discovery areas, not a hard boundary. Expand project-local investigation when required and report material additions.", ...packet.discovery_boundary.map((item) => `- ${item}`), "</discovery_boundary>", "", "<planned_write_areas>", "SOFT COORDINATION HINT ONLY. These paths help the coordinator avoid concurrent collisions. They do not grant or deny write permission and do not limit the files needed for this Work. You may create or change any project file under workspace_root that is necessary and in semantic scope; report every actual changed path.", ...(packet.planned_write_areas.length ? packet.planned_write_areas.map((item) => `- ${item}`) : ["- none predicted; derive the necessary files from the task"]), "</planned_write_areas>", "", ...(packet.provides_checks.length ? ["<provided_checks>", ...packet.provides_checks.map((item) => `- ${item.id}: materialize ${item.command}${item.definition ? ` as ${item.definition}` : ""}; it is not usable until this Work finishes.`), "Update the declared project command or alias before Work finish. The CLI verifies the materialization and then executes the check.", "</provided_checks>", ""] : []), "<verification>", ...packet.checks.map((item) => `- ${item.id} at ${item.run_at}: ${item.command} — ${item.purpose}`), "The CLI executes work-scoped checks and retains their receipts. Report semantic evidence only; do not rerun declared checks manually.", "</verification>", "", "<stop_conditions>", ...packet.stop_conditions.map((item) => `- ${item}`), "</stop_conditions>", ""] : [];
982
+ const finishWorkCommand = managedLifecycleCommand(context, `${command} work finish ${work.work_id} --result-stdin --project-root ${JSON.stringify(run.project_root)} --json --progress-jsonl`);
983
+ const failWorkCommand = managedLifecycleCommand(context, `${command} work fail ${work.work_id} --reason "receipt path + exact external or semantic blocker" --project-root ${JSON.stringify(run.project_root)} --json`);
984
+ const mergeWork = parsePayload(work)?.kind === "merge";
985
+ const writeBoundary = mergeWork
986
+ ? ["MERGE does not own product-code repair. Use only the stage packet's merge apply command; resolve only paths that Git reports as unmerged. Do not edit integration code, tests, documentation or configuration to make a gate pass.", "RUN artifacts are read-only evidence: refer to them with run:// URIs and let dd-flow persist your submitted result."]
987
+ : [`HARD RULE: project source reads and writes must remain under ${run.workspace_root}.`, "Do not write through project_root, outside workspace_root, into another RUN, or into Git/worktree control data. Do not create, switch, merge or delete branches/worktrees.", "RUN artifacts are read-only evidence: refer to them with run:// URIs and let dd-flow persist your submitted result. Accepted requirements, non-goals and stop_conditions are semantic hard boundaries. planned_write_areas is not."];
988
+ const completionRepair = mergeWork
989
+ ? ["A failed integration check is evidence for a source-repair cycle, not permission to repair the integration workspace. Follow the exact merge repair command returned by dd-flow."]
990
+ : ["Read the failed receipt and its stdout/stderr. Fix project-owned source, migration, test, formatting, or configuration errors in this same Work, then use the returned retry_command with your result. Internal invocation IDs are runtime-owned; do not copy or invent them. Do not invent a cause that does not appear in the retained output."];
991
+ const codeContext = packet ? ["<semantic_spine>", JSON.stringify(packet.semantic_spine, null, 2), "</semantic_spine>", "", ...(packet.repair ? ["<repair_context>", JSON.stringify(packet.repair, null, 2), "Read the failed receipt and its linked stdout/stderr before editing. Preserve the accepted origin context and fix only the evidenced failure.", "</repair_context>", ""] : []), "<accepted_requirements>", JSON.stringify(packet.requirements, null, 2), "</accepted_requirements>", "", "<write_boundary_invariant>", "For a mutation guarded by membership, ownership, authorization or parent lifecycle state, preserve that predicate in the write statement or make guard and write one explicit transaction with the needed lock. A prior read may diagnose an error but never proves a later write remains allowed. Apply this to create, update, delete and parent-state mutations.", "</write_boundary_invariant>", "", "<acceptance_context>", "The criteria below are end-to-end context. Complete this Work's semantic contribution and declared checks; another ordered Work may own a different acceptance surface.", JSON.stringify(packet.acceptance, null, 2), "</acceptance_context>", "", "<required_read>", "These are mandatory starting sources, not a read allowlist. Read any additional project files needed to implement the Work correctly.", ...packet.required_read.map((item) => `- ${resolveRunReferences(item, work.run_id, requireRunHome(run))}`), "</required_read>", "", "<discovery_boundary>", "These are likely discovery areas, not a hard boundary. Expand project-local investigation when required and report material additions.", ...packet.discovery_boundary.map((item) => `- ${item}`), "</discovery_boundary>", "", "<planned_write_areas>", "SOFT COORDINATION HINT ONLY. These paths help the coordinator avoid concurrent collisions. They do not grant or deny write permission and do not limit the files needed for this Work. You may create or change any project file under workspace_root that is necessary and in semantic scope; report every actual changed path.", ...(packet.planned_write_areas.length ? packet.planned_write_areas.map((item) => `- ${item}`) : ["- none predicted; derive the necessary files from the task"]), "</planned_write_areas>", "", ...(packet.provides_checks.length ? ["<provided_checks>", ...packet.provides_checks.map((item) => `- ${item.id}: materialize ${item.command}${item.definition ? ` as ${item.definition}` : ""}; it is not usable until this Work finishes.`), "Update the declared project command or alias before Work finish. The CLI verifies materialization at Work finish. Execution occurs at its declared run_at gate, not necessarily in this Work.", "</provided_checks>", ""] : []), "<verification>", ...packet.checks.map((item) => `- ${item.id} at ${item.run_at}: ${item.command} — ${item.purpose}`), "The CLI executes work-scoped checks and retains their receipts. Report semantic evidence only; do not rerun declared checks manually.", "</verification>", "", "<stop_conditions>", ...packet.stop_conditions.map((item) => `- ${item}`), "</stop_conditions>", ""] : [];
476
992
  if (packet)
477
993
  codeContext.push("<document_updates>", JSON.stringify(packet.document_updates, null, 2), "Materialize every listed update. dd-flow verifies the resulting file against its PLAN-time baseline.", "</document_updates>", "", "<completion_contract>", "Successful completion requires empty deviations and blockers and every assigned document update in changed_paths. A necessary path outside planned_write_areas is normal coordination drift, not a blocker; include it in changed_paths and continue.", "</completion_contract>", "");
478
- return ["<work>", `- work_id: ${work.work_id}`, `- run_id: ${work.run_id}`, `- project_root: ${run.project_root}`, `- workspace_root: ${run.workspace_root}`, `- run_home: ${requireRunHome(run)}`, "</work>", "", "<hard_write_boundary>", `HARD RULE: project source reads and writes must remain under ${run.workspace_root}.`, "Do not write through project_root, outside workspace_root, into another RUN, or into Git/worktree control data. Do not create, switch, merge or delete branches/worktrees.", "RUN artifacts are read-only evidence: refer to them with run:// URIs and let dd-flow persist your submitted result. Accepted requirements, non-goals and stop_conditions are semantic hard boundaries. planned_write_areas is not.", "</hard_write_boundary>", "", ...codeContext, "<dependency_results>", JSON.stringify(dependencies.filter(Boolean), null, 2), "</dependency_results>", "", "<task>", resolveRunReferences(work.task, work.run_id, requireRunHome(run)), "</task>", "", ...(work.result_schema ? ["<result_contract>", `Return JSON matching \`${work.result_schema}\`.`, ...resultSchemaGuidance(work, run.id), "Do not create result.json yourself. Send the JSON to dd-flow on stdin; it atomically validates and stores the canonical receipt.", "</result_contract>", ""] : []), "<completion>", "The CLI runs every declared required check before accepting this Work. A failed receipt means only that the check failed; it is not proof of an engine, harness, dependency, or environment blocker.", "Read the failed receipt and its stdout/stderr. Fix project-owned source, migration, test, formatting, or configuration errors in this same Work, then call Finish again. Do not invent a cause that does not appear in the retained output.", "Use Fail only for a concrete external blocker after deterministic bootstrap or a contradiction with an accepted requirement/non-goal. Never fail merely because a necessary project path was absent from planned_write_areas.", "Finish may run for several minutes. Preserve the shell tool's process/session handle and poll that same invocation until it exits; progress arrives as JSONL on stderr. Never reissue Finish merely because final stdout has not arrived.", `Finish as one standalone command, piping your JSON object to stdin: ${command} work finish ${work.work_id} --result-stdin --project-root ${JSON.stringify(run.project_root)} --json --progress-jsonl`, `Fail only for an evidenced external or semantic-contract blocker: ${command} work fail ${work.work_id} --reason "receipt path + exact external or semantic blocker" --project-root ${JSON.stringify(run.project_root)} --json`, "</completion>", ""].join("\n");
994
+ if (packet)
995
+ codeContext.push("<temporary_services>", "Prefer the declared check launcher: it already owns check resources. If the planned scenario genuinely requires an interactive HTTP service, use the managed supervisor below. This is a template: replace the project service command, port names and readiness path from the plan/project instructions; do not invent a fixed port.", `${command} runtime process start --run ${run.id} --project-root ${JSON.stringify(run.project_root)} --command '<project-service-command>' --ports api --ready-port api --ready-path /health --json --progress-jsonl`, "The service receives DD_FLOW_PORT_API (and equivalent variables for all declared names). The command stays running as its supervisor. Retain its tool handle; wait for the service ready event and read its service.json receipt. Pass those exact ports and the same project environment to reset/seed, API and browser operations.", "A ready receipt proves service readiness only. Record the scenario outcome and real evidence separately. After the scenario, execute the exact stop_command from that receipt, then wait for the supervisor to exit. Never use pkill/killall or stop a sibling's process. If cleanup fails, retain the process id and report the failure; do not claim the resource is free.", "</temporary_services>", "");
996
+ return ["<work>", `- work_id: ${work.work_id}`, `- run_id: ${work.run_id}`, `- project_root: ${run.project_root}`, `- workspace_root: ${run.workspace_root}`, `- run_home: ${requireRunHome(run)}`, "</work>", "", "<cli_context>", `- Work commands use the short ID ${shortWorkId(work.work_id)}; dd-flow binds it to this RUN.`, `- @project = ${run.project_root}`, `- @workspace = ${run.workspace_root}`, `- @run = ${requireRunHome(run)}`, "- @ aliases are accepted only by declared dd-flow path parameters. Shell tools such as cat and rg require ordinary paths relative to cwd or absolute paths.", "- Lifecycle invocation IDs are internal runtime authority and are intentionally omitted from commands.", "</cli_context>", "", "<hard_write_boundary>", ...writeBoundary, "</hard_write_boundary>", "", ...codeContext, "<dependency_results>", JSON.stringify(dependencies.filter(Boolean), null, 2), "</dependency_results>", "", "<task>", resolveRunReferences(work.task, work.run_id, requireRunHome(run)), "</task>", "", ...(work.result_schema ? ["<result_contract>", `Return JSON matching \`${work.result_schema}\`.`, ...resultSchemaGuidance(work, run.id), "Do not create result.json yourself. Send the JSON to dd-flow on stdin; it atomically validates and stores the canonical receipt.", "</result_contract>", ""] : []), "<completion>", packet?.repair?.verification_check_refs?.length ? "Work finish runs its normal work-scoped checks plus the listed causal repair checks. Their original run_at remains an aggregate obligation; this is the additional proof required before accepting this repair." : "Work finish runs only declared run_at=work checks. Stage finish owns readiness/code/merge gates; successful Work completion does not mean those gates have passed.", "A failed receipt means only that the check failed; it is not proof of an engine, harness, dependency, or environment blocker.", ...completionRepair, "Use Fail only for a concrete external blocker after deterministic bootstrap or a contradiction with an accepted requirement/non-goal. Never fail merely because a necessary project path was absent from planned_write_areas.", "Finish may run for several minutes. Preserve the shell tool's process/session handle and poll that same invocation until it exits; progress arrives as JSONL on stderr. Never reissue Finish merely because final stdout has not arrived.", `Finish as one standalone command with a quoted heredoc (replace the example JSON with your result):\n${finishWorkCommand} <<'DD_FLOW_RESULT'\n{}\nDD_FLOW_RESULT`, `Fail only for an evidenced external or semantic-contract blocker: ${failWorkCommand}`, "</completion>", ""].join("\n");
479
997
  }
480
- function resultSchemaGuidance(work, runId) {
998
+ export function resultSchemaGuidance(work, runId) {
481
999
  const schema = work.result_schema;
482
1000
  const refs = `Evidence refs for project source are relative to workspace_root; RUN evidence uses run://${runId}/path/to/artifact.`;
483
- if (schema === "dd-flow/code-work-result@2")
484
- return [refs, "Use this complete minimal shape. For a review repair, also include resolved_finding_refs with exactly the finding references assigned in repair_context:", "```json", JSON.stringify({ schema_id: schema, summary: "What was implemented.", changed_paths: ["project-relative/path"], evidence: [{ criterion_id: "AC-001", refs: ["project-relative/evidence", `run://${runId}/05-code/checks/receipt.json`] }], deviations: [], blockers: [], resolved_finding_refs: [] }, null, 2), "```"];
1001
+ if (schema === "dd-flow/code-work-result@3") {
1002
+ const packet = codePacket(work);
1003
+ const obligations = [...new Set([
1004
+ ...(packet?.acceptance ?? []).map((item) => item.criterion_id).filter((id) => Boolean(id)),
1005
+ ...(packet?.checks ?? []).map((item) => item.id),
1006
+ ...(packet?.repair?.review_findings ?? []).flatMap((finding) => finding.obligation_refs ?? [])
1007
+ ])];
1008
+ const findings = packet?.repair?.review_findings ?? [];
1009
+ return [refs, `Assigned obligation refs: ${JSON.stringify(obligations)}. Cite only these in evidence.obligation_ref.`,
1010
+ "This is a shape template, not a completed result. Populate changed_paths and evidence from the actual work and existing files; empty arrays below do not establish completion.",
1011
+ "For a gate repair, cite the assigned check id. For a review repair, replace each resolution summary and fill evidence_refs with existing evidence proving its required outcome. Ordinary Work has resolutions: [].",
1012
+ "```json", JSON.stringify({ schema_id: schema, summary: "Describe the actual implementation.", changed_paths: [], evidence: [], deviations: [], blockers: [], resolutions: findings.map((finding) => ({ finding_ref: finding.finding_ref, summary: "Describe how the assigned required outcome was achieved.", evidence_refs: [] })) }, null, 2), "```",
1013
+ "Each evidence entry has exactly obligation_ref (one assigned ref) and refs (nonempty list of existing evidence paths). Each resolution has finding_ref, summary and nonempty evidence_refs. Do not invent file names or finding ids."];
1014
+ }
485
1015
  if (schema === "dd-flow/code-review-result@1") {
486
- return [refs, "Assess every assigned aspect exactly once. Number findings locally inside this reviewer Work as FIND-001, FIND-002, ...; dd-flow adds the Work id to form the canonical reference.", "Use this complete minimal shape. Report only material, direct-evidence findings; taste and cosmetics are not findings:", "```json", JSON.stringify({ schema_id: schema, verdict: "pass | findings | blocked", summary: "Concise evidence-backed conclusion.", aspects: [{ aspect_id: "assigned_aspect_id", verdict: "pass | findings | blocked", summary: "Conclusion.", evidence_refs: ["path/to/file", `run://${runId}/05-code/checks/receipt.json`] }], findings: [{ finding_id: "FIND-001", aspect_id: "assigned_aspect_id", priority: "p0 | p1 | p2 | p3", problem: "Violated obligation or rule.", impact: "Concrete risk or failure.", evidence_refs: ["path/to/file"], obligation_refs: ["R-001 | AC-001 | policy ref"] }] }, null, 2), "```"];
1016
+ const aspect = { aspect_id: "assigned_aspect_id", verdict: "pass", summary: "Conclusion.", evidence_refs: ["path/to/evidence"] };
1017
+ const clean = { schema_id: schema, verdict: "pass", summary: "Concise evidence-backed conclusion.", aspects: [aspect], findings: [] };
1018
+ const mixed = { ...clean, verdict: "findings", aspects: [aspect, { ...aspect, aspect_id: "another_assigned_aspect_id", verdict: "findings" }], findings: [{ finding_id: "FIND-001", aspect_id: "another_assigned_aspect_id", priority: "p1", problem: "Describe the evidenced defect.", impact: "Describe its material impact.", required_outcome: "Describe the required correction.", evidence_refs: ["path/to/evidence"], obligation_refs: ["assigned_obligation_ref"] }] };
1019
+ return [refs, "Assess every assigned aspect exactly once. Number findings locally inside this reviewer Work as FIND-001, FIND-002, ...; dd-flow adds the Work id to form the canonical reference.", "Examples below show no findings and mixed aspect outcomes, not completed results. Replace placeholder ids and paths with assigned aspects, obligations and existing evidence. Choose verdict pass, findings or blocked. Keep findings: [] when none exist. Report only material, direct-evidence defects, not taste or cosmetics.", "```json", JSON.stringify(clean, null, 2), "```", "```json", JSON.stringify(mixed, null, 2), "```"];
487
1020
  }
488
1021
  if (schema !== "dd-flow/plan-review-result@1")
489
1022
  return [];
490
- return [refs, "Use this complete minimal shape; do not add fields. Number findings locally inside this reviewer Work as FIND-001, FIND-002, ...; dd-flow adds the Work id when the coordinator classifies them:", "```json", JSON.stringify({ schema_id: schema, plan_revision: 1, overall_verdict: "pass | watch | needs_changes | blocked", summary: "Concise evidence-backed conclusion.", aspects: [{ aspect_id: "assigned_aspect_id", verdict: "pass | watch | needs_changes | blocked", summary: "Conclusion for this aspect.", evidence_refs: ["path/to/file", `run://${runId}/03-plan/plan.json`], findings: [{ finding_id: "FIND-001", severity: "high | medium | low | info", summary: "Problem, if any.", evidence_refs: ["path/to/file"] }] }] }, null, 2), "```"];
1023
+ const aspect = { aspect_id: "assigned_aspect_id", verdict: "pass", summary: "Conclusion for this aspect.", evidence_refs: ["path/to/evidence"], findings: [] };
1024
+ const clean = { schema_id: schema, plan_revision: 1, overall_verdict: "pass", summary: "Concise evidence-backed conclusion.", aspects: [aspect] };
1025
+ const mixed = { ...clean, overall_verdict: "needs_changes", aspects: [aspect, { ...aspect, aspect_id: "another_assigned_aspect_id", verdict: "needs_changes", findings: [{ finding_id: "FIND-001", severity: "high", summary: "Describe the evidenced defect.", evidence_refs: ["path/to/evidence"] }] }] };
1026
+ return [refs, "Examples below show no findings and mixed aspect outcomes, not completed results. Assess each assigned aspect once, replace placeholder ids, plan_revision and paths with packet values and existing evidence. Choose verdict pass, watch, needs_changes or blocked. Keep findings: [] when an aspect has no findings. Do not add fields. Number findings locally as FIND-001, FIND-002, ...; dd-flow adds the Work id when the coordinator classifies them.", "```json", JSON.stringify(clean, null, 2), "```", "```json", JSON.stringify(mixed, null, 2), "```"];
491
1027
  }
492
1028
  export function validateCodeReviewResultIdentity(work, value) {
493
1029
  const group = codeReviewGroup(work);
@@ -516,6 +1052,7 @@ export function validateCodeReviewResultIdentity(work, value) {
516
1052
  function validateCodeReviewResult(work, value, input) {
517
1053
  validateCodeReviewResultIdentity(work, value);
518
1054
  const result = value;
1055
+ assertReviewAspectEvidence(work, result.aspects ?? [], "CODE");
519
1056
  const findings = result.findings ?? [];
520
1057
  // A reviewer is a child Work and cannot pause its coordinator-owned Stage.
521
1058
  // Its structured blocked result is evidence for the coordinator, which then
@@ -545,6 +1082,7 @@ export function validatePlanReviewResult(work, value, input) {
545
1082
  const unexpected = ids.filter((id) => !expected.has(id));
546
1083
  if (new Set(ids).size !== ids.length || missing.length || unexpected.length)
547
1084
  throw new AppError("review_evidence_invalid", "PLAN reviewer result must assess every assigned aspect exactly once", 2, { work_id: work.work_id, group: group.key, missing, unexpected });
1085
+ assertReviewAspectEvidence(work, aspects, "PLAN");
548
1086
  const findingIds = aspects.flatMap((aspect) => aspect.findings ?? []).map((finding) => finding.finding_id ?? "");
549
1087
  const invalid = findingIds.filter((id) => !/^FIND-\d{3}$/.test(id));
550
1088
  if (new Set(findingIds).size !== findingIds.length || invalid.length)
@@ -559,6 +1097,11 @@ export function validatePlanReviewResult(work, value, input) {
559
1097
  assertPortableArtifactRef(ref, input);
560
1098
  }
561
1099
  }
1100
+ function assertReviewAspectEvidence(work, aspects, stage) {
1101
+ const missing = aspects.filter((aspect) => !Array.isArray(aspect.evidence_refs) || aspect.evidence_refs.length === 0).map((aspect) => aspect.aspect_id ?? "");
1102
+ if (missing.length)
1103
+ throw new AppError("review_evidence_invalid", `${stage} reviewer result requires non-empty evidence_refs for every assigned aspect`, 2, { work_id: work.work_id, missing_aspects: missing });
1104
+ }
562
1105
  function codeReviewGroup(work) {
563
1106
  const payload = parsePayload(work);
564
1107
  const group = payload?.group;
@@ -569,10 +1112,23 @@ function codeReviewGroup(work) {
569
1112
  ? { key: value.key, aspect_ids: value.aspect_ids }
570
1113
  : null;
571
1114
  }
572
- function requireWork(context, id) { ensureWorkRegistry(context); const exact = context.db.get(`SELECT ${workColumns} FROM works WHERE work_id = ?`, [id]); if (exact)
573
- return exact; if (!/^WRK-\d{3,}$/.test(id))
574
- throw new AppError("not_found", "Work is not registered", 1, { work_id: id }); const matches = context.db.all(`SELECT ${workColumns} FROM works WHERE work_id LIKE ? ORDER BY work_id`, [`${id}-%`]); if (matches.length !== 1)
575
- throw new AppError(matches.length ? "ambiguous_work_alias" : "not_found", matches.length ? "Short Work alias is ambiguous" : "Work is not registered", 1, { work_id: id, matches: matches.map((work) => work.work_id) }); return matches[0]; }
1115
+ function requireWork(context, id) {
1116
+ ensureWorkRegistry(context);
1117
+ const configured = context.env.DD_FLOW_INVOCATION_SCOPE;
1118
+ const scope = configured ? JSON.parse(configured) : undefined;
1119
+ const projectId = scope?.projectRoot ? context.db.get("SELECT id FROM projects WHERE root = ?", [scope.projectRoot])?.id : undefined;
1120
+ const scoped = projectId && scope?.runId ? " AND project_id = ? AND run_id = ?" : "";
1121
+ const params = projectId && scope?.runId ? [projectId, scope.runId] : [];
1122
+ const exact = context.db.get(`SELECT ${workColumns} FROM works WHERE work_id = ?${scoped}`, [id, ...params]);
1123
+ if (exact)
1124
+ return exact;
1125
+ if (!/^WRK-\d{3,}$/.test(id))
1126
+ throw new AppError("not_found", "Work is not registered in the current RUN", 1, { work_id: id });
1127
+ const matches = context.db.all(`SELECT ${workColumns} FROM works WHERE work_id LIKE ?${scoped} ORDER BY work_id`, [`${id}-%`, ...params]);
1128
+ if (matches.length !== 1)
1129
+ throw new AppError(matches.length ? "ambiguous_work_alias" : "not_found", matches.length ? "Short Work alias is ambiguous in the current RUN" : "Work is not registered in the current RUN", 1, { work_id: id, matches: matches.map((work) => work.work_id) });
1130
+ return matches[0];
1131
+ }
576
1132
  function requireRun(context, projectId, runId) { const run = context.db.get("SELECT r.id, r.run_root, r.workspace_root, p.root AS project_root FROM runs r JOIN projects p ON p.id = r.project_id WHERE r.project_id = ? AND r.id = ?", [projectId, runId]); if (!run?.run_root)
577
1133
  throw new AppError("runtime_missing", "RUN artifact root is unavailable", 1, { run_id: runId }); return run; }
578
1134
  function requireRunHome(run) { if (!run.run_root)
@@ -613,19 +1169,13 @@ function validateItem(value, requireExecutionContext = false) { if (!value || ty
613
1169
  throw new AppError("validation", "launch_policy must be reuse_allowed or fresh_agent_required", 2); if (item.result_schema !== undefined && (typeof item.result_schema !== "string" || !item.result_schema))
614
1170
  throw new AppError("validation", "result_schema must be a non-empty schema id", 2); const payload = code ? item : (item.payload && typeof item.payload === "object" && !Array.isArray(item.payload) ? item.payload : undefined); return { key: item.key, task: item.task, ...(Array.isArray(item.depends_on) ? { depends_on: item.depends_on } : {}), ...(typeof item.parent === "string" ? { parent: item.parent } : {}), ...(typeof item.launch_policy === "string" ? { launch_policy: item.launch_policy } : {}), ...(typeof item.result_schema === "string" ? { result_schema: item.result_schema } : {}), ...(payload ? { payload } : {}) }; }
615
1171
  function allowsEmptyRepairChecks(item) { const repair = item.repair; if (!repair || typeof repair !== "object" || Array.isArray(repair))
616
- return false; const value = repair; return typeof value.check_receipt_id === "string" || (Array.isArray(value.review_check_refs) && value.review_check_refs.some((ref) => typeof ref === "string")) || (Array.isArray(value.semantic_unresolved) && value.semantic_unresolved.some((item) => typeof item === "string")); }
617
- function readJson(file) { try {
618
- return JSON.parse(fs.readFileSync(path.resolve(file), "utf8"));
619
- }
620
- catch (error) {
621
- throw new AppError("validation", `Invalid JSON file: ${String(error)}`, 2, { file });
622
- } }
1172
+ return false; const value = repair; return typeof value.check_receipt_id === "string" || (Array.isArray(value.review_findings) && value.review_findings.some((finding) => typeof finding === "object" && finding !== null && Array.isArray(finding.check_refs) && finding.check_refs.some((ref) => typeof ref === "string"))) || (Array.isArray(value.semantic_unresolved) && value.semantic_unresolved.some((item) => typeof item === "string")); }
623
1173
  export function refreshRunWorkProjection(context, projectId, runId) { refreshRunSessionProjection(context, projectId, runId); const run = context.db.get("SELECT run_root FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]); if (run?.run_root) {
624
1174
  const obsolete = path.join(run.run_root, "work.json");
625
1175
  if (fs.existsSync(obsolete))
626
1176
  fs.rmSync(obsolete);
627
1177
  } }
628
- export function codeWorkGraph(context, projectId, runId) { const works = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? ORDER BY created_at, work_id`, [projectId, runId]).filter((work) => Boolean(codePacket(work))); const ready = works.filter((work) => isReady(context, work)); return { total: works.length, created: works.filter((work) => work.status === "created").length, running: works.filter((work) => work.status === "running").length, completed: works.filter((work) => work.status === "completed").length, failed: works.filter((work) => work.status === "failed").length, ready: ready.map((work) => ({ work_id: work.work_id, task: work.task, start_command: workStartCommand(context, work) })), blocked: works.filter((work) => work.status === "created" && !ready.includes(work)).map((work) => ({ work_id: work.work_id, depends_on: parseDependencies(work) })) }; }
1178
+ export function codeWorkGraph(context, projectId, runId) { const works = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? ORDER BY created_at, work_id`, [projectId, runId]).filter((work) => Boolean(codePacket(work))); const ready = works.filter((work) => isReady(context, work)); return { total: works.length, created: works.filter((work) => work.status === "created").length, running: works.filter((work) => work.status === "running").length, completed: works.filter((work) => work.status === "completed").length, failed: works.filter((work) => work.status === "failed").length, ready: ready.map((work) => ({ work_id: work.work_id, task: work.task, launch_policy: work.launch_policy, start_command: workStartCommand(context, work) })), blocked: works.filter((work) => work.status === "created" && !ready.includes(work)).map((work) => ({ work_id: work.work_id, depends_on: parseDependencies(work) })) }; }
629
1179
  function parsePayload(work) { if (!work.payload_json)
630
1180
  return null; try {
631
1181
  const value = JSON.parse(work.payload_json);
@@ -634,6 +1184,7 @@ function parsePayload(work) { if (!work.payload_json)
634
1184
  catch {
635
1185
  return null;
636
1186
  } }
1187
+ function uniqueChecks(checks) { return checks.filter((check, index) => checks.findIndex((candidate) => candidate.id === check.id) === index); }
637
1188
  function codePacket(work) { const value = parsePayload(work); if (value?.schema_id !== "dd-flow/code-work-packet@5")
638
1189
  return null; return value; }
639
1190
  function assertNoCycles(nodes) { const local = new Map(nodes.map((node) => [node.id, node.dependencies.filter((dependency) => nodes.some((candidate) => candidate.id === dependency))])); const active = new Set(); const done = new Set(); const visit = (id) => { if (active.has(id))