@deksden-com/dd-flow-cli 0.9.0-beta.10 → 0.9.0-beta.103
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +491 -0
- package/README.md +68 -0
- package/dist/build-info.json +8 -8
- package/dist/cli/command-inputs.js +305 -0
- package/dist/cli/help.js +89 -13
- package/dist/cli/hook-ingress.js +77 -0
- package/dist/cli/input-preparation.js +116 -0
- package/dist/cli/run-cli.js +1437 -384
- package/dist/cli.js +6 -2
- package/dist/harness-runtime/DD-ZCODE.md +99 -0
- package/dist/harness-runtime/bin/dd-agy.mjs +52 -0
- package/dist/harness-runtime/bin/dd-codex.mjs +25 -0
- package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
- package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
- package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
- package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
- package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
- package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
- package/dist/harness-runtime/lib/daemon-operations.mjs +226 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +502 -0
- package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.mjs +149 -0
- package/dist/harness-runtime/lib/dd-codex.mjs +563 -0
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
- package/dist/harness-runtime/lib/dd-droid.mjs +475 -0
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +387 -0
- package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +219 -0
- package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +640 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +978 -0
- package/dist/harness-runtime/lib/delegation-instructions.d.mts +10 -0
- package/dist/harness-runtime/lib/delegation-instructions.mjs +135 -0
- package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
- package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
- package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
- package/dist/harness-runtime/lib/managed-daemon.mjs +296 -0
- package/dist/harness-runtime/lib/model-observations.mjs +77 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +1 -0
- package/dist/harness-runtime/lib/native-hook-command.mjs +108 -0
- package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
- package/dist/harness-runtime/lib/operation-context.mjs +5 -0
- package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
- package/dist/harness-runtime/lib/process-json.mjs +71 -0
- package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
- package/dist/harness-runtime/lib/runner-events.mjs +200 -0
- package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
- package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
- package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
- package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
- package/dist/harness-runtime/lib/zcode-usage.mjs +54 -0
- package/dist/schemas/agent-profile.schema.json +1 -1
- package/dist/schemas/code-review-result.schema.json +1 -1
- package/dist/schemas/code-work-batch.schema.json +3 -3
- package/dist/schemas/code-work-result.schema.json +3 -3
- package/dist/schemas/plan-review-result.schema.json +2 -2
- package/dist/schemas/run-control-receipt.schema.json +99 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
- package/dist/services/canon.js +11 -8
- package/dist/services/cleanup.js +57 -13
- package/dist/services/cli-operation-classifier.js +22 -24
- package/dist/services/code-checks.js +583 -99
- package/dist/services/codex-hook-delivery.js +28 -0
- package/dist/services/command-context.js +80 -0
- package/dist/services/config.js +11 -8
- package/dist/services/continuation-outcome.js +20 -0
- package/dist/services/controller-fanout.js +165 -0
- package/dist/services/dashboard.js +103 -31
- package/dist/services/engines.js +121 -76
- package/dist/services/eval-snapshots.js +952 -83
- package/dist/services/execution-policy.js +170 -0
- package/dist/services/external-work-launch.js +165 -0
- package/dist/services/harness-adapter.js +147 -24
- package/dist/services/harness-config.js +2 -0
- package/dist/services/hooks.js +596 -300
- package/dist/services/lanes.js +61 -53
- package/dist/services/lifecycle-command.js +103 -17
- package/dist/services/lifecycle-contract.js +30 -0
- package/dist/services/lifecycle-invocations.js +1128 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-processes.js +283 -27
- package/dist/services/merge-queue.js +179 -104
- package/dist/services/merge-server.js +73 -28
- package/dist/services/migrations.js +14 -9
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +39 -0
- package/dist/services/plan-runtime.js +19 -8
- package/dist/services/plans.js +28 -25
- package/dist/services/projects.js +18 -5
- package/dist/services/prompts.js +25 -16
- package/dist/services/protocols.js +64 -20
- package/dist/services/recovery-observation-budget.js +61 -0
- package/dist/services/recovery-snapshot-database.js +107 -0
- package/dist/services/repair-intents.js +40 -0
- package/dist/services/review-copy.js +136 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +368 -0
- package/dist/services/run-control.js +876 -0
- package/dist/services/run-controller-adapter.js +231 -0
- package/dist/services/run-controller-capture.js +136 -0
- package/dist/services/run-controller-process.js +189 -0
- package/dist/services/run-controller-recovery.js +222 -0
- package/dist/services/run-controller-state.js +36 -0
- package/dist/services/run-controller.js +803 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +138 -0
- package/dist/services/run-observations.js +112 -0
- package/dist/services/run-recovery-runtime.js +69 -0
- package/dist/services/run-recovery.js +343 -0
- package/dist/services/runs.js +371 -74
- package/dist/services/runtime-budget.js +439 -0
- package/dist/services/runtime-command.js +43 -0
- package/dist/services/runtime-scope-capture.js +50 -0
- package/dist/services/runtime-scope-control.js +450 -0
- package/dist/services/runtime-scope-resume.js +565 -0
- package/dist/services/runtime-scope-stop.js +159 -0
- package/dist/services/runtime-scope-worker.js +243 -0
- package/dist/services/runtime-service.js +97 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/sessions.js +35 -69
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +44 -18
- package/dist/services/stage-lifecycle.js +99 -102
- package/dist/services/stage-pause.js +84 -55
- package/dist/services/stage-work-graph.js +35 -0
- package/dist/services/usage.js +37 -93
- package/dist/services/vnext-code-review.js +190 -80
- package/dist/services/vnext-code.js +283 -248
- package/dist/services/vnext-execution-profile.js +5 -3
- package/dist/services/vnext-fanout.js +172 -17
- package/dist/services/vnext-merge.js +296 -105
- package/dist/services/vnext-plan-review.js +141 -94
- package/dist/services/vnext-plan.js +142 -69
- package/dist/services/vnext-protocolize.js +132 -57
- package/dist/services/vnext-specify.js +95 -65
- package/dist/services/work-registry.js +891 -162
- package/dist/services/workspace-bootstrap.js +76 -0
- package/dist/services/workspace-files.js +83 -0
- package/dist/services/worktrees.js +88 -36
- package/dist/shared/entity-references.js +8 -0
- package/dist/shared/errors.js +12 -0
- package/dist/storage/database.js +459 -32
- package/dist/storage/paths.js +17 -4
- package/dist/storage/work-references.js +23 -0
- package/dist/storage/writer-contract.js +77 -0
- package/dist/storage/writer-migration.js +102 -0
- package/package.json +24 -13
- package/tools/repair-paused-run-status.mjs +59 -0
|
@@ -1,33 +1,125 @@
|
|
|
1
|
+
import { managedLifecycleCommand } from "./lifecycle-invocations.js";
|
|
2
|
+
import { bindStageWork, currentStageWorkIds, stageWorkIds } from "./stage-work-graph.js";
|
|
3
|
+
import { runtimeCommand } from "./runtime-command.js";
|
|
1
4
|
import crypto from "node:crypto";
|
|
2
5
|
import fs from "node:fs";
|
|
3
6
|
import path from "node:path";
|
|
4
7
|
import { AppError } from "../shared/errors.js";
|
|
5
|
-
import {
|
|
8
|
+
import { entityReferenceVariants, shortEntityReference } from "../shared/entity-references.js";
|
|
9
|
+
import { resolveWorkReference } from "../storage/work-references.js";
|
|
10
|
+
import { findRecentMatchingHookEvent, claimStageLifecycleHookEvent, claimStageStartHookEvent, claimWorkLifecycleHookEvent, claimWorkStartHookEvent, hookSessionIdentity, workStartMatchKey } from "./hooks.js";
|
|
6
11
|
import { validateSchema } from "./schema-validation.js";
|
|
7
12
|
import { resolveProjectRoot, resolveRunReferences } from "../storage/paths.js";
|
|
8
13
|
import { refreshRunSessionProjection } from "./run-projection.js";
|
|
9
|
-
import { readCodeCheckProfile, runCodeChecks, workspaceFingerprint } from "./code-checks.js";
|
|
14
|
+
import { ignoredWorkspacePaths, normalizeWorkspacePath, readCodeCheckProfile, runCodeChecks, validateFailedCheckRetry, workspaceFingerprint } from "./code-checks.js";
|
|
10
15
|
import { nextWorkId, nextWorkIds } from "./ids.js";
|
|
11
16
|
import { appendFlowRunTimelineEvent } from "./runs.js";
|
|
17
|
+
import { resolveStageTransition } from "./execution-policy.js";
|
|
18
|
+
import { appendAudit } from "./audit.js";
|
|
12
19
|
import { flowCommand } from "./stage-pause.js";
|
|
13
20
|
import { assertPortableArtifactRef } from "./portable-refs.js";
|
|
14
21
|
import { publicSessionIdentity } from "./session-identity.js";
|
|
22
|
+
import { activateRecoveryWork, assertRecoveryHookCurrent, assertRunMutationAllowed, assertWorkSettlementAllowed, recoveryGuard, recoveryPromptForWork, settleRecoveryWork } from "./run-recovery.js";
|
|
23
|
+
import { runControlDirective } from "./run-control.js";
|
|
24
|
+
import { prepareError, prepareJsonFile } from "../cli/input-preparation.js";
|
|
25
|
+
import { reviewEnvironmentAllowed, reviewExecutionCopyHash, reviewSourceHash, reviewSourcePaths } from "./review-copy.js";
|
|
15
26
|
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
27
|
export function ensureWorkRegistry(context) { context.db.exec("SELECT 1 FROM works LIMIT 1"); context.db.exec("SELECT 1 FROM work_sessions LIMIT 1"); }
|
|
28
|
+
function ownsPhysicalWorkSession(context, projectId, owner, identity) {
|
|
29
|
+
if (identity.sessionId !== owner.session_id)
|
|
30
|
+
return false;
|
|
31
|
+
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;
|
|
32
|
+
// Legacy non-daemon sessions remain usable. Once a physical daemon was
|
|
33
|
+
// captured, another process cannot inherit authority merely by resuming
|
|
34
|
+
// the same provider Session ID.
|
|
35
|
+
return !binding?.daemon_id || binding.daemon_id === identity.daemonId;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A Stage terminal command is allowed only from the Session that owns its
|
|
39
|
+
* running coordinator Work. A hook receipt proves the caller; a WorkSession
|
|
40
|
+
* proves the owner. Either fact alone is insufficient.
|
|
41
|
+
*/
|
|
42
|
+
export function assertStageLifecycleOwner(context, input) {
|
|
43
|
+
ensureWorkRegistry(context);
|
|
44
|
+
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
45
|
+
const project = context.db.get("SELECT id FROM projects WHERE root = ?", [projectRoot]);
|
|
46
|
+
if (!project)
|
|
47
|
+
throw new AppError("not_found", "Project is not registered", 1, { project_root: projectRoot });
|
|
48
|
+
requireRun(context, project.id, input.runId);
|
|
49
|
+
const scopedWork = input.workId ? requireWork(context, input.workId, { projectId: project.id, runId: input.runId }) : undefined;
|
|
50
|
+
let owner = context.db.get(`SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id
|
|
51
|
+
FROM work_sessions ws
|
|
52
|
+
JOIN works w ON w.work_id = ws.work_id
|
|
53
|
+
JOIN sessions s ON s.project_id = w.project_id AND s.session_id = ws.session_id
|
|
54
|
+
WHERE w.project_id = ? AND w.run_id = ? AND ws.status = 'running'
|
|
55
|
+
AND w.status IN ('running', 'paused') AND (w.parent_work_id IS NULL OR s.current_stage = ?)
|
|
56
|
+
${scopedWork ? "AND w.work_id = ?" : ""}
|
|
57
|
+
ORDER BY ws.created_at DESC LIMIT 1`, scopedWork ? [project.id, input.runId, input.stage, scopedWork.work_id] : [project.id, input.runId, input.stage]);
|
|
58
|
+
if (!owner && input.operation === "stage_finish" && ["code", "code-review"].includes(input.stage)) {
|
|
59
|
+
const row = context.db.get("SELECT run_root, index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
|
|
60
|
+
const index = row ? JSON.parse(row.index_json) : null;
|
|
61
|
+
const completed = index?.stage_runs.find(entry => entry.stage === input.stage && entry.status === "done");
|
|
62
|
+
if (row && completed && (index?.current_stage ?? index?.stage_runs.at(-1)?.stage) === input.stage)
|
|
63
|
+
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")]);
|
|
64
|
+
}
|
|
65
|
+
if (!owner)
|
|
66
|
+
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 } : {}) });
|
|
67
|
+
const identity = claimStageLifecycleHookEvent(context, {
|
|
68
|
+
projectId: project.id, ...(input.hookEventId ? { eventKey: input.hookEventId } : {}), operation: input.operation,
|
|
69
|
+
runId: input.runId, stage: input.stage, projectRoot, ...(input.operation === "stage_pause" ? { workId: owner.work_id } : {})
|
|
70
|
+
});
|
|
71
|
+
if (ownsPhysicalWorkSession(context, project.id, owner, identity))
|
|
72
|
+
return identity;
|
|
73
|
+
context.db.run("UPDATE hook_events SET status = 'rejected', claimed_at = ? WHERE id = ?", [context.now(), identity.hookEventId]);
|
|
74
|
+
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 };
|
|
75
|
+
appendFlowRunTimelineEvent(context, project.id, input.runId, { type: "lifecycle_caller_mismatch", ...payload });
|
|
76
|
+
appendAudit(context, { projectId: project.id, eventType: "stage.lifecycle_caller_rejected", payload });
|
|
77
|
+
throw new AppError("lifecycle_caller_mismatch", "Stage lifecycle command was issued by a Session that does not own the running Work", 1, payload);
|
|
78
|
+
}
|
|
79
|
+
/** A Work terminal command belongs to the Session that started that Work.
|
|
80
|
+
* Controllers can still use their explicit non-agent operations; they cannot
|
|
81
|
+
* borrow a native worker's authority by naming its Work id. */
|
|
82
|
+
export function assertWorkLifecycleOwner(context, input) {
|
|
83
|
+
ensureWorkRegistry(context);
|
|
84
|
+
const work = requireWork(context, input.workId);
|
|
85
|
+
const run = requireRun(context, work.project_id, work.run_id);
|
|
86
|
+
if (resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
|
|
87
|
+
throw new AppError("project_mismatch", "Work lifecycle project root does not match its RUN", 1, { work_id: work.work_id });
|
|
88
|
+
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]);
|
|
89
|
+
if (!owner)
|
|
90
|
+
throw new AppError("trusted_session_binding_required", "Work lifecycle command has no running Work/Session binding", 1, { work_id: work.work_id });
|
|
91
|
+
const identity = claimWorkLifecycleHookEvent(context, { projectId: work.project_id, ...(input.hookEventId ? { eventKey: input.hookEventId } : {}), operation: input.operation, workId: work.work_id, projectRoot: run.project_root });
|
|
92
|
+
if (ownsPhysicalWorkSession(context, work.project_id, owner, identity))
|
|
93
|
+
return identity;
|
|
94
|
+
context.db.run("UPDATE hook_events SET status = 'rejected', claimed_at = ? WHERE id = ?", [context.now(), identity.hookEventId]);
|
|
95
|
+
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 };
|
|
96
|
+
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_lifecycle_caller_mismatch", ...payload });
|
|
97
|
+
appendAudit(context, { projectId: work.project_id, eventType: "work.lifecycle_caller_rejected", payload });
|
|
98
|
+
throw new AppError("lifecycle_caller_mismatch", "Work lifecycle command was issued by a Session that does not own the running Work", 1, payload);
|
|
99
|
+
}
|
|
17
100
|
export function createChildWork(context, input) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
101
|
+
return context.db.writeTransaction(() => {
|
|
102
|
+
const parent = requireWork(context, input.parentWorkId);
|
|
103
|
+
assertRunMutationAllowed(context, parent.project_id, parent.run_id);
|
|
104
|
+
if (parent.status !== "running")
|
|
105
|
+
throw new AppError("invalid_work_state", "Child Work requires a running parent", 2, { parent_work_id: parent.work_id, status: parent.status });
|
|
106
|
+
const id = nextWorkId(context, parent.project_id, input.slug);
|
|
107
|
+
const now = context.now();
|
|
108
|
+
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]);
|
|
109
|
+
if (input.stage)
|
|
110
|
+
bindStageWork(context, { projectId: parent.project_id, runId: parent.run_id, workId: id, stage: input.stage });
|
|
111
|
+
refreshRunWorkProjection(context, parent.project_id, parent.run_id);
|
|
112
|
+
return requireWork(context, id);
|
|
113
|
+
});
|
|
26
114
|
}
|
|
27
115
|
/** Validate a proposed batch before PLAN accepts it, without registering Work. */
|
|
28
116
|
export function validateWorkBatchFile(file) {
|
|
29
|
-
|
|
30
|
-
|
|
117
|
+
validateWorkBatch(prepareJsonFile(file, "work batch").value);
|
|
118
|
+
}
|
|
119
|
+
/** Validate an already prepared batch without reopening its source file. */
|
|
120
|
+
export function validateWorkBatch(value) {
|
|
121
|
+
const parsed = value;
|
|
122
|
+
if (!parsed || !Array.isArray(parsed.works) || parsed.works.length === 0)
|
|
31
123
|
throw new AppError("validation", "work batch requires non-empty works", 2);
|
|
32
124
|
const items = parsed.works.map((item) => validateItem(item, true));
|
|
33
125
|
const keys = new Set(items.map((item) => item.key));
|
|
@@ -43,18 +135,29 @@ export function validateWorkBatchFile(file) {
|
|
|
43
135
|
assertNoCycles(items.map((item) => ({ id: item.key, dependencies: item.depends_on ?? [] })));
|
|
44
136
|
assertNoParentCycles(items.filter((item) => Boolean(item.parent)).map((item) => ({ id: item.key, parent: item.parent })));
|
|
45
137
|
}
|
|
46
|
-
export function
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
if (
|
|
50
|
-
throw new AppError("
|
|
51
|
-
const parsed =
|
|
52
|
-
if (!Array.isArray(parsed.works) || parsed.works.length === 0)
|
|
138
|
+
export function prepareWorkBatch(context, input) {
|
|
139
|
+
if (input.file !== undefined && input.value !== undefined)
|
|
140
|
+
throw new AppError("usage", "Work batch accepts either file or value, not both", 2);
|
|
141
|
+
if (input.file === undefined && input.value === undefined)
|
|
142
|
+
throw new AppError("usage", "Work batch input is required", 2);
|
|
143
|
+
const parsed = (input.file !== undefined ? prepareJsonFile(input.file, "work batch").value : input.value);
|
|
144
|
+
if (!parsed || !Array.isArray(parsed.works) || parsed.works.length === 0)
|
|
53
145
|
throw new AppError("validation", "work batch requires non-empty works", 2);
|
|
54
146
|
const items = parsed.works.map((item) => validateItem(item));
|
|
55
147
|
const keys = new Set(items.map((item) => item.key));
|
|
56
148
|
if (keys.size !== items.length)
|
|
57
149
|
throw new AppError("validation", "work batch keys must be unique", 2);
|
|
150
|
+
assertNoCycles(items.map(item => ({ id: item.key, dependencies: item.depends_on ?? [] })));
|
|
151
|
+
assertNoParentCycles(items.filter((item) => Boolean(item.parent)).map(item => ({ id: item.key, parent: item.parent })));
|
|
152
|
+
prepareBatchParent(context, input.parentWorkId, items);
|
|
153
|
+
return items;
|
|
154
|
+
}
|
|
155
|
+
function prepareBatchParent(context, parentWorkId, items) {
|
|
156
|
+
const keys = new Set(items.map(item => item.key));
|
|
157
|
+
const parent = requireWork(context, parentWorkId);
|
|
158
|
+
assertRunMutationAllowed(context, parent.project_id, parent.run_id);
|
|
159
|
+
if (parent.status !== "running")
|
|
160
|
+
throw new AppError("invalid_work_state", "Batch parent must be running", 2, { work_id: parent.work_id, status: parent.status });
|
|
58
161
|
const existing = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ?`, [parent.project_id, parent.run_id]);
|
|
59
162
|
const existingIds = new Set(existing.map((row) => row.work_id));
|
|
60
163
|
for (const item of items)
|
|
@@ -64,9 +167,15 @@ export function addWorkBatch(context, input) {
|
|
|
64
167
|
for (const item of items)
|
|
65
168
|
if (item.parent && !keys.has(item.parent) && !existingIds.has(item.parent))
|
|
66
169
|
throw new AppError("validation", "work parent is unknown", 2, { key: item.key, parent: item.parent });
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
170
|
+
return parent;
|
|
171
|
+
}
|
|
172
|
+
export function addWorkBatch(context, input) {
|
|
173
|
+
const items = input.prepared ?? prepareWorkBatch(context, input);
|
|
174
|
+
return context.db.writeTransaction(() => {
|
|
175
|
+
// Only mutable authority/references are rechecked under the write lock.
|
|
176
|
+
// Caller bytes were read once, before admission, and are never reopened.
|
|
177
|
+
const parent = prepareBatchParent(context, input.parentWorkId, items);
|
|
178
|
+
const now = context.now();
|
|
70
179
|
const allocated = nextWorkIds(context, parent.project_id, items.map((item) => item.key));
|
|
71
180
|
const ids = new Map(items.map((item, index) => [item.key, allocated[index]]));
|
|
72
181
|
const resolve = (value) => ids.get(value) ?? value;
|
|
@@ -76,16 +185,17 @@ export function addWorkBatch(context, input) {
|
|
|
76
185
|
for (const item of proposed)
|
|
77
186
|
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
187
|
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.
|
|
80
|
-
|
|
188
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [parent.project_id, parent.run_id]);
|
|
189
|
+
const stages = run ? (JSON.parse(run.index_json).stage_runs ?? []) : [];
|
|
190
|
+
const ownerStage = input.stage ?? [...stages].reverse().find(stage => stage.status === "running")?.stage;
|
|
191
|
+
for (const item of proposed) {
|
|
192
|
+
if (ownerStage)
|
|
193
|
+
bindStageWork(context, { projectId: parent.project_id, runId: parent.run_id, workId: item.id, stage: ownerStage, ...(input.cycle ? { cycle: input.cycle } : {}) });
|
|
81
194
|
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" });
|
|
195
|
+
}
|
|
82
196
|
refreshRunWorkProjection(context, parent.project_id, parent.run_id);
|
|
83
197
|
return { ok: true, work_ids: Object.fromEntries(ids) };
|
|
84
|
-
}
|
|
85
|
-
catch (error) {
|
|
86
|
-
context.db.exec("ROLLBACK");
|
|
87
|
-
throw error;
|
|
88
|
-
}
|
|
198
|
+
});
|
|
89
199
|
}
|
|
90
200
|
export function listWorks(context, input) {
|
|
91
201
|
ensureWorkRegistry(context);
|
|
@@ -105,8 +215,8 @@ export function listWorks(context, input) {
|
|
|
105
215
|
where.push("status = ?");
|
|
106
216
|
params.push(input.status);
|
|
107
217
|
}
|
|
108
|
-
const rows = context.db.all(`SELECT ${workColumns} FROM works WHERE ${where.join(" AND ")} ORDER BY created_at, work_id`, params);
|
|
109
|
-
const ready = (work) => isReady(context, work);
|
|
218
|
+
const rows = context.db.all(`SELECT ${workColumns} FROM works WHERE ${where.join(" AND ")} ORDER BY created_at, work_id`, params).filter(work => !input.workIds || input.workIds.has(work.work_id));
|
|
219
|
+
const ready = (work) => (input.workIds || currentStageWorkIds(context, work.project_id, work.run_id))?.has(work.work_id) !== false && isReady(context, work);
|
|
110
220
|
const filtered = input.ready ? rows.filter(ready) : rows;
|
|
111
221
|
return { works: filtered.slice(0, input.limit ?? filtered.length).map((work) => {
|
|
112
222
|
const isReadyNow = ready(work);
|
|
@@ -114,10 +224,137 @@ export function listWorks(context, input) {
|
|
|
114
224
|
}) };
|
|
115
225
|
}
|
|
116
226
|
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 }) } : {}) })) } }; }
|
|
227
|
+
function receiptIntentPath(resultPath, sessionId) {
|
|
228
|
+
return `${resultPath}.pending-${crypto.createHash("sha256").update(sessionId).digest("hex")}`;
|
|
229
|
+
}
|
|
230
|
+
function receiptFileHash(file) {
|
|
231
|
+
return fs.existsSync(file) ? crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex") : null;
|
|
232
|
+
}
|
|
233
|
+
function sha256(contents) { return crypto.createHash("sha256").update(contents).digest("hex"); }
|
|
234
|
+
function publishReceiptFile(file, contents) {
|
|
235
|
+
const temporary = `${file}.tmp-${crypto.randomUUID()}`;
|
|
236
|
+
try {
|
|
237
|
+
fs.writeFileSync(temporary, contents);
|
|
238
|
+
const descriptor = fs.openSync(temporary, "r");
|
|
239
|
+
try {
|
|
240
|
+
fs.fsyncSync(descriptor);
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
fs.closeSync(descriptor);
|
|
244
|
+
}
|
|
245
|
+
fs.renameSync(temporary, file);
|
|
246
|
+
const directory = fs.openSync(path.dirname(file), "r");
|
|
247
|
+
try {
|
|
248
|
+
fs.fsyncSync(directory);
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
fs.closeSync(directory);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
finally {
|
|
255
|
+
fs.rmSync(temporary, { force: true });
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** Rebuild prompt/context projections from a committed Work-start receipt. */
|
|
259
|
+
export function materializePendingWorkStarts(context, projectId, runId) {
|
|
260
|
+
const runHome = requireRunHome(requireRun(context, projectId, runId));
|
|
261
|
+
context.db.writeTransaction(() => {
|
|
262
|
+
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]);
|
|
263
|
+
for (const row of rows) {
|
|
264
|
+
// The same coordinator Session can move on to a different stage packet.
|
|
265
|
+
// A start receipt is not authority to overwrite that later packet.
|
|
266
|
+
let receipt;
|
|
267
|
+
try {
|
|
268
|
+
receipt = JSON.parse(row.start_receipt_json);
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
throw new AppError("work_start_receipt_invalid", "Committed Work start receipt is not valid JSON", 1, { work_id: row.work_id });
|
|
272
|
+
}
|
|
273
|
+
const originalPromptPath = path.join(runHome, "works", row.work_id, ...(receipt.generation && receipt.generation > 0 ? ["starts", row.id] : []), "prompt.md");
|
|
274
|
+
if (path.resolve(row.prompt_path) !== path.resolve(originalPromptPath))
|
|
275
|
+
continue;
|
|
276
|
+
if (receipt.version !== 1 || typeof receipt.prompt !== "string" || typeof receipt.context !== "string" || receipt.prompt_sha256 !== sha256(receipt.prompt) || receipt.context_sha256 !== sha256(receipt.context))
|
|
277
|
+
throw new AppError("work_start_receipt_invalid", "Committed Work start receipt does not match its retained bytes", 1, { work_id: row.work_id });
|
|
278
|
+
publishStartReceiptFile(row.prompt_path, receipt.prompt, String(receipt.prompt_sha256));
|
|
279
|
+
publishStartReceiptFile(path.join(path.dirname(row.prompt_path), "context.json"), receipt.context, String(receipt.context_sha256));
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
function publishStartReceiptFile(file, contents, expectedHash) {
|
|
284
|
+
const actual = receiptFileHash(file);
|
|
285
|
+
if (actual === expectedHash)
|
|
286
|
+
return;
|
|
287
|
+
if (actual !== null) {
|
|
288
|
+
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 });
|
|
289
|
+
}
|
|
290
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
291
|
+
publishReceiptFile(file, contents);
|
|
292
|
+
}
|
|
293
|
+
/** Replay only a prepared publication whose exact receipt was committed in SQLite. */
|
|
294
|
+
export function materializePendingWorkResults(context, projectId, runId) {
|
|
295
|
+
context.db.beginWriteTransaction();
|
|
296
|
+
try {
|
|
297
|
+
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]);
|
|
298
|
+
for (const row of rows) {
|
|
299
|
+
const intentPath = receiptIntentPath(row.result_path, row.id);
|
|
300
|
+
if (!fs.existsSync(intentPath))
|
|
301
|
+
continue;
|
|
302
|
+
const intent = JSON.parse(fs.readFileSync(intentPath, "utf8"));
|
|
303
|
+
const digest = crypto.createHash("sha256").update(row.result).digest("hex");
|
|
304
|
+
if (intent.work_id !== row.work_id || intent.work_session_id !== row.id || intent.status !== row.status || intent.result_sha256 !== digest)
|
|
305
|
+
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 });
|
|
306
|
+
const actual = receiptFileHash(row.result_path);
|
|
307
|
+
if (actual !== digest && actual !== intent.previous_sha256)
|
|
308
|
+
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 });
|
|
309
|
+
if (fs.existsSync(row.result_path)) {
|
|
310
|
+
const previous = fs.readFileSync(row.result_path);
|
|
311
|
+
if (!previous.equals(Buffer.from(row.result))) {
|
|
312
|
+
const retained = `${row.result_path}.conflict-${crypto.createHash("sha256").update(previous).digest("hex")}`;
|
|
313
|
+
try {
|
|
314
|
+
fs.writeFileSync(retained, previous, { flag: "wx", flush: true });
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
if (error.code !== "EEXIST" || !fs.readFileSync(retained).equals(previous))
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
publishReceiptFile(row.result_path, row.result);
|
|
323
|
+
fs.unlinkSync(intentPath);
|
|
324
|
+
}
|
|
325
|
+
context.db.exec("COMMIT");
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
context.db.exec("ROLLBACK");
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
117
332
|
export function mutateWorkDeps(context, input) {
|
|
333
|
+
if (input.action === "list") {
|
|
334
|
+
const { work, dependencies } = prepareWorkDeps(context, input);
|
|
335
|
+
return { work_id: work.work_id, depends_on: dependencies };
|
|
336
|
+
}
|
|
337
|
+
prepareWorkDeps(context, input);
|
|
338
|
+
return context.db.writeTransaction(() => {
|
|
339
|
+
const { work, dependencies } = prepareWorkDeps(context, input);
|
|
340
|
+
context.db.run("UPDATE works SET depends_on_json = ?, updated_at = ? WHERE work_id = ?", [JSON.stringify(dependencies), context.now(), work.work_id]);
|
|
341
|
+
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
342
|
+
return { work_id: work.work_id, depends_on: dependencies };
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
export function prepareWorkDeps(context, input) {
|
|
346
|
+
if (!["list", "add", "remove", "clear"].includes(input.action) || (input.on !== undefined && (!Array.isArray(input.on) || input.on.some(id => typeof id !== "string" || !id.trim()))))
|
|
347
|
+
throw new AppError("usage", "Invalid Work dependency action or --on target", 2);
|
|
348
|
+
if (["add", "remove"].includes(input.action) && !input.on?.length)
|
|
349
|
+
throw new AppError("usage", "Dependency add/remove requires at least one --on target", 2);
|
|
350
|
+
if (["list", "clear"].includes(input.action) && input.on?.length)
|
|
351
|
+
throw new AppError("usage", "Dependency list/clear does not accept --on targets", 2);
|
|
352
|
+
if (input.action === "list") {
|
|
353
|
+
const work = requireWork(context, input.workId);
|
|
354
|
+
return { work, dependencies: parseDependencies(work) };
|
|
355
|
+
}
|
|
118
356
|
const work = requireWork(context, input.workId);
|
|
119
|
-
|
|
120
|
-
return { work_id: work.work_id, depends_on: parseDependencies(work) };
|
|
357
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
121
358
|
if (work.status !== "created")
|
|
122
359
|
throw new AppError("invalid_work_state", "Dependencies change only while Work is created", 2);
|
|
123
360
|
const dependencies = new Set(parseDependencies(work));
|
|
@@ -125,8 +362,8 @@ export function mutateWorkDeps(context, input) {
|
|
|
125
362
|
dependencies.clear();
|
|
126
363
|
for (const id of input.on ?? []) {
|
|
127
364
|
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);
|
|
365
|
+
if (dependency.project_id !== work.project_id || dependency.run_id !== work.run_id)
|
|
366
|
+
throw new AppError("validation", "Dependencies must stay in one project and RUN", 2);
|
|
130
367
|
if (input.action === "add")
|
|
131
368
|
dependencies.add(dependency.work_id);
|
|
132
369
|
else
|
|
@@ -135,56 +372,78 @@ export function mutateWorkDeps(context, input) {
|
|
|
135
372
|
if (dependencies.has(work.work_id))
|
|
136
373
|
throw new AppError("validation", "Work cannot depend on itself", 2);
|
|
137
374
|
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
|
-
|
|
139
|
-
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
140
|
-
return { work_id: work.work_id, depends_on: [...dependencies] };
|
|
375
|
+
return { work, dependencies: [...dependencies] };
|
|
141
376
|
}
|
|
142
|
-
export function
|
|
143
|
-
|
|
144
|
-
|
|
377
|
+
export function prepareWorkDelete(context, id) {
|
|
378
|
+
const work = requireWork(context, id);
|
|
379
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
380
|
+
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}%`]))
|
|
381
|
+
throw new AppError("invalid_work_state", "Only an unstarted unreferenced Work may be deleted", 2);
|
|
382
|
+
return work;
|
|
383
|
+
}
|
|
384
|
+
export function deleteWork(context, id) {
|
|
385
|
+
prepareWorkDelete(context, id);
|
|
386
|
+
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 }; });
|
|
387
|
+
}
|
|
388
|
+
export function shortWorkId(id) { return shortEntityReference(id); }
|
|
145
389
|
/**
|
|
146
390
|
* Return the engine-bound command, never a PATH-dependent `dd-flow` token.
|
|
147
391
|
* Fan-out workers run in independently spawned harnesses where the adapter's
|
|
148
392
|
* PATH is not inherited; using the shared lifecycle command keeps them on the
|
|
149
393
|
* same captured runtime as their parent stage.
|
|
150
394
|
*/
|
|
151
|
-
export function workStartCommand(context, work) { const run = requireRun(context, work.project_id, work.run_id);
|
|
152
|
-
export function
|
|
395
|
+
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, runtimeCommand(context, ["work", "start", shortWorkId(work.work_id), "--project-root", run.project_root, ...(recovery ? ["--recovery-id", recovery.recovery_id] : []), "--json"])); }
|
|
396
|
+
export function assertWorkLaunchReady(context, id) {
|
|
153
397
|
ensureWorkRegistry(context);
|
|
154
398
|
const work = requireWork(context, id);
|
|
399
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
155
400
|
if (work.status !== "created")
|
|
156
401
|
throw new AppError("invalid_work_state", "Work is not created", 2, { work_id: id, status: work.status });
|
|
157
402
|
if (!isReady(context, work)) {
|
|
158
403
|
const blockers = readinessBlockers(context, work);
|
|
159
|
-
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) }));
|
|
404
|
+
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) => currentStageWorkIds(context, candidate.project_id, candidate.run_id)?.has(candidate.work_id) !== false && isReady(context, candidate)).map((candidate) => ({ work_id: candidate.work_id, start_command: workStartCommand(context, candidate) }));
|
|
160
405
|
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
406
|
}
|
|
407
|
+
if (parsePayload(work)?.read_only === true)
|
|
408
|
+
assertSharedReviewInput(context, work, requireRun(context, work.project_id, work.run_id));
|
|
409
|
+
return work;
|
|
410
|
+
}
|
|
411
|
+
export function startWork(context, id, input) {
|
|
412
|
+
if (input.hookEventId && !context.env.DD_FLOW_CURRENT_INVOCATION) {
|
|
413
|
+
const retainedWork = requireWork(context, id);
|
|
414
|
+
const retainedRun = requireRun(context, retainedWork.project_id, retainedWork.run_id);
|
|
415
|
+
if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(retainedRun.project_root))
|
|
416
|
+
throw new AppError("project_mismatch", "Work start belongs to another project", 1);
|
|
417
|
+
const reply = recoverCommittedWorkStart(context, null, input.hookEventId, recoveryGuard(context, retainedWork.project_id, retainedWork.run_id)?.generation ?? 0, retainedWork.work_id);
|
|
418
|
+
if (reply)
|
|
419
|
+
return reply;
|
|
420
|
+
}
|
|
421
|
+
const work = assertWorkLaunchReady(context, id);
|
|
162
422
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
163
423
|
if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
|
|
164
424
|
throw new AppError("project_mismatch", "work start project root does not match its RUN", 1, { work_id: id });
|
|
165
|
-
|
|
166
|
-
if (
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
}
|
|
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 });
|
|
425
|
+
const recoveryId = recoveryGuard(context, work.project_id, work.run_id)?.recovery_id;
|
|
426
|
+
if (input.recoveryId !== recoveryId)
|
|
427
|
+
throw new AppError("run_recovery_generation_stale", "Work launch must use the exact current recovery packet", 1, { work_id: id, recovery_id: recoveryId ?? null });
|
|
428
|
+
const hookEventId = input.hookEventId ?? findRecentMatchingHookEvent(context, { projectId: work.project_id, matchKey: entityReferenceVariants(work.work_id).map((reference) => workStartMatchKey(reference, run.project_root, recoveryId)), errorCode: "trusted_session_binding_required", operation: "work start" }).eventKey;
|
|
429
|
+
const eventKey = hookEventId;
|
|
430
|
+
const started = startBoundWork(context, work, run, () => claimWorkStartHookEvent(context, { projectId: work.project_id, eventKey, workId: work.work_id, projectRoot: run.project_root, ...(recoveryId ? { recoveryId } : {}) }), eventKey);
|
|
431
|
+
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_started", work_id: work.work_id, work_session_id: started.work_session_id });
|
|
177
432
|
return started;
|
|
178
433
|
}
|
|
179
434
|
/** Binds the already-running coordinator of a stage to its trusted hook Session. */
|
|
180
435
|
export function bindRunningWorkSession(context, input) {
|
|
181
436
|
const work = requireWork(context, input.workId);
|
|
437
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
182
438
|
if (work.status !== "running")
|
|
183
439
|
throw new AppError("invalid_work_state", "Stage coordinator Work must be running", 1, { work_id: work.work_id, status: work.status });
|
|
184
440
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
185
441
|
const identity = hookSessionIdentity(context, work.project_id, input.hookEventId);
|
|
442
|
+
assertRecoveryHookCurrent(context, work.project_id, work.run_id, identity);
|
|
186
443
|
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
444
|
if (active) {
|
|
445
|
+
if (active.session_id === identity.sessionId && !ownsPhysicalWorkSession(context, work.project_id, active, identity))
|
|
446
|
+
throw new AppError("handoff_session_mismatch", "The active Work belongs to another physical daemon", 1, { work_id: work.work_id });
|
|
188
447
|
if (active.session_id !== identity.sessionId) {
|
|
189
448
|
// A frozen `new_session` policy may transfer the same coordinator Work
|
|
190
449
|
// only to its next stage. Repeating the same stage from another Session
|
|
@@ -193,7 +452,7 @@ export function bindRunningWorkSession(context, input) {
|
|
|
193
452
|
throw new AppError("handoff_session_mismatch", "The active Work is already bound to a different Session", 1, { work_id: work.work_id });
|
|
194
453
|
const now = context.now();
|
|
195
454
|
const id = `WS-${crypto.randomUUID()}`;
|
|
196
|
-
context.db.
|
|
455
|
+
context.db.beginWriteTransaction();
|
|
197
456
|
try {
|
|
198
457
|
context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = ?, updated_at = ? WHERE id = ?", [now, now, active.id]);
|
|
199
458
|
const stillRunning = context.db.get("SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running' LIMIT 1", [active.session_id]);
|
|
@@ -215,7 +474,7 @@ export function bindRunningWorkSession(context, input) {
|
|
|
215
474
|
}
|
|
216
475
|
const now = context.now();
|
|
217
476
|
const id = `WS-${crypto.randomUUID()}`;
|
|
218
|
-
context.db.
|
|
477
|
+
context.db.beginWriteTransaction();
|
|
219
478
|
try {
|
|
220
479
|
bindSession(context, work, run, identity, now);
|
|
221
480
|
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 +490,22 @@ export function bindRunningWorkSession(context, input) {
|
|
|
231
490
|
/** A stage coordinator is launched by `stage start`, not by an invented nested `work start`. */
|
|
232
491
|
export function bindStageCoordinatorWork(context, input) {
|
|
233
492
|
const work = requireWork(context, input.workId);
|
|
493
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
234
494
|
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
495
|
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
|
|
496
|
+
const profile = snapshot.execution_profile;
|
|
497
|
+
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]);
|
|
498
|
+
let sessionMode = profile?.settings.stage_session_mode ?? "same_session";
|
|
499
|
+
if (profile?.settings.execution) {
|
|
500
|
+
if (!profile.agent_profiles)
|
|
501
|
+
throw new AppError("execution_profile_not_frozen", "Stage handoff requires frozen RUN profiles", 1);
|
|
502
|
+
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;
|
|
503
|
+
}
|
|
504
|
+
const identity = hookSessionIdentity(context, work.project_id, input.hookEventId);
|
|
505
|
+
if (previous?.current_stage && previous.current_stage !== input.stage && sessionMode === "new_session" && previous.session_id === identity.sessionId)
|
|
506
|
+
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 });
|
|
507
|
+
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 } : {}) });
|
|
508
|
+
const binding = bindRunningWorkSession(context, { ...input, allowStageHandoff: sessionMode === "new_session" });
|
|
238
509
|
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
510
|
refreshRunSessionProjection(context, work.project_id, work.run_id);
|
|
240
511
|
return binding;
|
|
@@ -242,95 +513,471 @@ export function bindStageCoordinatorWork(context, input) {
|
|
|
242
513
|
/** Starts a created coordinator Work from its trusted `stage start` event. */
|
|
243
514
|
export function startStageCoordinatorWork(context, input) {
|
|
244
515
|
const work = requireWork(context, input.workId);
|
|
516
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
245
517
|
if (work.status !== "created")
|
|
246
518
|
throw new AppError("invalid_work_state", "Stage coordinator Work is not created", 2, { work_id: work.work_id, status: work.status });
|
|
247
519
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
248
520
|
if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
|
|
249
521
|
throw new AppError("project_mismatch", "stage coordinator project root does not match its RUN", 1, { work_id: work.work_id });
|
|
250
|
-
const
|
|
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]);
|
|
522
|
+
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
523
|
refreshRunSessionProjection(context, work.project_id, work.run_id);
|
|
255
524
|
return binding;
|
|
256
525
|
}
|
|
257
|
-
/**
|
|
258
|
-
export function startBoundWork(context, work, run,
|
|
259
|
-
|
|
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()}`;
|
|
526
|
+
/** Claim, command authority and binding commit together; only packet projection follows. */
|
|
527
|
+
export function startBoundWork(context, work, run, claimIdentity, hookEventId, stage) {
|
|
528
|
+
const generation = assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
263
529
|
const directory = path.join(requireRunHome(run), "works", work.work_id);
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
const
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
const
|
|
271
|
-
const
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
fs.writeFileSync(promptCandidate, prompt);
|
|
277
|
-
fs.writeFileSync(contextCandidate, `${JSON.stringify(workContext, null, 2)}\n`);
|
|
278
|
-
context.db.exec("BEGIN IMMEDIATE");
|
|
530
|
+
const linkId = `WS-${crypto.randomUUID()}`;
|
|
531
|
+
// Recovery can reopen the same Work without retiring its historical packet.
|
|
532
|
+
// Give each new-generation start its own immutable publication destination.
|
|
533
|
+
const packetDirectory = generation > 0 ? path.join(directory, "starts", linkId) : directory;
|
|
534
|
+
const promptPath = path.join(packetDirectory, "prompt.md"), resultPath = path.join(directory, "result.json");
|
|
535
|
+
// The first reviewer freezes shared inputs in the same transaction as its claim.
|
|
536
|
+
const readOnly = parsePayload(work)?.read_only === true;
|
|
537
|
+
const workerRun = readOnly && context.env.DD_FLOW_READ_ONLY_WORKSPACE
|
|
538
|
+
? { ...run, workspace_root: path.resolve(context.env.DD_FLOW_READ_ONLY_WORKSPACE) }
|
|
539
|
+
: run;
|
|
540
|
+
let fingerprint;
|
|
541
|
+
let binding;
|
|
279
542
|
try {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
context
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
543
|
+
binding = context.db.writeTransaction(() => {
|
|
544
|
+
const current = requireWork(context, work.work_id);
|
|
545
|
+
assertRunMutationAllowed(context, current.project_id, current.run_id, generation);
|
|
546
|
+
if (current.status !== "created")
|
|
547
|
+
throw new AppError("conflict", "Work was claimed concurrently", 1, { work_id: current.work_id, status: current.status });
|
|
548
|
+
if (Object.keys(current).some(key => current[key] !== work[key]))
|
|
549
|
+
throw new AppError("work_not_ready", "Work inputs changed while preparing its start packet", 2, { work_id: current.work_id });
|
|
550
|
+
if (!isReady(context, current))
|
|
551
|
+
throw new AppError("work_not_ready", "Work dependencies are not ready", 2, { work_id: current.work_id, blockers: readinessBlockers(context, current) });
|
|
552
|
+
if (fs.existsSync(path.join(directory, ".retry.json")))
|
|
553
|
+
throw new AppError("work_retry_incomplete", "Complete the interrupted Work retry before starting its next attempt", 1, { work_id: work.work_id });
|
|
554
|
+
const identity = claimIdentity();
|
|
555
|
+
assertRecoveryHookCurrent(context, current.project_id, current.run_id, identity);
|
|
556
|
+
if (readOnly && !context.env.DD_FLOW_READ_ONLY_WORKSPACE
|
|
557
|
+
&& context.db.get("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'work_launches'")
|
|
558
|
+
&& context.db.get("SELECT 1 FROM work_launches WHERE work_id = ? AND status IN ('launching','start_requested')", [current.work_id]))
|
|
559
|
+
throw new AppError("read_only_workspace_unbound", "External reviewer did not inherit its qualified execution workspace", 1, { work_id: current.work_id });
|
|
560
|
+
const reviewInput = readOnly ? assertSharedReviewInput(context, current, run, generation) : null;
|
|
561
|
+
const reviewPaths = reviewInput?.run_inputs.filter(item => item.root === "workspace").map(item => item.path) ?? [];
|
|
562
|
+
const reviewCopy = readOnly && context.env.DD_FLOW_READ_ONLY_WORKSPACE ? boundReviewCopy(context, current, run, identity, context.env.DD_FLOW_READ_ONLY_WORKSPACE, reviewPaths) : null;
|
|
563
|
+
const dependencyResults = parseDependencies(current).map(dependency => context.db.get("SELECT work_id, result FROM works WHERE work_id = ?", [dependency])).filter(Boolean);
|
|
564
|
+
const recovery = recoveryPromptForWork(context, current.work_id);
|
|
565
|
+
let prompt = renderWorkerPrompt(context, current, workerRun, dependencyResults);
|
|
566
|
+
if (recovery)
|
|
567
|
+
prompt = `${recoveryPrompt(recovery)}\n\n${prompt}`;
|
|
568
|
+
if (readOnly)
|
|
569
|
+
fingerprint = reviewInput?.source_sha256 ?? reviewInput?.workspace_fingerprint ?? legacyReviewFingerprint(current, run) ?? workspaceFingerprint(run.workspace_root);
|
|
570
|
+
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: workerRun.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, ...(reviewInput ? { review_input: reviewInput } : {}), ...(reviewCopy ? { review_copy: reviewCopy } : {}) } : {}) };
|
|
571
|
+
const contextBytes = `${JSON.stringify(workContext, null, 2)}\n`;
|
|
572
|
+
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 } } };
|
|
573
|
+
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 });
|
|
574
|
+
const now = context.now();
|
|
575
|
+
bindSession(context, current, run, identity, now);
|
|
576
|
+
if (current.parent_work_id && current.launch_policy === "reuse_allowed")
|
|
577
|
+
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]);
|
|
578
|
+
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)
|
|
579
|
+
throw new AppError("conflict", "Work was claimed concurrently", 1, { work_id: current.work_id });
|
|
580
|
+
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]);
|
|
581
|
+
if (stage)
|
|
582
|
+
context.db.run("UPDATE sessions SET current_stage = ?, updated_at = ? WHERE project_id = ? AND session_id = ?", [stage, now, current.project_id, identity.sessionId]);
|
|
583
|
+
if (recovery)
|
|
584
|
+
activateRecoveryWork(context, current.work_id);
|
|
585
|
+
return response;
|
|
586
|
+
});
|
|
290
587
|
}
|
|
291
588
|
catch (error) {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
589
|
+
// This transaction publishes only SQL authority, never files or provider calls.
|
|
590
|
+
if (error instanceof AppError && error.code === "storage_write_failed" && error.details.transaction_rolled_back === true)
|
|
591
|
+
error.details.effect = "no_effect";
|
|
592
|
+
if (error instanceof AppError && error.details.effect === "no_effect" && !context.env.DD_FLOW_CURRENT_INVOCATION) {
|
|
593
|
+
let retry = false;
|
|
594
|
+
try {
|
|
595
|
+
retry = context.db.writeTransaction(() => {
|
|
596
|
+
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]))
|
|
597
|
+
return false;
|
|
598
|
+
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;
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
catch (persistence) {
|
|
602
|
+
error.details.retry_persistence_error = String(persistence);
|
|
603
|
+
}
|
|
604
|
+
if (retry)
|
|
605
|
+
return startBoundWork(context, work, run, claimIdentity, hookEventId, stage);
|
|
606
|
+
}
|
|
295
607
|
throw error;
|
|
296
608
|
}
|
|
297
|
-
|
|
298
|
-
|
|
609
|
+
try {
|
|
610
|
+
materializePendingWorkStarts(context, work.project_id, work.run_id);
|
|
611
|
+
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
612
|
+
}
|
|
613
|
+
catch (error) {
|
|
614
|
+
if (error instanceof AppError) {
|
|
615
|
+
error.details.effect = "committed";
|
|
616
|
+
throw error;
|
|
617
|
+
}
|
|
618
|
+
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 } });
|
|
619
|
+
}
|
|
620
|
+
return binding;
|
|
299
621
|
}
|
|
300
|
-
|
|
622
|
+
/** Read the exact committed reply, never bind another Session or regenerate a packet. */
|
|
623
|
+
export function recoverCommittedWorkStart(context, invocationId, eventKey, generation, workId) {
|
|
624
|
+
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]);
|
|
625
|
+
if (!row)
|
|
626
|
+
return undefined;
|
|
627
|
+
const receipt = JSON.parse(row.start_receipt_json);
|
|
628
|
+
if (receipt.generation !== generation || !receipt.response || receipt.response_sha256 !== sha256(JSON.stringify(receipt.response)))
|
|
629
|
+
throw new AppError("work_start_receipt_invalid", "Committed reply identity or checksum differs", 1, { invocation_id: invocationId });
|
|
630
|
+
assertRunMutationAllowed(context, row.project_id, row.run_id, generation);
|
|
631
|
+
materializePendingWorkStarts(context, row.project_id, row.run_id);
|
|
632
|
+
return receipt.response;
|
|
633
|
+
}
|
|
634
|
+
/** Root coordinators have no worker checks: settle them inside the stage transaction. */
|
|
635
|
+
export function finishStageCoordinatorWork(context, id, result) {
|
|
636
|
+
const work = requireWork(context, id);
|
|
637
|
+
if (work.parent_work_id !== null || codePacket(work) || parsePayload(work)?.read_only)
|
|
638
|
+
throw new AppError("invalid_work_state", "Stage settlement requires a root coordinator", 2);
|
|
639
|
+
const run = requireRun(context, work.project_id, work.run_id);
|
|
640
|
+
const link = context.db.get("SELECT * FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [id]);
|
|
641
|
+
if (!link)
|
|
642
|
+
throw new AppError("runtime_missing", "Coordinator has no open Work/Session link", 1);
|
|
643
|
+
validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link.result_path);
|
|
644
|
+
finishFanInWork(context, id, result);
|
|
645
|
+
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]);
|
|
646
|
+
settleRecoveryWork(context, id, "completed");
|
|
647
|
+
}
|
|
648
|
+
export function finishWork(context, id, result, progress, retry) { return settle(context, id, "completed", result, progress, retry); }
|
|
301
649
|
/** 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")
|
|
650
|
+
export function finishFanInWork(context, id, result) { const work = requireWork(context, id); assertRunMutationAllowed(context, work.project_id, work.run_id); if (work.status !== "running")
|
|
303
651
|
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
652
|
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
653
|
export function failWork(context, id, reason) { return settle(context, id, "failed", reason); }
|
|
306
654
|
export function cancelWork(context, id, reason) { return settle(context, id, "cancelled", reason); }
|
|
307
|
-
export function
|
|
308
|
-
|
|
309
|
-
|
|
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) {
|
|
655
|
+
export function prepareWorkSettlement(context, id, status, result) {
|
|
656
|
+
if (status !== "completed" && (typeof result !== "string" || !result.trim()))
|
|
657
|
+
throw new AppError("usage", "Work settlement requires a nonempty --reason", 2);
|
|
314
658
|
const work = requireWork(context, id);
|
|
315
|
-
|
|
659
|
+
assertWorkSettlementAllowed(context, work.project_id, work.run_id, work.work_id);
|
|
316
660
|
if (work.status !== "running" && !(status === "cancelled" && work.status === "created"))
|
|
317
661
|
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", [
|
|
319
|
-
throw new AppError("active_child_work", "Work cannot complete while a child Work is active", 2, { work_id:
|
|
662
|
+
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]))
|
|
663
|
+
throw new AppError("active_child_work", "Work cannot complete while a child Work is active", 2, { work_id: work.work_id });
|
|
320
664
|
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", [
|
|
665
|
+
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
666
|
if (work.status === "running" && !link)
|
|
323
|
-
throw new AppError("runtime_missing", "Running Work has no open Work/Session link", 1, { work_id:
|
|
667
|
+
throw new AppError("runtime_missing", "Running Work has no open Work/Session link", 1, { work_id: work.work_id });
|
|
668
|
+
return { work, run, link };
|
|
669
|
+
}
|
|
670
|
+
export function prepareWorkRetry(context, id, reason) {
|
|
671
|
+
if (typeof reason !== "string" || !reason.trim())
|
|
672
|
+
throw new AppError("usage", "Work retry requires a nonempty --reason", 2);
|
|
673
|
+
const work = requireWork(context, id);
|
|
674
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
675
|
+
const run = requireRun(context, work.project_id, work.run_id);
|
|
676
|
+
const directory = path.join(requireRunHome(run), "works", work.work_id);
|
|
677
|
+
const journal = path.join(directory, ".retry.json");
|
|
678
|
+
let pending = null;
|
|
679
|
+
if (fs.existsSync(journal)) {
|
|
680
|
+
let value;
|
|
681
|
+
try {
|
|
682
|
+
value = JSON.parse(fs.readFileSync(journal, "utf8"));
|
|
683
|
+
}
|
|
684
|
+
catch (error) {
|
|
685
|
+
if (!(error instanceof SyntaxError))
|
|
686
|
+
throw error;
|
|
687
|
+
throw new AppError("work_retry_invalid", "Retry journal is not valid JSON", 1);
|
|
688
|
+
}
|
|
689
|
+
const item = value;
|
|
690
|
+
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)))
|
|
691
|
+
throw new AppError("work_retry_invalid", "Retry journal does not identify this Work", 1);
|
|
692
|
+
pending = item;
|
|
693
|
+
}
|
|
694
|
+
if (work.status !== "failed" && !(pending && work.status === "created"))
|
|
695
|
+
throw new AppError("invalid_work_state", "Only failed Work may be retried", 2);
|
|
696
|
+
const attempts = path.join(directory, "attempts");
|
|
697
|
+
let number = 1;
|
|
698
|
+
while (fs.existsSync(path.join(attempts, `ATT-${String(number).padStart(3, "0")}`)))
|
|
699
|
+
number += 1;
|
|
700
|
+
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") };
|
|
701
|
+
const archive = path.join(attempts, prepared.archive);
|
|
702
|
+
if (work.status === "failed") {
|
|
703
|
+
if (prepared.result_sha256 !== (work.result === null ? null : crypto.createHash("sha256").update(work.result).digest("hex")))
|
|
704
|
+
throw new AppError("work_retry_conflict", "Failed Work receipt changed during retry", 1);
|
|
705
|
+
const receipt = path.join(archive, "accepted-receipt.json");
|
|
706
|
+
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 }))
|
|
707
|
+
throw new AppError("work_retry_conflict", "Archived receipt differs from failed Work", 1);
|
|
708
|
+
for (const file of prepared.entries) {
|
|
709
|
+
const source = path.join(directory, file), target = path.join(archive, file);
|
|
710
|
+
if (fs.existsSync(source) && fs.existsSync(target))
|
|
711
|
+
throw new AppError("archive_conflict", "Both live and archived Work artifact exist; preserve both", 1, { source, target });
|
|
712
|
+
if (!fs.existsSync(source) && !fs.existsSync(target))
|
|
713
|
+
throw new AppError("archive_artifact_missing", "Work artifact is absent from both retry locations", 1, { source, target });
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return { work, run, directory, journal, pending, prepared, archive };
|
|
717
|
+
}
|
|
718
|
+
export function retryWork(context, id, reason) {
|
|
719
|
+
const { work, run, directory, journal } = prepareWorkRetry(context, id, reason);
|
|
720
|
+
let archive = "";
|
|
721
|
+
context.db.beginWriteTransaction();
|
|
722
|
+
try {
|
|
723
|
+
const { work: current, pending, prepared, archive: targetArchive } = prepareWorkRetry(context, work.work_id, reason);
|
|
724
|
+
archive = targetArchive;
|
|
725
|
+
if (current.status === "failed") {
|
|
726
|
+
if (prepared.result_sha256 !== (current.result === null ? null : crypto.createHash("sha256").update(current.result).digest("hex")))
|
|
727
|
+
throw new AppError("work_retry_conflict", "Failed Work receipt changed during retry", 1);
|
|
728
|
+
fs.mkdirSync(archive, { recursive: true });
|
|
729
|
+
if (!pending)
|
|
730
|
+
publishReceiptFile(journal, JSON.stringify(prepared));
|
|
731
|
+
const receipt = path.join(archive, "accepted-receipt.json");
|
|
732
|
+
const receiptBytes = JSON.stringify({ work_id: current.work_id, status: current.status, result: current.result, result_sha256: prepared.result_sha256 });
|
|
733
|
+
if (fs.existsSync(receipt) && fs.readFileSync(receipt, "utf8") !== receiptBytes)
|
|
734
|
+
throw new AppError("work_retry_conflict", "Archived receipt differs from failed Work", 1);
|
|
735
|
+
if (!fs.existsSync(receipt))
|
|
736
|
+
publishReceiptFile(receipt, receiptBytes);
|
|
737
|
+
for (const file of prepared.entries) {
|
|
738
|
+
const source = path.join(directory, file), target = path.join(archive, file);
|
|
739
|
+
if (fs.existsSync(source)) {
|
|
740
|
+
if (fs.existsSync(target))
|
|
741
|
+
throw new AppError("archive_conflict", "Both live and archived Work artifact exist; preserve both", 1, { source, target });
|
|
742
|
+
fs.renameSync(source, target);
|
|
743
|
+
}
|
|
744
|
+
else if (!fs.existsSync(target))
|
|
745
|
+
throw new AppError("archive_artifact_missing", "Work artifact is absent from both retry locations", 1, { source, target });
|
|
746
|
+
}
|
|
747
|
+
for (const folder of [archive, directory]) {
|
|
748
|
+
const descriptor = fs.openSync(folder, "r");
|
|
749
|
+
try {
|
|
750
|
+
fs.fsyncSync(descriptor);
|
|
751
|
+
}
|
|
752
|
+
finally {
|
|
753
|
+
fs.closeSync(descriptor);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
for (const column of ["prompt_path", "result_path"]) {
|
|
757
|
+
const file = column === "prompt_path" ? "prompt.md" : "result.json";
|
|
758
|
+
context.db.run(`UPDATE work_sessions SET ${column} = ? WHERE work_id = ? AND ${column} = ?`, [path.join(archive, file), work.work_id, path.join(directory, file)]);
|
|
759
|
+
}
|
|
760
|
+
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]);
|
|
761
|
+
}
|
|
762
|
+
context.db.exec("COMMIT");
|
|
763
|
+
}
|
|
764
|
+
catch (error) {
|
|
765
|
+
context.db.exec("ROLLBACK");
|
|
766
|
+
throw error;
|
|
767
|
+
}
|
|
768
|
+
fs.rmSync(journal, { force: true });
|
|
769
|
+
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
770
|
+
return { ok: true, work_id: work.work_id, archived_attempt: path.relative(requireRunHome(run), archive).split(path.sep).join("/"), reason };
|
|
771
|
+
}
|
|
772
|
+
export function reviewSourceInputs(context, workId) {
|
|
773
|
+
const work = requireWork(context, workId);
|
|
774
|
+
const input = assertSharedReviewInput(context, work, requireRun(context, work.project_id, work.run_id));
|
|
775
|
+
return input?.run_inputs.filter(item => item.root === "workspace").map(item => item.path) ?? [];
|
|
776
|
+
}
|
|
777
|
+
function reviewInputPath(root, relative) {
|
|
778
|
+
const resolved = path.resolve(root, relative);
|
|
779
|
+
const inside = path.relative(root, resolved);
|
|
780
|
+
if (!relative || path.isAbsolute(relative) || inside === ".." || inside.startsWith(`..${path.sep}`))
|
|
781
|
+
throw new AppError("review_input_invalid", "Review input path escapes its declared root", 1, { path: relative });
|
|
782
|
+
if (fs.existsSync(resolved)) {
|
|
783
|
+
const canonicalInside = path.relative(fs.realpathSync(root), fs.realpathSync(resolved));
|
|
784
|
+
if (canonicalInside === ".." || canonicalInside.startsWith(`..${path.sep}`))
|
|
785
|
+
throw new AppError("review_input_invalid", "Review input symlink escapes its declared root", 1, { path: relative });
|
|
786
|
+
}
|
|
787
|
+
return resolved;
|
|
788
|
+
}
|
|
789
|
+
function boundReviewCopy(context, work, run, identity, requested, reviewPaths) {
|
|
790
|
+
const launch = context.db.get("SELECT provider_session_id, profile_json FROM work_launches WHERE work_id = ? AND status IN ('launching','start_requested')", [work.work_id]);
|
|
791
|
+
const metadata = launch ? JSON.parse(launch.profile_json) : null;
|
|
792
|
+
const copy = metadata?.review_copy;
|
|
793
|
+
if (!copy?.root || !copy.sha256 || !copy.source_sha256 || launch?.provider_session_id !== identity.providerSessionId)
|
|
794
|
+
throw new AppError("read_only_workspace_unbound", "Read-only execution copy has no matching trusted launch", 1, { work_id: work.work_id });
|
|
795
|
+
const expected = reviewInputPath(requireRunHome(run), copy.root);
|
|
796
|
+
if (path.resolve(requested) !== expected)
|
|
797
|
+
throw new AppError("read_only_workspace_unbound", "Read-only execution path differs from the trusted launch", 1, { work_id: work.work_id });
|
|
798
|
+
const base = reviewWorkspaceBase(context, work);
|
|
799
|
+
if (reviewSourceHash(run.workspace_root, reviewPaths, base) !== copy.source_sha256)
|
|
800
|
+
throw new AppError("read_only_input_changed", "Authoritative review workspace changed after the execution copy was made", 2, { work_id: work.work_id });
|
|
801
|
+
const actual = reviewExecutionCopyHash(expected, run.workspace_root, true, reviewPaths, base);
|
|
802
|
+
if (actual !== copy.sha256)
|
|
803
|
+
throw new AppError("read_only_input_changed", "Read-only execution copy changed before Work start", 2, { work_id: work.work_id, expected: copy.sha256, current: actual });
|
|
804
|
+
return { root: copy.root, sha256: copy.sha256, source_sha256: copy.source_sha256 };
|
|
805
|
+
}
|
|
806
|
+
function assertReviewCopyUnchanged(context, work, run, link) {
|
|
807
|
+
if (!link)
|
|
808
|
+
return;
|
|
809
|
+
const row = context.db.get("SELECT start_receipt_json FROM work_sessions WHERE id = ?", [link.id]);
|
|
810
|
+
const external = context.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'work_launches'")
|
|
811
|
+
? context.db.get("SELECT 1 FROM work_launches WHERE work_id = ? LIMIT 1", [work.work_id]) : null;
|
|
812
|
+
if (!row?.start_receipt_json) {
|
|
813
|
+
if (external)
|
|
814
|
+
throw new AppError("read_only_workspace_unbound", "External review has no committed start receipt", 1, { work_id: work.work_id });
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
let copy;
|
|
818
|
+
let reviewPaths = [];
|
|
819
|
+
try {
|
|
820
|
+
const receipt = JSON.parse(row.start_receipt_json);
|
|
821
|
+
const retained = receipt.context ? JSON.parse(receipt.context) : null;
|
|
822
|
+
copy = retained?.review_copy;
|
|
823
|
+
reviewPaths = retained?.review_input?.run_inputs.filter(item => item.root === "workspace").map(item => item.path) ?? [];
|
|
824
|
+
}
|
|
825
|
+
catch {
|
|
826
|
+
throw new AppError("read_only_workspace_unbound", "Review start receipt is malformed", 1, { work_id: work.work_id });
|
|
827
|
+
}
|
|
828
|
+
if (!copy) {
|
|
829
|
+
if (external)
|
|
830
|
+
throw new AppError("read_only_workspace_unbound", "External review start receipt has no copy binding", 1, { work_id: work.work_id });
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
if (!copy.root || !copy.sha256)
|
|
834
|
+
throw new AppError("read_only_workspace_unbound", "Review copy receipt is incomplete", 1, { work_id: work.work_id });
|
|
835
|
+
const base = reviewWorkspaceBase(context, work);
|
|
836
|
+
const actual = reviewExecutionCopyHash(reviewInputPath(requireRunHome(run), copy.root), run.workspace_root, true, reviewPaths, base);
|
|
837
|
+
if (actual !== copy.sha256)
|
|
838
|
+
throw new AppError("read_only_input_changed", "Read-only execution copy changed during review", 2, { work_id: work.work_id, expected: copy.sha256, current: actual });
|
|
839
|
+
if (copy.source_sha256 && reviewSourceHash(run.workspace_root, reviewPaths, base) !== copy.source_sha256)
|
|
840
|
+
throw new AppError("read_only_input_changed", "Authoritative review workspace changed during review", 2, { work_id: work.work_id });
|
|
841
|
+
}
|
|
842
|
+
function reviewWorkspaceBase(context, work) {
|
|
843
|
+
const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]);
|
|
844
|
+
const base = row && JSON.parse(row.index_json).workspace?.base;
|
|
845
|
+
return base && base !== "unknown" ? base : "HEAD";
|
|
846
|
+
}
|
|
847
|
+
function legacyReviewFingerprint(work, run) {
|
|
848
|
+
const kind = parsePayload(work)?.kind;
|
|
849
|
+
const relative = kind === "code-review" ? "06-code-review/review-context.json" : kind === "plan-review" ? "04-plan-review/work-context.json" : null;
|
|
850
|
+
if (!relative || !work.parent_work_id)
|
|
851
|
+
return null;
|
|
852
|
+
const file = path.join(requireRunHome(run), relative);
|
|
853
|
+
if (!fs.existsSync(file))
|
|
854
|
+
return null;
|
|
855
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
856
|
+
return value.read_only_input?.version !== 2 && value.read_only_input?.parent_work_id === work.parent_work_id && typeof value.read_only_input.fingerprint === "string" ? value.read_only_input.fingerprint : null;
|
|
857
|
+
}
|
|
858
|
+
function assertSharedReviewInput(context, work, run, generation = recoveryGuard(context, work.project_id, work.run_id)?.generation ?? 0) {
|
|
859
|
+
const payload = parsePayload(work), kind = payload?.kind;
|
|
860
|
+
const relative = kind === "code-review" ? "06-code-review/review-context.json" : kind === "plan-review" ? "04-plan-review/work-context.json" : null;
|
|
861
|
+
if (!relative || !work.parent_work_id)
|
|
862
|
+
return null;
|
|
863
|
+
const home = requireRunHome(run), file = path.join(home, relative);
|
|
864
|
+
if (!fs.existsSync(file))
|
|
865
|
+
throw new AppError("review_input_missing", "The review stage context is missing", 1, { work_id: work.work_id, file: relative });
|
|
866
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
867
|
+
if (value.read_only_input?.parent_work_id !== work.parent_work_id)
|
|
868
|
+
throw new AppError("review_input_invalid", "Reviewer belongs to a different review group", 1, { work_id: work.work_id, parent_work_id: work.parent_work_id });
|
|
869
|
+
const index = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json);
|
|
870
|
+
const stage = (name) => index.stage_runs?.find(item => item.stage === name);
|
|
871
|
+
if (value.read_only_input.version !== 2 && value.read_only_input.version !== 3) {
|
|
872
|
+
if (stage(kind === "plan-review" ? "plan" : "code")?.data_sha256)
|
|
873
|
+
throw new AppError("review_input_contract_missing", "A new review run cannot downgrade its input contract", 1, { work_id: work.work_id });
|
|
874
|
+
return null; // Historical receipts retain their original fingerprint contract.
|
|
875
|
+
}
|
|
876
|
+
const expected = new Map();
|
|
877
|
+
const add = (root, relativePath, sha) => {
|
|
878
|
+
if (!/^[a-f0-9]{64}$/.test(sha))
|
|
879
|
+
throw new AppError("review_input_invalid", "Review input lacks an accepted checksum", 1, { path: relativePath });
|
|
880
|
+
reviewInputPath(root === "run" ? home : run.workspace_root, relativePath);
|
|
881
|
+
const key = `${root}:${relativePath}`;
|
|
882
|
+
if (expected.has(key) && expected.get(key) !== sha)
|
|
883
|
+
throw new AppError("review_input_invalid", "Review input has conflicting accepted checksums", 1, { path: relativePath });
|
|
884
|
+
expected.set(key, sha);
|
|
885
|
+
};
|
|
886
|
+
const stageReport = (name, relativePath) => {
|
|
887
|
+
const sha = stage(name)?.data_sha256;
|
|
888
|
+
if (!sha)
|
|
889
|
+
throw new AppError("review_input_contract_missing", "Accepted stage report has no committed checksum", 1, { stage: name });
|
|
890
|
+
add("run", relativePath, sha);
|
|
891
|
+
const reportFile = reviewInputPath(home, relativePath);
|
|
892
|
+
if (!fs.existsSync(reportFile) || sha256(fs.readFileSync(reportFile, "utf8")) !== sha)
|
|
893
|
+
throw new AppError("read_only_input_changed", "Accepted stage report changed before or during review", 2, { path: relativePath, expected: sha });
|
|
894
|
+
return JSON.parse(fs.readFileSync(reportFile, "utf8"));
|
|
895
|
+
};
|
|
896
|
+
if (kind === "plan-review") {
|
|
897
|
+
const accepted = stageReport("plan", "03-plan/stage-report.json").semantic;
|
|
898
|
+
if (!accepted?.plan_checksums?.length || !accepted.aspect_map_checksums?.length || !accepted.batch_checksum)
|
|
899
|
+
throw new AppError("review_input_contract_missing", "Accepted PLAN lacks exact review input checksums", 1);
|
|
900
|
+
for (const item of accepted.plan_checksums)
|
|
901
|
+
add("workspace", item.path, item.sha256);
|
|
902
|
+
for (const item of accepted.aspect_map_checksums)
|
|
903
|
+
add("run", item.path, item.sha256);
|
|
904
|
+
add("run", "03-plan/code-work-batch.json", accepted.batch_checksum);
|
|
905
|
+
if (value.system?.batch_checksum !== accepted.batch_checksum)
|
|
906
|
+
throw new AppError("read_only_input_changed", "PLAN-REVIEW batch differs from accepted PLAN", 2);
|
|
907
|
+
const planSet = accepted.plan_checksums.map(item => ({ protocol_id: path.basename(path.dirname(item.path)), path: item.path, sha256: item.sha256 })).sort((a, b) => a.protocol_id.localeCompare(b.protocol_id));
|
|
908
|
+
if (value.system?.plan_checksum !== sha256(JSON.stringify(planSet)))
|
|
909
|
+
throw new AppError("read_only_input_changed", "PLAN-REVIEW plan revision differs from accepted PLAN", 2);
|
|
910
|
+
}
|
|
911
|
+
else {
|
|
912
|
+
stageReport("code", "05-code/stage-report.json");
|
|
913
|
+
if (value.code_report_sha256 !== stage("code")?.data_sha256 || !stage("code-review")?.input_sha256 || !value.review_batch_sha256 || !Array.isArray(value.aspect_map_checksums) || !value.aspect_map_checksums.length
|
|
914
|
+
|| sha256(JSON.stringify({ batch: value.review_batch_sha256, aspect_maps: value.aspect_map_checksums })) !== stage("code-review")?.input_sha256)
|
|
915
|
+
throw new AppError("review_input_contract_missing", "CODE-REVIEW inputs are not bound to their accepted stage", 1);
|
|
916
|
+
add("run", "06-code-review/review-work-batch.json", value.review_batch_sha256);
|
|
917
|
+
for (const item of value.aspect_map_checksums)
|
|
918
|
+
add("run", item.path, item.sha256);
|
|
919
|
+
if (value.cycle !== payload?.review_cycle)
|
|
920
|
+
throw new AppError("review_input_invalid", "CODE-REVIEW cycle differs from its Work", 1);
|
|
921
|
+
}
|
|
922
|
+
const runInputs = [...expected].map(([key, sha]) => { const [root, ...parts] = key.split(":"); return { root: root, path: parts.join(":"), sha256: sha }; }).sort((a, b) => `${a.root}:${a.path}`.localeCompare(`${b.root}:${b.path}`));
|
|
923
|
+
for (const item of runInputs) {
|
|
924
|
+
const target = reviewInputPath(item.root === "run" ? home : run.workspace_root, item.path);
|
|
925
|
+
const actual = fs.existsSync(target) ? sha256(fs.readFileSync(target, "utf8")) : null;
|
|
926
|
+
if (actual !== item.sha256)
|
|
927
|
+
throw new AppError("read_only_input_changed", "Accepted review input changed", 2, { work_id: work.work_id, root: item.root, path: item.path, expected: item.sha256, current: actual });
|
|
928
|
+
}
|
|
929
|
+
const reviewPaths = runInputs.filter(item => item.root === "workspace").map(item => item.path);
|
|
930
|
+
if (value.read_only_input.version === 3)
|
|
931
|
+
for (const relative of reviewPaths) {
|
|
932
|
+
if (!reviewEnvironmentAllowed(relative))
|
|
933
|
+
throw new AppError("review_input_invalid", "Required review input is excluded from external review", 1, { path: relative });
|
|
934
|
+
}
|
|
935
|
+
const base = index.workspace?.base && index.workspace.base !== "unknown" ? index.workspace.base : "HEAD";
|
|
936
|
+
const selectedPaths = value.read_only_input.version === 3 ? reviewSourcePaths(run.workspace_root, reviewPaths, base) : null;
|
|
937
|
+
if (selectedPaths && reviewPaths.some(relative => !selectedPaths.includes(relative)))
|
|
938
|
+
throw new AppError("review_input_invalid", "Required review input is excluded from external review", 1, { work_id: work.work_id });
|
|
939
|
+
const selectedSource = value.read_only_input.version === 3 ? reviewSourceHash(run.workspace_root, reviewPaths, base) : null;
|
|
940
|
+
const current = { schema_id: value.read_only_input.version === 3 ? "dd-flow/review-input@3" : "dd-flow/review-input@2", parent_work_id: work.parent_work_id, kind: String(kind), cycle: kind === "code-review" ? String(payload?.review_cycle) : "initial", generation, workspace_fingerprint: selectedSource ?? workspaceFingerprint(run.workspace_root), ...(selectedSource ? { source_policy: "review-inputs@1", source_sha256: selectedSource } : {}), run_inputs: runInputs };
|
|
941
|
+
const committed = context.db.all("SELECT 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 w.parent_work_id = ? AND json_extract(w.payload_json, '$.kind') = ? AND ws.start_receipt_json IS NOT NULL ORDER BY ws.created_at, ws.id", [work.project_id, work.run_id, work.parent_work_id, kind]);
|
|
942
|
+
for (const row of committed) {
|
|
943
|
+
const receipt = JSON.parse(row.start_receipt_json);
|
|
944
|
+
if (!receipt.context)
|
|
945
|
+
continue;
|
|
946
|
+
const prior = JSON.parse(receipt.context).review_input;
|
|
947
|
+
if (!prior || prior.cycle !== current.cycle)
|
|
948
|
+
continue;
|
|
949
|
+
// Recovery changes the execution owner, not the review revision. A
|
|
950
|
+
// completed sibling from an older generation still pins this review cycle.
|
|
951
|
+
if (prior.schema_id !== current.schema_id || JSON.stringify({ ...prior, generation }) !== JSON.stringify(current))
|
|
952
|
+
throw new AppError("read_only_input_changed", "Reviewer inputs differ from the first committed review start", 2, { work_id: work.work_id, baseline: prior, current });
|
|
953
|
+
break;
|
|
954
|
+
}
|
|
955
|
+
return current;
|
|
956
|
+
}
|
|
957
|
+
async function settle(context, id, status, result, progress, retry) {
|
|
958
|
+
const { work, run, link } = prepareWorkSettlement(context, id, status, result);
|
|
959
|
+
id = work.work_id;
|
|
324
960
|
let receipts = [];
|
|
325
961
|
let coordinationDrift = [];
|
|
326
|
-
|
|
327
|
-
if (parsePayload(work)?.read_only === true) {
|
|
962
|
+
const assertReadOnlyInput = () => {
|
|
963
|
+
if (status === "completed" && parsePayload(work)?.read_only === true) {
|
|
964
|
+
assertReviewCopyUnchanged(context, work, run, link);
|
|
965
|
+
const shared = assertSharedReviewInput(context, work, run);
|
|
966
|
+
if (shared)
|
|
967
|
+
return;
|
|
968
|
+
const legacy = legacyReviewFingerprint(work, run);
|
|
969
|
+
// The final reviewer commits the shared input boundary under the writer
|
|
970
|
+
// reservation. Concurrent finishes cannot both skip this verification.
|
|
971
|
+
if (legacy && 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]))
|
|
972
|
+
return;
|
|
328
973
|
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;
|
|
974
|
+
const baseline = legacy ?? (contextFile && fs.existsSync(contextFile) ? JSON.parse(fs.readFileSync(contextFile, "utf8")).workspace_fingerprint : null);
|
|
330
975
|
const current = workspaceFingerprint(run.workspace_root);
|
|
331
976
|
if (typeof baseline !== "string" || baseline !== current)
|
|
332
|
-
throw new AppError("
|
|
977
|
+
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
978
|
}
|
|
979
|
+
};
|
|
980
|
+
if (status === "completed") {
|
|
334
981
|
validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link?.result_path ?? null);
|
|
335
982
|
const packet = codePacket(work);
|
|
336
983
|
if (packet) {
|
|
@@ -340,19 +987,28 @@ async function settle(context, id, status, result, progress) {
|
|
|
340
987
|
readCodeCheckProfile(run.workspace_root);
|
|
341
988
|
coordinationDrift = plannedAreaDrift(packet, result);
|
|
342
989
|
const artifactDir = path.relative(requireRunHome(run), path.dirname(link.result_path));
|
|
343
|
-
|
|
990
|
+
const requiredChecks = packet.repair?.verification_check_refs?.length
|
|
991
|
+
? uniqueChecks([...packet.checks.filter((check) => check.run_at === "work"), ...packet.repair.verification_check_refs])
|
|
992
|
+
: packet.checks.filter((check) => check.run_at === "work");
|
|
993
|
+
if (retry)
|
|
994
|
+
validateFailedCheckRetry(context, { projectId: work.project_id, runId: work.run_id, receiptId: retry.receiptId, declarations: requiredChecks, reason: retry.reason });
|
|
995
|
+
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
996
|
const failed = receipts.filter((receipt) => receipt.status !== "passed");
|
|
345
997
|
if (failed.length)
|
|
346
998
|
throw new AppError("work_checks_failed", "Work remains running because required checks failed", 2, { work_id: id, failures: failed, all_receipts: receipts });
|
|
347
999
|
}
|
|
348
1000
|
}
|
|
349
1001
|
const now = context.now();
|
|
350
|
-
context.db.
|
|
1002
|
+
context.db.beginWriteTransaction();
|
|
351
1003
|
try {
|
|
1004
|
+
assertReadOnlyInput();
|
|
1005
|
+
assertWorkSettlementAllowed(context, work.project_id, work.run_id, work.work_id);
|
|
1006
|
+
if (link && !context.db.get("SELECT 1 FROM work_sessions WHERE id = ? AND status = 'running'", [link.id]))
|
|
1007
|
+
throw new AppError("work_generation_stale", "Work Session was interrupted or superseded while checks ran", 1, { work_id: id });
|
|
1008
|
+
if (link?.result_path && work.parent_work_id !== null)
|
|
1009
|
+
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
1010
|
context.db.run("UPDATE works SET status = ?, result = ?, completed_at = ?, updated_at = ? WHERE work_id = ?", [status, result, now, now, id]);
|
|
353
1011
|
if (link) {
|
|
354
|
-
if (link.result_path && work.parent_work_id !== null)
|
|
355
|
-
fs.writeFileSync(link.result_path, result);
|
|
356
1012
|
context.db.run("UPDATE work_sessions SET status = ?, completed_at = ?, updated_at = ? WHERE id = ?", [status, now, now, link.id]);
|
|
357
1013
|
const stillRunning = context.db.get("SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running' LIMIT 1", [link.session_id]);
|
|
358
1014
|
if (!stillRunning)
|
|
@@ -364,18 +1020,25 @@ async function settle(context, id, status, result, progress) {
|
|
|
364
1020
|
context.db.exec("ROLLBACK");
|
|
365
1021
|
throw error;
|
|
366
1022
|
}
|
|
1023
|
+
materializePendingWorkResults(context, work.project_id, work.run_id);
|
|
1024
|
+
settleRecoveryWork(context, work.work_id, status);
|
|
367
1025
|
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
368
|
-
const
|
|
1026
|
+
const control = runControlDirective(context, work.project_id, work.run_id);
|
|
1027
|
+
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
1028
|
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
1029
|
for (const ready of newlyReady)
|
|
371
1030
|
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" } };
|
|
1031
|
+
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
1032
|
}
|
|
1033
|
+
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
1034
|
function plannedAreaDrift(packet, result) {
|
|
375
1035
|
const changed = JSON.parse(result).changed_paths;
|
|
376
1036
|
if (!Array.isArray(changed) || packet.planned_write_areas.length === 0)
|
|
377
1037
|
return [];
|
|
378
|
-
return changed.filter((item) => typeof item === "string" && !packet.planned_write_areas.some((area) =>
|
|
1038
|
+
return changed.filter((item) => typeof item === "string" && !packet.planned_write_areas.some((area) => {
|
|
1039
|
+
const normalized = area.replace(/[\\/]+$/, "");
|
|
1040
|
+
return item === normalized || item.startsWith(`${normalized}/`);
|
|
1041
|
+
}));
|
|
379
1042
|
}
|
|
380
1043
|
function bindSession(context, work, run, identity, now) {
|
|
381
1044
|
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 +1048,30 @@ function bindSession(context, work, run, identity, now) {
|
|
|
385
1048
|
// Work ancestry and provider-tree containment are different relations. An
|
|
386
1049
|
// isolated worker is logically a child Work but physically a provider root.
|
|
387
1050
|
const parentSession = inferredParentSession ?? identity.parentSessionId;
|
|
1051
|
+
// Stored provider ancestry uses internal keys, just like hook_events.
|
|
1052
|
+
// Resolve native IDs only when rendering diagnostics; changing storage here
|
|
1053
|
+
// breaks existing bindings and usage ancestry joins.
|
|
388
1054
|
const providerParentSession = identity.parentSessionId;
|
|
1055
|
+
const identityDetails = (sessionKey = identity.sessionId, parentKey = parentSession) => ({
|
|
1056
|
+
internal_session_key: sessionKey,
|
|
1057
|
+
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,
|
|
1058
|
+
internal_parent_session_key: parentKey,
|
|
1059
|
+
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,
|
|
1060
|
+
harness: identity.harness
|
|
1061
|
+
});
|
|
389
1062
|
if (work.parent_work_id && !parentSession)
|
|
390
1063
|
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 });
|
|
1064
|
+
if (work.launch_policy === "fresh_agent_required" && inferredParentSession && identity.parentSessionId && identity.parentSessionId !== inferredParentSession)
|
|
1065
|
+
throw new AppError("native_work_parent_mismatch", "Fresh native Work must be started by a direct child of its assigned parent Session", 1, { work_id: work.work_id, effect: "no_effect", ...identityDetails(), observed_provider_parent_session_key: identity.parentSessionId });
|
|
391
1066
|
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,
|
|
1067
|
+
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
1068
|
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
|
-
|
|
395
|
-
|
|
1069
|
+
// A reuse-allowed Work can follow another Work in this same Session. Its
|
|
1070
|
+
// Work predecessor is not a new physical/logical parent of the Session.
|
|
1071
|
+
if (existing && existing.parent_session_id && parentSession && parentSession !== identity.sessionId && existing.parent_session_id !== parentSession)
|
|
1072
|
+
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
1073
|
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:
|
|
1074
|
+
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
1075
|
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
1076
|
reactivateBoundSession(context, work.project_id, identity.sessionId, now);
|
|
400
1077
|
}
|
|
@@ -408,6 +1085,15 @@ export function bindSessionForResume(context, workId, identity, now) {
|
|
|
408
1085
|
function reactivateBoundSession(context, projectId, sessionId, now) {
|
|
409
1086
|
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
1087
|
}
|
|
1088
|
+
export function prepareWorkResult(context, id, result) {
|
|
1089
|
+
try {
|
|
1090
|
+
const { work, run, link } = prepareWorkSettlement(context, id, "completed", result);
|
|
1091
|
+
validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link?.result_path ?? null);
|
|
1092
|
+
}
|
|
1093
|
+
catch (error) {
|
|
1094
|
+
prepareError(error, { work_id: id });
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
411
1097
|
function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, runId, resultPath) {
|
|
412
1098
|
if (!work.result_schema)
|
|
413
1099
|
return;
|
|
@@ -420,15 +1106,8 @@ function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, r
|
|
|
420
1106
|
catch {
|
|
421
1107
|
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
1108
|
}
|
|
423
|
-
|
|
424
|
-
|
|
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")
|
|
1109
|
+
validateSchema({ schemaName: work.result_schema.replace(/^dd-flow\//, "").replace(/@\d+$/, ""), file: resultPath, data: parsed, projectRoot, runId, runRoot: runHome });
|
|
1110
|
+
if (work.result_schema === "dd-flow/code-work-result@3")
|
|
432
1111
|
validateCodeWorkResult(work, parsed, workspaceRoot, runHome, runId);
|
|
433
1112
|
if (work.result_schema === "dd-flow/code-review-result@1")
|
|
434
1113
|
validateCodeReviewResult(work, parsed, { workspaceRoot, runHome, runId });
|
|
@@ -437,20 +1116,29 @@ function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, r
|
|
|
437
1116
|
}
|
|
438
1117
|
function validateCodeWorkResult(work, value, projectRoot, runHome, runId) {
|
|
439
1118
|
const result = value;
|
|
1119
|
+
const changedPaths = (result.changed_paths ?? []).map((item) => normalizeWorkspacePath(projectRoot, item));
|
|
1120
|
+
const ignored = ignoredWorkspacePaths(projectRoot, changedPaths);
|
|
1121
|
+
if (ignored.length)
|
|
1122
|
+
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
1123
|
if ((result.deviations?.length ?? 0) > 0 || (result.blockers?.length ?? 0) > 0)
|
|
441
1124
|
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
1125
|
const packet = codePacket(work);
|
|
443
1126
|
if (!packet)
|
|
444
1127
|
return;
|
|
445
|
-
const
|
|
1128
|
+
const acceptedObligations = new Set(packet.acceptance.map((item) => item.criterion_id).filter((item) => typeof item === "string"));
|
|
1129
|
+
for (const check of packet.checks)
|
|
1130
|
+
acceptedObligations.add(check.id);
|
|
1131
|
+
for (const finding of packet.repair?.review_findings ?? [])
|
|
1132
|
+
for (const ref of finding.obligation_refs ?? [])
|
|
1133
|
+
acceptedObligations.add(ref);
|
|
446
1134
|
for (const item of result.evidence ?? []) {
|
|
447
|
-
if (!item.
|
|
448
|
-
throw new AppError("
|
|
1135
|
+
if (!item.obligation_ref || !acceptedObligations.has(item.obligation_ref))
|
|
1136
|
+
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
1137
|
for (const ref of item.refs ?? [])
|
|
450
1138
|
assertPortableArtifactRef(ref, { workspaceRoot: projectRoot, runHome, runId });
|
|
451
1139
|
}
|
|
452
1140
|
const documentUpdates = (packet.document_updates ?? []);
|
|
453
|
-
const changed = new Set(
|
|
1141
|
+
const changed = new Set(changedPaths);
|
|
454
1142
|
const missingDocuments = documentUpdates.map((entry) => entry.path).filter((entry) => !changed.has(entry));
|
|
455
1143
|
if (missingDocuments.length)
|
|
456
1144
|
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 });
|
|
@@ -459,10 +1147,10 @@ function validateCodeWorkResult(work, value, projectRoot, runHome, runId) {
|
|
|
459
1147
|
if (unchangedDocuments.length)
|
|
460
1148
|
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
1149
|
const assigned = packet.repair?.review_findings?.map((finding) => finding.finding_ref) ?? [];
|
|
1150
|
+
validateReviewResolutions(work.work_id, assigned, result.resolutions ?? []);
|
|
462
1151
|
if (assigned.length) {
|
|
463
|
-
if (
|
|
1152
|
+
if (changedPaths.length === 0)
|
|
464
1153
|
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
|
-
validateReviewResolutions(work.work_id, assigned, result.resolutions ?? []);
|
|
466
1154
|
for (const resolution of result.resolutions ?? [])
|
|
467
1155
|
for (const ref of resolution.evidence_refs ?? [])
|
|
468
1156
|
assertPortableArtifactRef(ref, { workspaceRoot: projectRoot, runHome, runId });
|
|
@@ -479,22 +1167,57 @@ export function validateReviewResolutions(workId, assigned, resolutions) {
|
|
|
479
1167
|
function renderWorkerPrompt(context, work, run, dependencies) {
|
|
480
1168
|
const command = flowCommand(context);
|
|
481
1169
|
const packet = codePacket(work);
|
|
482
|
-
const
|
|
1170
|
+
const readOnly = parsePayload(work)?.read_only === true;
|
|
1171
|
+
const resultInputPath = path.join(requireRunHome(run), "works", work.work_id, "result-input.json");
|
|
1172
|
+
const finishWorkCommand = managedLifecycleCommand(context, runtimeCommand(context, ["work", "finish", work.work_id, "--result-file", resultInputPath, "--project-root", run.project_root, "--json", "--progress-jsonl"]));
|
|
1173
|
+
const failWorkCommand = managedLifecycleCommand(context, runtimeCommand(context, ["work", "fail", shortWorkId(work.work_id), "--reason", "receipt path + exact external or semantic blocker", "--project-root", run.project_root, "--json"]));
|
|
1174
|
+
const mergeWork = parsePayload(work)?.kind === "merge";
|
|
1175
|
+
const writeBoundary = readOnly
|
|
1176
|
+
? [`Review inputs under workspace_root (${run.workspace_root}) and run_home are read-only. After Work start, work from workspace_root and do not edit project source, PLAN, aspect maps, CODE evidence, or another Work's files.`, "Do not write inside workspace_root, including an isolated review copy. Write only this Work's declared result-input.json and explicitly assigned Work-owned evidence paths under run_home. Report changed or inaccessible review inputs as a blocker; do not repair them."]
|
|
1177
|
+
: mergeWork
|
|
1178
|
+
? ["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."]
|
|
1179
|
+
: [`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."];
|
|
1180
|
+
const completionRepair = readOnly
|
|
1181
|
+
? ["If Finish reports input drift or an infrastructure failure, report the exact receipt and stop. Do not change the reviewed files to make the check pass."]
|
|
1182
|
+
: mergeWork
|
|
1183
|
+
? ["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."]
|
|
1184
|
+
: ["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."];
|
|
1185
|
+
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>", ""] : [];
|
|
483
1186
|
if (packet)
|
|
484
1187
|
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>", "");
|
|
485
|
-
|
|
1188
|
+
if (packet)
|
|
1189
|
+
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>", "");
|
|
1190
|
+
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. Copy the quoted alias literally; do not add backslashes. 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), `Write the completed JSON to ${resultInputPath}. This is an attempt input, not the canonical result.json receipt. dd-flow validates the file and atomically 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.", `First write only the result JSON to ${resultInputPath}. Then run this standalone command:\n${finishWorkCommand}`, `Fail only for an evidenced external or semantic-contract blocker: ${failWorkCommand}`, "</completion>", ""].join("\n");
|
|
486
1191
|
}
|
|
487
|
-
function resultSchemaGuidance(work, runId) {
|
|
1192
|
+
export function resultSchemaGuidance(work, runId) {
|
|
488
1193
|
const schema = work.result_schema;
|
|
489
1194
|
const refs = `Evidence refs for project source are relative to workspace_root; RUN evidence uses run://${runId}/path/to/artifact.`;
|
|
490
|
-
if (schema === "dd-flow/code-work-result@
|
|
491
|
-
|
|
1195
|
+
if (schema === "dd-flow/code-work-result@3") {
|
|
1196
|
+
const packet = codePacket(work);
|
|
1197
|
+
const obligations = [...new Set([
|
|
1198
|
+
...(packet?.acceptance ?? []).map((item) => item.criterion_id).filter((id) => Boolean(id)),
|
|
1199
|
+
...(packet?.checks ?? []).map((item) => item.id),
|
|
1200
|
+
...(packet?.repair?.review_findings ?? []).flatMap((finding) => finding.obligation_refs ?? [])
|
|
1201
|
+
])];
|
|
1202
|
+
const findings = packet?.repair?.review_findings ?? [];
|
|
1203
|
+
return [refs, `Assigned obligation refs: ${JSON.stringify(obligations)}. Cite only these in evidence.obligation_ref.`,
|
|
1204
|
+
"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.",
|
|
1205
|
+
"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: [].",
|
|
1206
|
+
"```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), "```",
|
|
1207
|
+
"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."];
|
|
1208
|
+
}
|
|
492
1209
|
if (schema === "dd-flow/code-review-result@1") {
|
|
493
|
-
|
|
1210
|
+
const aspect = { aspect_id: "assigned_aspect_id", verdict: "pass", summary: "Conclusion.", evidence_refs: ["path/to/evidence"] };
|
|
1211
|
+
const clean = { schema_id: schema, verdict: "pass", summary: "Concise evidence-backed conclusion.", aspects: [aspect], findings: [] };
|
|
1212
|
+
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"] }] };
|
|
1213
|
+
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), "```"];
|
|
494
1214
|
}
|
|
495
1215
|
if (schema !== "dd-flow/plan-review-result@1")
|
|
496
1216
|
return [];
|
|
497
|
-
|
|
1217
|
+
const aspect = { aspect_id: "assigned_aspect_id", verdict: "pass", summary: "Conclusion for this aspect.", evidence_refs: ["path/to/evidence"], findings: [] };
|
|
1218
|
+
const clean = { schema_id: schema, plan_revision: 1, overall_verdict: "pass", summary: "Concise evidence-backed conclusion.", aspects: [aspect] };
|
|
1219
|
+
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"] }] }] };
|
|
1220
|
+
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), "```"];
|
|
498
1221
|
}
|
|
499
1222
|
export function validateCodeReviewResultIdentity(work, value) {
|
|
500
1223
|
const group = codeReviewGroup(work);
|
|
@@ -523,6 +1246,7 @@ export function validateCodeReviewResultIdentity(work, value) {
|
|
|
523
1246
|
function validateCodeReviewResult(work, value, input) {
|
|
524
1247
|
validateCodeReviewResultIdentity(work, value);
|
|
525
1248
|
const result = value;
|
|
1249
|
+
assertReviewAspectEvidence(work, result.aspects ?? [], "CODE");
|
|
526
1250
|
const findings = result.findings ?? [];
|
|
527
1251
|
// A reviewer is a child Work and cannot pause its coordinator-owned Stage.
|
|
528
1252
|
// Its structured blocked result is evidence for the coordinator, which then
|
|
@@ -552,6 +1276,7 @@ export function validatePlanReviewResult(work, value, input) {
|
|
|
552
1276
|
const unexpected = ids.filter((id) => !expected.has(id));
|
|
553
1277
|
if (new Set(ids).size !== ids.length || missing.length || unexpected.length)
|
|
554
1278
|
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 });
|
|
1279
|
+
assertReviewAspectEvidence(work, aspects, "PLAN");
|
|
555
1280
|
const findingIds = aspects.flatMap((aspect) => aspect.findings ?? []).map((finding) => finding.finding_id ?? "");
|
|
556
1281
|
const invalid = findingIds.filter((id) => !/^FIND-\d{3}$/.test(id));
|
|
557
1282
|
if (new Set(findingIds).size !== findingIds.length || invalid.length)
|
|
@@ -566,6 +1291,11 @@ export function validatePlanReviewResult(work, value, input) {
|
|
|
566
1291
|
assertPortableArtifactRef(ref, input);
|
|
567
1292
|
}
|
|
568
1293
|
}
|
|
1294
|
+
function assertReviewAspectEvidence(work, aspects, stage) {
|
|
1295
|
+
const missing = aspects.filter((aspect) => !Array.isArray(aspect.evidence_refs) || aspect.evidence_refs.length === 0).map((aspect) => aspect.aspect_id ?? "");
|
|
1296
|
+
if (missing.length)
|
|
1297
|
+
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 });
|
|
1298
|
+
}
|
|
569
1299
|
function codeReviewGroup(work) {
|
|
570
1300
|
const payload = parsePayload(work);
|
|
571
1301
|
const group = payload?.group;
|
|
@@ -576,10 +1306,14 @@ function codeReviewGroup(work) {
|
|
|
576
1306
|
? { key: value.key, aspect_ids: value.aspect_ids }
|
|
577
1307
|
: null;
|
|
578
1308
|
}
|
|
579
|
-
function requireWork(context, id
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
1309
|
+
function requireWork(context, id, explicitScope) {
|
|
1310
|
+
ensureWorkRegistry(context);
|
|
1311
|
+
const configured = context.env.DD_FLOW_INVOCATION_SCOPE;
|
|
1312
|
+
const scope = configured ? JSON.parse(configured) : undefined;
|
|
1313
|
+
const projectId = explicitScope?.projectId ?? (scope?.projectRoot ? context.db.get("SELECT id FROM projects WHERE root = ?", [scope.projectRoot])?.id : undefined);
|
|
1314
|
+
const runId = explicitScope?.runId ?? scope?.runId;
|
|
1315
|
+
return resolveWorkReference(context, id, { projectId, runId });
|
|
1316
|
+
}
|
|
583
1317
|
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)
|
|
584
1318
|
throw new AppError("runtime_missing", "RUN artifact root is unavailable", 1, { run_id: runId }); return run; }
|
|
585
1319
|
function requireRunHome(run) { if (!run.run_root)
|
|
@@ -621,18 +1355,12 @@ function validateItem(value, requireExecutionContext = false) { if (!value || ty
|
|
|
621
1355
|
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 } : {}) }; }
|
|
622
1356
|
function allowsEmptyRepairChecks(item) { const repair = item.repair; if (!repair || typeof repair !== "object" || Array.isArray(repair))
|
|
623
1357
|
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")); }
|
|
624
|
-
function readJson(file) { try {
|
|
625
|
-
return JSON.parse(fs.readFileSync(path.resolve(file), "utf8"));
|
|
626
|
-
}
|
|
627
|
-
catch (error) {
|
|
628
|
-
throw new AppError("validation", `Invalid JSON file: ${String(error)}`, 2, { file });
|
|
629
|
-
} }
|
|
630
1358
|
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) {
|
|
631
1359
|
const obsolete = path.join(run.run_root, "work.json");
|
|
632
1360
|
if (fs.existsSync(obsolete))
|
|
633
1361
|
fs.rmSync(obsolete);
|
|
634
1362
|
} }
|
|
635
|
-
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) })) }; }
|
|
1363
|
+
export function codeWorkGraph(context, projectId, runId) { const index = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId])?.index_json ?? "{}"); const active = index.stage_runs?.some(item => item.stage === "code-review" && item.status === "running") ? "code-review" : "code"; const members = index.stage_runs?.length ? stageWorkIds(context, projectId, runId, active) : null; 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)) && (!members || members.has(work.work_id))); 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) })) }; }
|
|
636
1364
|
function parsePayload(work) { if (!work.payload_json)
|
|
637
1365
|
return null; try {
|
|
638
1366
|
const value = JSON.parse(work.payload_json);
|
|
@@ -641,6 +1369,7 @@ function parsePayload(work) { if (!work.payload_json)
|
|
|
641
1369
|
catch {
|
|
642
1370
|
return null;
|
|
643
1371
|
} }
|
|
1372
|
+
function uniqueChecks(checks) { return checks.filter((check, index) => checks.findIndex((candidate) => candidate.id === check.id) === index); }
|
|
644
1373
|
function codePacket(work) { const value = parsePayload(work); if (value?.schema_id !== "dd-flow/code-work-packet@5")
|
|
645
1374
|
return null; return value; }
|
|
646
1375
|
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))
|