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