@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,45 +1,55 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
|
-
import os from "node:os";
|
|
4
3
|
import path from "node:path";
|
|
4
|
+
import { quote } from "shell-quote";
|
|
5
|
+
import { lifecycleRetryCommands, managedLifecycleCommand } from "./lifecycle-invocations.js";
|
|
5
6
|
import { AppError } from "../shared/errors.js";
|
|
7
|
+
import { entityReferenceVariants, shortEntityReference } from "../shared/entity-references.js";
|
|
6
8
|
import { resolveProjectRoot } from "../storage/paths.js";
|
|
9
|
+
import { publishImmutableInput } from "../storage/immutable-input.js";
|
|
10
|
+
import { resolveWorkReference } from "../storage/work-references.js";
|
|
7
11
|
import { findRecentMatchingHookEvent, claimStageResumeHookEvent, stageResumeMatchKey } from "./hooks.js";
|
|
8
12
|
import { requireProjectByRoot } from "./projects.js";
|
|
9
13
|
import { appendFlowRunTimelineEvent, pauseFlowRunStage, resumeFlowRunStage } from "./runs.js";
|
|
10
14
|
import { bindSessionForResume, refreshRunWorkProjection } from "./work-registry.js";
|
|
11
|
-
|
|
15
|
+
import { assertRunMutationAllowed } from "./run-recovery.js";
|
|
16
|
+
import { runtimeCommand } from "./runtime-command.js";
|
|
17
|
+
import { prepareAgentOutputFile } from "../storage/agent-output.js";
|
|
18
|
+
export { flowCommand } from "./runtime-command.js";
|
|
19
|
+
export function prepareStagePause(context, input) {
|
|
20
|
+
if (typeof input.question !== "string" || !input.question.trim())
|
|
21
|
+
throw new AppError("validation", "stage pause requires a non-empty user question", 2);
|
|
22
|
+
safeStage(input.stage);
|
|
12
23
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
13
24
|
const project = requireProjectByRoot(context, projectRoot);
|
|
14
25
|
const run = requireRun(context, project.id, input.runId);
|
|
26
|
+
assertRunMutationAllowed(context, project.id, run.id);
|
|
15
27
|
const work = requireWork(context, project.id, run.id, input.workId);
|
|
16
28
|
if (work.status !== "running")
|
|
17
29
|
throw new AppError("invalid_work_state", "Only a running Work can pause", 1, { work_id: work.work_id, status: work.status });
|
|
18
30
|
const question = input.question;
|
|
19
|
-
if (!question.trim())
|
|
20
|
-
throw new AppError("validation", "stage pause requires a non-empty user question", 2);
|
|
21
31
|
const stage = requireStage(run, input.stage, "running");
|
|
32
|
+
requireRunHome(run);
|
|
33
|
+
return { projectRoot, project, run, work, question, stage };
|
|
34
|
+
}
|
|
35
|
+
export function pauseStageForUser(context, input) {
|
|
36
|
+
const { projectRoot, project, run, work, question, stage } = prepareStagePause(context, input);
|
|
22
37
|
const pauseId = nextPauseId(requireRunHome(run));
|
|
23
38
|
const pauseRoot = path.join(requireRunHome(run), "intake", "hitl", `${pauseId}-${safeStage(input.stage)}`);
|
|
24
39
|
const questionPath = path.join(pauseRoot, "question.md");
|
|
25
40
|
fs.mkdirSync(pauseRoot, { recursive: true });
|
|
26
|
-
|
|
41
|
+
publishImmutableInput(questionPath, Buffer.from(question), "hitl_question_conflict");
|
|
42
|
+
const answerInputPath = prepareAgentOutputFile(path.join(pauseRoot, "answer-input.md"));
|
|
27
43
|
const now = context.now();
|
|
28
|
-
context.db.
|
|
29
|
-
try {
|
|
44
|
+
context.db.writeTransaction(() => {
|
|
30
45
|
const paused = context.db.run("UPDATE works SET status = 'paused', updated_at = ? WHERE work_id = ? AND status = 'running'", [now, work.work_id]);
|
|
31
46
|
if (paused.changes !== 1)
|
|
32
47
|
throw new AppError("invalid_work_state", "Work changed before pause could be accepted", 1, { work_id: work.work_id });
|
|
33
48
|
pauseFlowRunStage(context, { projectRoot, runId: run.id, stage: stage.stage, workId: work.work_id, pauseId, questionPath });
|
|
34
|
-
context.db.
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
throw error;
|
|
39
|
-
}
|
|
40
|
-
refreshRunWorkProjection(context, project.id, run.id);
|
|
41
|
-
const resume = stageResumeCommand(context, { runId: run.id, stage: stage.stage, workId: work.work_id, projectRoot });
|
|
42
|
-
const resumeTemplate = `${resume} <<'USER_ANSWER'\n<paste the complete user answer exactly>\nUSER_ANSWER`;
|
|
49
|
+
context.db.afterCommit(() => refreshRunWorkProjection(context, project.id, run.id));
|
|
50
|
+
});
|
|
51
|
+
const resume = stageResumeCommand(context, { runId: run.id, stage: stage.stage, workId: work.work_id, projectRoot, answerInputPath });
|
|
52
|
+
const resumeTemplate = `Write the complete user answer exactly to ${quote([answerInputPath])}, then run:\n${resume}`;
|
|
43
53
|
return {
|
|
44
54
|
ok: true,
|
|
45
55
|
outcome: "paused",
|
|
@@ -48,39 +58,56 @@ export function pauseStageForUser(context, input) {
|
|
|
48
58
|
stage: stage.stage,
|
|
49
59
|
pause: { id: pauseId, reason: "waiting_for_user", question_path: questionPath, user_message: question },
|
|
50
60
|
next_action: "ask_user_then_resume_same_stage",
|
|
51
|
-
agent_instruction:
|
|
61
|
+
agent_instruction: `Send user_message to the user and stop this Turn. When the user answers, write the complete raw answer without interpretation to ${answerInputPath}, then make resume_command the first flow command and follow the returned continuation prompt. Do not create a RUN, Work, attempt, or stage start.`,
|
|
52
62
|
resume_command: resume,
|
|
53
63
|
resume_command_template: resumeTemplate
|
|
54
64
|
};
|
|
55
65
|
}
|
|
56
|
-
export function
|
|
66
|
+
export function prepareStageResume(context, input) {
|
|
67
|
+
if (typeof input.answer !== "string" || !input.answer.trim())
|
|
68
|
+
throw new AppError("validation", "stage resume requires a non-empty user answer", 2);
|
|
69
|
+
safeStage(input.stage);
|
|
57
70
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
58
71
|
const project = requireProjectByRoot(context, projectRoot);
|
|
59
72
|
const run = requireRun(context, project.id, input.runId);
|
|
73
|
+
assertRunMutationAllowed(context, project.id, run.id);
|
|
60
74
|
const work = requireWork(context, project.id, run.id, input.workId);
|
|
61
75
|
if (work.status !== "paused")
|
|
62
76
|
throw new AppError("invalid_work_state", "stage resume requires its paused Work", 1, { work_id: work.work_id, status: work.status });
|
|
63
77
|
const stage = requireStage(run, input.stage, "paused");
|
|
64
78
|
if (!stage.pause || stage.pause.work_id !== work.work_id || stage.pause.answer_path)
|
|
65
79
|
throw new AppError("invalid_stage_state", "Stage has no unanswered pause for this Work", 1, { run_id: run.id, stage: stage.stage, work_id: work.work_id });
|
|
66
|
-
|
|
67
|
-
|
|
80
|
+
const workSession = context.db.get("SELECT id, session_id, prompt_path, result_path, status FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
|
|
81
|
+
if (!workSession)
|
|
82
|
+
throw new AppError("runtime_missing", "Paused Work has no open Session link", 1, { work_id: work.work_id });
|
|
83
|
+
let evidence = input.evidence;
|
|
84
|
+
if (evidence && (evidence.pauseId !== stage.pause.id || evidence.promptPath !== workSession.prompt_path || evidence.questionPath !== stage.pause.question_path))
|
|
85
|
+
throw new AppError("runtime_state_changed", "Paused Work changed after resume preparation", 1, { work_id: work.work_id });
|
|
86
|
+
if (!evidence) {
|
|
87
|
+
try {
|
|
88
|
+
evidence = { pauseId: stage.pause.id, promptPath: workSession.prompt_path, questionPath: stage.pause.question_path, prompt: fs.readFileSync(workSession.prompt_path, "utf8"), question: fs.readFileSync(stage.pause.question_path, "utf8") };
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
throw new AppError("runtime_missing", "Paused Work continuation artifacts cannot be read", 1, { work_id: work.work_id, cause: String(error) });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return { projectRoot, project, run, work, stage, pause: stage.pause, workSession, evidence };
|
|
95
|
+
}
|
|
96
|
+
export function resumeStageAfterUser(context, input) {
|
|
97
|
+
const { projectRoot, project, run, work, stage, pause, workSession, evidence } = prepareStageResume(context, input);
|
|
68
98
|
const hookEventId = input.hookEventId ?? findRecentMatchingHookEvent(context, {
|
|
69
99
|
projectId: project.id,
|
|
70
|
-
matchKey:
|
|
100
|
+
matchKey: entityReferenceVariants(run.id).flatMap((runReference) => entityReferenceVariants(work.work_id).map((workReference) => stageResumeMatchKey(runReference, stage.stage, workReference, projectRoot))),
|
|
71
101
|
errorCode: "trusted_stage_resume_required",
|
|
72
102
|
operation: "stage resume"
|
|
73
103
|
}).eventKey;
|
|
74
|
-
const answerPath = path.join(path.dirname(stage.pause.question_path), "answer.md");
|
|
75
|
-
fs.writeFileSync(answerPath, input.answer);
|
|
76
104
|
const now = context.now();
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
identity = claimStageResumeHookEvent(context, { projectId: project.id, runId: run.id, stage: stage.stage, workId: work.work_id, projectRoot, eventKey: hookEventId });
|
|
105
|
+
const answerPath = path.join(path.dirname(pause.question_path), `answer-${crypto.createHash("sha256").update(`${pause.id}\0${input.answer}`).digest("hex")}.md`);
|
|
106
|
+
// The answer is an immutable, content-addressed input. Prepare it before
|
|
107
|
+
// reserving SQLite's writer; an unreferenced candidate has no flow authority.
|
|
108
|
+
publishImmutableInput(answerPath, Buffer.from(input.answer), "hitl_answer_conflict");
|
|
109
|
+
context.db.writeTransaction(() => {
|
|
110
|
+
const identity = claimStageResumeHookEvent(context, { projectId: project.id, runId: run.id, stage: stage.stage, workId: work.work_id, projectRoot, eventKey: hookEventId });
|
|
84
111
|
if (workSession.session_id !== identity.sessionId) {
|
|
85
112
|
bindSessionForResume(context, work.work_id, identity, now);
|
|
86
113
|
context.db.run("UPDATE work_sessions SET status = 'completed', updated_at = ?, completed_at = ? WHERE id = ?", [now, now, workSession.id]);
|
|
@@ -90,26 +117,23 @@ export function resumeStageAfterUser(context, input) {
|
|
|
90
117
|
if (resumed.changes !== 1)
|
|
91
118
|
throw new AppError("invalid_work_state", "Work changed before resume could be accepted", 1, { work_id: work.work_id });
|
|
92
119
|
resumeFlowRunStage(context, { projectRoot, runId: run.id, stage: stage.stage, workId: work.work_id, answerPath });
|
|
93
|
-
context.
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
}
|
|
99
|
-
refreshRunWorkProjection(context, project.id, run.id);
|
|
100
|
-
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "stage_resume_session_bound", stage: stage.stage, work_id: work.work_id, session_id: identity.sessionId });
|
|
101
|
-
const prompt = fs.readFileSync(workSession.prompt_path, "utf8");
|
|
120
|
+
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "stage_resume_session_bound", stage: stage.stage, work_id: work.work_id, session_id: identity.sessionId });
|
|
121
|
+
context.db.afterCommit(() => refreshRunWorkProjection(context, project.id, run.id));
|
|
122
|
+
});
|
|
123
|
+
const prompt = evidence.prompt;
|
|
124
|
+
const retryCommands = lifecycleRetryCommands(context, stage.stage);
|
|
102
125
|
const continuation = [
|
|
103
126
|
prompt.trimEnd(),
|
|
104
127
|
"",
|
|
105
128
|
"<hitl_resume>",
|
|
106
|
-
`- Pause: ${
|
|
107
|
-
`- Question source: ${
|
|
129
|
+
`- Pause: ${pause.id}`,
|
|
130
|
+
`- Question source: ${pause.question_path}`,
|
|
108
131
|
`- Answer source: ${answerPath}`,
|
|
109
132
|
"- Continue the same stage, Work and attempt. Do not call stage start or repeat completed preparation.",
|
|
133
|
+
...(retryCommands.length ? ["- A prior no-effect lifecycle rejection now has these authoritative replacement commands; correct the rejected input and use only these replacements:", ...retryCommands.map(command => ` ${command}`)] : []),
|
|
110
134
|
"",
|
|
111
135
|
"<user_question>",
|
|
112
|
-
|
|
136
|
+
evidence.question,
|
|
113
137
|
"</user_question>",
|
|
114
138
|
"",
|
|
115
139
|
"<user_answer>",
|
|
@@ -118,18 +142,18 @@ export function resumeStageAfterUser(context, input) {
|
|
|
118
142
|
"</hitl_resume>",
|
|
119
143
|
""
|
|
120
144
|
].join("\n");
|
|
121
|
-
return { ok: true, outcome: "resumed", run_id: run.id, work_id: work.work_id, stage: stage.stage, pause_id:
|
|
145
|
+
return { ok: true, outcome: "resumed", run_id: run.id, work_id: work.work_id, stage: stage.stage, pause_id: pause.id, question_path: pause.question_path, answer_path: answerPath, prompt_path: workSession.prompt_path, worker_prompt_markdown: continuation, next_action: `continue_${stage.stage}` };
|
|
122
146
|
}
|
|
123
147
|
export function stagePauseCommand(context, input) {
|
|
124
|
-
|
|
148
|
+
const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
|
|
149
|
+
const run = requireRun(context, project.id, input.runId);
|
|
150
|
+
const questionInputPath = prepareAgentOutputFile(path.join(requireRunHome(run), "works", input.workId, "question-input.md"));
|
|
151
|
+
return managedLifecycleCommand(context, runtimeCommand(context, ["stage", "pause", shortEntityReference(input.runId), "--stage", input.stage, "--work", shortEntityReference(input.workId), "--question-file", questionInputPath, "--project-root", input.projectRoot, "--json"]));
|
|
125
152
|
}
|
|
126
|
-
/**
|
|
127
|
-
* The only shell form allowed for an agent-owned HITL pause. Supplying a
|
|
128
|
-
* complete heredoc makes stdin explicit without asking an agent to invent a
|
|
129
|
-
* pipe, a temporary file or a second command.
|
|
130
|
-
*/
|
|
153
|
+
/** Render separate file-write and lifecycle-call instructions for HITL. */
|
|
131
154
|
export function stagePauseCommandTemplate(command) {
|
|
132
|
-
|
|
155
|
+
const questionFile = command.match(/--question-file\s+(?:'([^']*)'|"([^"]*)"|(\S+))/)?.slice(1).find(Boolean) ?? "<question-file-from-command>";
|
|
156
|
+
return `Write this text to ${questionFile}:
|
|
133
157
|
## Q-001 — <short decision title>
|
|
134
158
|
|
|
135
159
|
Why this decision is required:
|
|
@@ -144,27 +168,12 @@ Recommendation:
|
|
|
144
168
|
|
|
145
169
|
Effect on scope or acceptance:
|
|
146
170
|
- <one sentence>
|
|
147
|
-
|
|
171
|
+
|
|
172
|
+
Then run this standalone command:
|
|
173
|
+
${command}`;
|
|
148
174
|
}
|
|
149
175
|
function stageResumeCommand(context, input) {
|
|
150
|
-
return
|
|
151
|
-
}
|
|
152
|
-
export function flowCommand(context) {
|
|
153
|
-
const defaultHome = path.resolve(path.join(os.homedir(), ".dd-flow"));
|
|
154
|
-
// Desktop/ACP tool processes are not required to inherit the environment of
|
|
155
|
-
// the adapter that created their Session. In an isolated runtime, a bare
|
|
156
|
-
// `dd-flow` can therefore select the host-global router despite a correct
|
|
157
|
-
// DD_FLOW_HOME. The runner supplies an absolute executable for that case;
|
|
158
|
-
// make every generated lifecycle command self-contained.
|
|
159
|
-
const executable = context.env.DD_FLOW_BIN;
|
|
160
|
-
if (executable && path.isAbsolute(executable)) {
|
|
161
|
-
return `DD_FLOW_HOME=${JSON.stringify(context.ddFlowHome)} ${JSON.stringify(executable)}`;
|
|
162
|
-
}
|
|
163
|
-
const isolatedExecutable = path.join(context.ddFlowHome, "bin", "dd-flow");
|
|
164
|
-
if (context.ddFlowHome !== defaultHome && fs.existsSync(isolatedExecutable)) {
|
|
165
|
-
return `DD_FLOW_HOME=${JSON.stringify(context.ddFlowHome)} ${JSON.stringify(isolatedExecutable)}`;
|
|
166
|
-
}
|
|
167
|
-
return context.ddFlowHome === defaultHome ? "dd-flow" : `DD_FLOW_HOME=${JSON.stringify(context.ddFlowHome)} dd-flow`;
|
|
176
|
+
return managedLifecycleCommand(context, runtimeCommand(context, ["stage", "resume", shortEntityReference(input.runId), "--stage", input.stage, "--work", shortEntityReference(input.workId), "--answer-file", input.answerInputPath, "--project-root", input.projectRoot, "--json"]));
|
|
168
177
|
}
|
|
169
178
|
function requireRun(context, projectId, id) {
|
|
170
179
|
const rows = context.db.all("SELECT id, short_id, project_id, project_root, run_root, index_json FROM runs WHERE project_id = ? AND (id = ? OR short_id = ?)", [projectId, id, id]);
|
|
@@ -173,14 +182,19 @@ function requireRun(context, projectId, id) {
|
|
|
173
182
|
return rows[0];
|
|
174
183
|
}
|
|
175
184
|
function requireWork(context, projectId, runId, workId) {
|
|
176
|
-
|
|
177
|
-
if (!work)
|
|
178
|
-
throw new AppError("not_found", "Work does not belong to this RUN", 1, { run_id: runId, work_id: workId });
|
|
179
|
-
return work;
|
|
185
|
+
return resolveWorkReference(context, workId, { projectId, runId });
|
|
180
186
|
}
|
|
181
187
|
function requireStage(run, stage, status) {
|
|
182
|
-
|
|
183
|
-
|
|
188
|
+
let index;
|
|
189
|
+
try {
|
|
190
|
+
index = JSON.parse(run.index_json);
|
|
191
|
+
if (!index || !Array.isArray(index.stage_runs))
|
|
192
|
+
throw new Error("RUN index must contain stage_runs");
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
throw new AppError("runtime_state_invalid", "RUN mechanical state in SQLite is missing or invalid", 1, { run_id: run.id, cause: String(error) });
|
|
196
|
+
}
|
|
197
|
+
const found = index.stage_runs.find((item) => item.stage === stage);
|
|
184
198
|
if (!found || found.status !== status)
|
|
185
199
|
throw new AppError("invalid_stage_state", `Stage must be ${status}`, 1, { run_id: run.id, stage, status: found?.status ?? "missing" });
|
|
186
200
|
return found;
|
|
@@ -1,14 +1,171 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import { AppError } from "../shared/errors.js";
|
|
5
|
+
import { withProjectionLock } from "../storage/projection-lock.js";
|
|
3
6
|
import { writeJsonAtomic } from "../storage/paths.js";
|
|
4
7
|
/** Deterministic JSON -> Markdown/HTML projection shared by every stage. */
|
|
5
8
|
export function writeStageReport(root, report) {
|
|
6
9
|
const json = path.join(root, "stage-report.json");
|
|
7
10
|
const markdown = path.join(root, "stage-report.md");
|
|
8
11
|
const html = path.join(root, "stage-report.html");
|
|
12
|
+
const normalized = normalizeStageReport(report);
|
|
13
|
+
writeJsonAtomic(json, normalized);
|
|
14
|
+
const text = renderStageReportMarkdown(normalized);
|
|
15
|
+
fs.writeFileSync(markdown, text);
|
|
16
|
+
fs.writeFileSync(html, renderStageReportHtml(normalized, text));
|
|
17
|
+
return { json, markdown, html };
|
|
18
|
+
}
|
|
19
|
+
export function prepareStageReport(report) {
|
|
20
|
+
const normalized = normalizeStageReport(report);
|
|
21
|
+
const json = `${JSON.stringify(normalized, null, 2)}\n`;
|
|
22
|
+
const markdown = renderStageReportMarkdown(normalized);
|
|
23
|
+
const html = renderStageReportHtml(normalized, markdown);
|
|
24
|
+
return { normalized, bytes: { json, markdown, html }, sha256: crypto.createHash("sha256").update(json).digest("hex") };
|
|
25
|
+
}
|
|
26
|
+
export function prepareStagePacket(file, bytes) {
|
|
27
|
+
if (fs.existsSync(file) && !bytes.equals(fs.readFileSync(file)))
|
|
28
|
+
throw new AppError("stage_packet_conflict", "An existing Stage packet differs from prepared bytes", 2, { file });
|
|
29
|
+
return { file, bytes, sha256: crypto.createHash("sha256").update(bytes).digest("hex") };
|
|
30
|
+
}
|
|
31
|
+
export function acceptStagePacket(context, input) {
|
|
32
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [input.projectId, input.runId]);
|
|
33
|
+
const index = run ? JSON.parse(run.index_json) : null;
|
|
34
|
+
const attempt = index?.stage_runs?.find((item) => item.stage === input.stage)?.attempt;
|
|
35
|
+
if (!attempt)
|
|
36
|
+
throw new AppError("stage_packet_owner_missing", "Stage packet has no owning attempt", 1, { run_id: input.runId, stage: input.stage });
|
|
37
|
+
const payload = { run_id: input.runId, stage: input.stage, attempt, file: input.prepared.file, sha256: input.prepared.sha256, base64: input.prepared.bytes.toString("base64") };
|
|
38
|
+
context.db.run("INSERT INTO audit_events (project_id, event_type, forced, payload_json, created_at) VALUES (?, 'flow_run.stage_packet', 0, ?, ?)", [input.projectId, JSON.stringify(payload), context.now()]);
|
|
39
|
+
context.db.afterCommit(() => publishStagePacket(context, input.projectId, input.runId, input.stage, input.prepared.file));
|
|
40
|
+
}
|
|
41
|
+
export function publishStagePacket(context, projectId, runId, stage, file) {
|
|
42
|
+
file = resolveStagePublicationPath(context, projectId, runId, file);
|
|
43
|
+
assertPublicationPath(context, projectId, runId, file);
|
|
44
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
45
|
+
withProjectionLock(`${file}.publish-lock`, () => {
|
|
46
|
+
assertPublicationPath(context, projectId, runId, file);
|
|
47
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
48
|
+
const index = run ? JSON.parse(run.index_json) : null;
|
|
49
|
+
const currentAttempt = index?.stage_runs?.find((item) => item.stage === stage)?.attempt;
|
|
50
|
+
const rows = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.stage_packet' ORDER BY id DESC", [projectId]);
|
|
51
|
+
const packet = rows.map((row) => JSON.parse(row.payload_json)).find((item) => item.run_id === runId && item.stage === stage && item.attempt === currentAttempt && resolveStagePublicationPath(context, projectId, runId, item.file) === file);
|
|
52
|
+
if (!packet)
|
|
53
|
+
return;
|
|
54
|
+
const bytes = Buffer.from(packet.base64, "base64");
|
|
55
|
+
if (crypto.createHash("sha256").update(bytes).digest("hex") !== packet.sha256)
|
|
56
|
+
throw new AppError("stage_packet_invalid", "Stored Stage packet hash does not match its bytes", 1, { file });
|
|
57
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
58
|
+
try {
|
|
59
|
+
fs.writeFileSync(file, bytes, { flag: "wx" });
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code !== "EEXIST")
|
|
63
|
+
throw error;
|
|
64
|
+
if (!bytes.equals(fs.readFileSync(file)))
|
|
65
|
+
throw new AppError("stage_packet_conflict", "Accepted Stage packet differs from the published file", 1, { file, run_id: runId, stage, attempt: currentAttempt });
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/** SQL receipt and exact bytes are committed with the owning Stage transition. */
|
|
70
|
+
export function acceptStageReport(context, input) {
|
|
71
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [input.projectId, input.runId]);
|
|
72
|
+
const index = run ? JSON.parse(run.index_json) : null;
|
|
73
|
+
const attempt = index?.stage_runs?.find((item) => item.stage === input.stage)?.attempt;
|
|
74
|
+
if (!attempt)
|
|
75
|
+
throw new AppError("stage_report_owner_missing", "Stage report has no owning attempt", 1, { run_id: input.runId, stage: input.stage });
|
|
76
|
+
const payload = { run_id: input.runId, stage: input.stage, attempt, root: input.root, sha256: input.prepared.sha256, bytes: input.prepared.bytes };
|
|
77
|
+
context.db.run("INSERT INTO audit_events (project_id, event_type, forced, payload_json, created_at) VALUES (?, 'flow_run.stage_report', 0, ?, ?)", [input.projectId, JSON.stringify(payload), context.now()]);
|
|
78
|
+
context.db.afterCommit(() => publishStageReport(context, input.projectId, input.runId, input.stage, input.root));
|
|
79
|
+
}
|
|
80
|
+
/** Replays the latest committed receipt, never an obsolete attempt. */
|
|
81
|
+
export function publishStageReport(context, projectId, runId, stage, root) {
|
|
82
|
+
root = resolveStagePublicationPath(context, projectId, runId, root);
|
|
83
|
+
assertPublicationPath(context, projectId, runId, root);
|
|
84
|
+
withProjectionLock(`${root}.report-publish-lock`, () => {
|
|
85
|
+
assertPublicationPath(context, projectId, runId, root);
|
|
86
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
87
|
+
const index = run ? JSON.parse(run.index_json) : null;
|
|
88
|
+
const currentAttempt = index?.stage_runs?.find((item) => item.stage === stage)?.attempt;
|
|
89
|
+
const events = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.stage_report' ORDER BY id DESC", [projectId]);
|
|
90
|
+
const receipt = events.map((row) => JSON.parse(row.payload_json)).find((item) => item.run_id === runId && item.stage === stage && item.attempt === currentAttempt && resolveStagePublicationPath(context, projectId, runId, item.root) === root);
|
|
91
|
+
if (!receipt)
|
|
92
|
+
return;
|
|
93
|
+
fs.mkdirSync(root, { recursive: true });
|
|
94
|
+
for (const [name, bytes] of Object.entries(receipt.bytes)) {
|
|
95
|
+
const file = path.join(root, `stage-report.${name === "json" ? "json" : name === "markdown" ? "md" : "html"}`);
|
|
96
|
+
assertPublicationPath(context, projectId, runId, file);
|
|
97
|
+
try {
|
|
98
|
+
fs.writeFileSync(file, bytes, { flag: "wx" });
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (error.code !== "EEXIST")
|
|
102
|
+
throw error;
|
|
103
|
+
if (fs.readFileSync(file, "utf8") !== bytes)
|
|
104
|
+
throw new AppError("stage_report_conflict", "Accepted Stage report differs from the published file", 1, { run_id: runId, stage, attempt: currentAttempt, file });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** Operational destinations follow validated imports, while audit bytes retain
|
|
110
|
+
* their original locators. SQL-only so readers may also use it in settlement. */
|
|
111
|
+
export function resolveStagePublicationPath(context, projectId, runId, locator) {
|
|
112
|
+
const run = context.db.get("SELECT run_root FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
113
|
+
if (!run?.run_root || !path.isAbsolute(locator))
|
|
114
|
+
throw new AppError("stage_packet_invalid", "Stage publication has no absolute bound RUN locator", 1, { run_id: runId, locator });
|
|
115
|
+
let destination = path.resolve(locator);
|
|
116
|
+
const mappings = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.publication_relocation' ORDER BY id", [projectId]);
|
|
117
|
+
for (const row of mappings) {
|
|
118
|
+
const mapping = JSON.parse(row.payload_json);
|
|
119
|
+
if (mapping.run_id !== runId || !path.isAbsolute(mapping.from) || !path.isAbsolute(mapping.to))
|
|
120
|
+
continue;
|
|
121
|
+
const relative = path.relative(mapping.from, destination);
|
|
122
|
+
if (relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
|
|
123
|
+
destination = path.resolve(mapping.to, relative);
|
|
124
|
+
}
|
|
125
|
+
const relative = path.relative(run.run_root, destination);
|
|
126
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
|
|
127
|
+
throw new AppError("publication_pending", "Stage publication escaped its bound RUN lineage", 1, { effect: "committed", run_id: runId, locator });
|
|
128
|
+
return destination;
|
|
129
|
+
}
|
|
130
|
+
/** Recheck the actual destination after preparation: a missing leaf may have
|
|
131
|
+
* an existing symlink ancestor, and retained packet bytes never authorize it. */
|
|
132
|
+
function assertPublicationPath(context, projectId, runId, file) {
|
|
133
|
+
const run = context.db.get("SELECT run_root FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
134
|
+
const root = run?.run_root && path.resolve(run.run_root), destination = path.resolve(file);
|
|
135
|
+
if (!root || !destination.startsWith(`${root}${path.sep}`))
|
|
136
|
+
throw new AppError("publication_pending", "Stage publication escaped its RUN", 1, { effect: "committed", run_id: runId, file });
|
|
137
|
+
let ancestor = destination;
|
|
138
|
+
while (!fs.existsSync(ancestor) && ancestor !== root)
|
|
139
|
+
ancestor = path.dirname(ancestor);
|
|
140
|
+
const actual = fs.realpathSync(ancestor), realRoot = fs.realpathSync(root);
|
|
141
|
+
if (actual !== realRoot && !actual.startsWith(`${realRoot}${path.sep}`))
|
|
142
|
+
throw new AppError("publication_pending", "Stage publication escaped its RUN through a symlink", 1, { effect: "committed", run_id: runId, file });
|
|
143
|
+
}
|
|
144
|
+
/** Admission repair for predecessor reports; the stage being retried is archived separately. */
|
|
145
|
+
export function reconcileRunStageReports(context, projectId, runId, exceptStage) {
|
|
146
|
+
const rows = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.stage_report' ORDER BY id DESC", [projectId]);
|
|
147
|
+
const seen = new Set();
|
|
148
|
+
for (const row of rows) {
|
|
149
|
+
const receipt = JSON.parse(row.payload_json);
|
|
150
|
+
if (receipt.run_id !== runId || typeof receipt.stage !== "string" || typeof receipt.root !== "string" || receipt.stage === exceptStage || seen.has(receipt.stage))
|
|
151
|
+
continue;
|
|
152
|
+
seen.add(receipt.stage);
|
|
153
|
+
publishStageReport(context, projectId, runId, receipt.stage, receipt.root);
|
|
154
|
+
}
|
|
155
|
+
const packets = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.stage_packet' ORDER BY id DESC", [projectId]);
|
|
156
|
+
const packetFiles = new Set();
|
|
157
|
+
for (const row of packets) {
|
|
158
|
+
const packet = JSON.parse(row.payload_json);
|
|
159
|
+
if (packet.run_id !== runId || typeof packet.stage !== "string" || typeof packet.file !== "string" || packet.stage === exceptStage || packetFiles.has(packet.file))
|
|
160
|
+
continue;
|
|
161
|
+
packetFiles.add(packet.file);
|
|
162
|
+
publishStagePacket(context, projectId, runId, packet.stage, packet.file);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function normalizeStageReport(report) {
|
|
9
166
|
const semantic = object(report.semantic);
|
|
10
167
|
const sourceArtifacts = object(report.artifacts);
|
|
11
|
-
|
|
168
|
+
return {
|
|
12
169
|
...report,
|
|
13
170
|
schema_id: "dd-flow/stage-report@2",
|
|
14
171
|
summary: string(report.summary) || string(semantic.result) || "Stage completed.",
|
|
@@ -27,11 +184,6 @@ export function writeStageReport(root, report) {
|
|
|
27
184
|
html: string(sourceArtifacts.html) || "stage-report.html"
|
|
28
185
|
}
|
|
29
186
|
};
|
|
30
|
-
writeJsonAtomic(json, normalized);
|
|
31
|
-
const text = renderStageReportMarkdown(normalized);
|
|
32
|
-
fs.writeFileSync(markdown, text);
|
|
33
|
-
fs.writeFileSync(html, renderStageReportHtml(normalized, text));
|
|
34
|
-
return { json, markdown, html };
|
|
35
187
|
}
|
|
36
188
|
export function renderStageReportMarkdown(report) {
|
|
37
189
|
const semantic = object(report.semantic);
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { AppError } from "../shared/errors.js";
|
|
2
|
+
export function stageAttempt(context, projectId, runId, stage) {
|
|
3
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
4
|
+
if (!run)
|
|
5
|
+
throw new AppError("not_found", "Stage graph RUN is unavailable", 1);
|
|
6
|
+
const stages = JSON.parse(run.index_json).stage_runs ?? [];
|
|
7
|
+
return [...stages].reverse().find(item => item.stage === stage)?.attempt ?? "try-001";
|
|
8
|
+
}
|
|
9
|
+
export function bindStageWork(context, input) {
|
|
10
|
+
context.db.run("INSERT OR IGNORE INTO stage_work_memberships (project_id, run_id, work_id, stage, attempt, cycle) VALUES (?, ?, ?, ?, ?, ?)", [input.projectId, input.runId, input.workId, input.stage, input.attempt ?? stageAttempt(context, input.projectId, input.runId, input.stage), input.cycle ?? stageCycle(context, input.projectId, input.runId, input.stage)]);
|
|
11
|
+
}
|
|
12
|
+
export function stageCycle(context, projectId, runId, stage) {
|
|
13
|
+
if (stage !== "code" && stage !== "code-review")
|
|
14
|
+
return "";
|
|
15
|
+
const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
16
|
+
const cycle = row ? JSON.parse(row.index_json).variables?.["merge.source_repair"]?.cycle : undefined;
|
|
17
|
+
return typeof cycle === "string" ? cycle : stage === "code-review" ? "initial" : "";
|
|
18
|
+
}
|
|
19
|
+
export function stageWorkIds(context, projectId, runId, stage) {
|
|
20
|
+
if (!context.db.get("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'stage_work_memberships'"))
|
|
21
|
+
throw new AppError("stage_graph_compatibility_required", "Stage Work membership is unavailable; use the RUN's pinned engine", 1);
|
|
22
|
+
return new Set(context.db.all("SELECT work_id FROM stage_work_memberships WHERE project_id = ? AND run_id = ? AND stage = ? AND attempt = ? AND cycle = ?", [projectId, runId, stage, stageAttempt(context, projectId, runId, stage), stageCycle(context, projectId, runId, stage)]).map(row => row.work_id));
|
|
23
|
+
}
|
|
24
|
+
/** Generic Work APIs also serve non-stage runs; null preserves that contract. */
|
|
25
|
+
export function currentStageWorkIds(context, projectId, runId) {
|
|
26
|
+
const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
27
|
+
if (!row)
|
|
28
|
+
return null;
|
|
29
|
+
const index = JSON.parse(row.index_json);
|
|
30
|
+
const stage = [...(index.stage_runs ?? [])].reverse().find(item => item.status === "running")?.stage;
|
|
31
|
+
return stage ? stageWorkIds(context, projectId, runId, stage) : null;
|
|
32
|
+
}
|
|
33
|
+
export function stageGraphScope(context, projectId, runId, stage) {
|
|
34
|
+
return { project_id: projectId, run_id: runId, attempt: stageAttempt(context, projectId, runId, stage), cycle: stageCycle(context, projectId, runId, stage) };
|
|
35
|
+
}
|
package/dist/services/tooling.js
CHANGED
|
@@ -2,7 +2,8 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import {
|
|
5
|
+
import { commandResult, commandText } from '../harness-runtime/lib/process-json.mjs';
|
|
6
|
+
import { publishSetup, SETUP_STARTUP_MS } from '../harness-runtime/lib/setup-progress.mjs';
|
|
6
7
|
import { AppError } from "../shared/errors.js";
|
|
7
8
|
import { ensureDir } from "../storage/paths.js";
|
|
8
9
|
const manifestRelativePath = path.join("tools", "worktrunk-manifest.json");
|
|
@@ -71,7 +72,7 @@ export function inspectManagedWorktrunk(context) {
|
|
|
71
72
|
};
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
|
-
export function ensureManagedWorktrunk(context) {
|
|
75
|
+
export async function ensureManagedWorktrunk(context) {
|
|
75
76
|
const manifest = worktrunkManifest();
|
|
76
77
|
const platform = worktrunkPlatform();
|
|
77
78
|
const cachedRoot = worktrunkCacheRoot(context, platform);
|
|
@@ -92,14 +93,14 @@ export function ensureManagedWorktrunk(context) {
|
|
|
92
93
|
next_action: "Place the verified official artifact in the managed tool cache and retry."
|
|
93
94
|
});
|
|
94
95
|
}
|
|
95
|
-
installWorktrunkArtifact(manifest, platform, cachedRoot);
|
|
96
|
+
await installWorktrunkArtifact(manifest, platform, cachedRoot);
|
|
96
97
|
return verifyCachedWorktrunk(context, manifest, platform);
|
|
97
98
|
}
|
|
98
99
|
finally {
|
|
99
100
|
fs.rmSync(lockDir, { recursive: true, force: true });
|
|
100
101
|
}
|
|
101
102
|
}
|
|
102
|
-
function installWorktrunkArtifact(manifest, platform, targetRoot) {
|
|
103
|
+
async function installWorktrunkArtifact(manifest, platform, targetRoot) {
|
|
103
104
|
const artifact = artifactFor(manifest, platform);
|
|
104
105
|
const parent = path.dirname(targetRoot);
|
|
105
106
|
ensureDir(parent);
|
|
@@ -107,8 +108,17 @@ function installWorktrunkArtifact(manifest, platform, targetRoot) {
|
|
|
107
108
|
const archivePath = path.join(tempRoot, `worktrunk.${artifact.archive}`);
|
|
108
109
|
const extractedRoot = path.join(tempRoot, "extracted");
|
|
109
110
|
try {
|
|
110
|
-
|
|
111
|
-
|
|
111
|
+
let observedBytes = 0;
|
|
112
|
+
publishSetup('probe_started', 'worktrunk-download');
|
|
113
|
+
const download = await commandResult("curl", ["--fail", "--location", "--silent", "--show-error", "-o", archivePath, artifact.url], { startupMs: SETUP_STARTUP_MS, progress: () => {
|
|
114
|
+
const bytes = fs.existsSync(archivePath) ? fs.statSync(archivePath).size : 0;
|
|
115
|
+
if (bytes > observedBytes) {
|
|
116
|
+
observedBytes = bytes;
|
|
117
|
+
publishSetup('transfer_progress', `worktrunk-transfer:${bytes}`);
|
|
118
|
+
}
|
|
119
|
+
return observedBytes;
|
|
120
|
+
} });
|
|
121
|
+
if (download.exit_code !== 0) {
|
|
112
122
|
throw new AppError("tool_unavailable", "Unable to download the pinned Worktrunk artifact", 1, {
|
|
113
123
|
tool: manifest.tool,
|
|
114
124
|
version: manifest.version,
|
|
@@ -118,6 +128,7 @@ function installWorktrunkArtifact(manifest, platform, targetRoot) {
|
|
|
118
128
|
stderr: sanitize(download.stderr)
|
|
119
129
|
});
|
|
120
130
|
}
|
|
131
|
+
publishSetup('probe_completed', 'worktrunk-download');
|
|
121
132
|
const archiveChecksum = sha256File(archivePath);
|
|
122
133
|
if (archiveChecksum !== artifact.sha256) {
|
|
123
134
|
throw new AppError("tool_integrity_failed", "Pinned Worktrunk artifact checksum mismatch", 1, {
|
|
@@ -129,12 +140,12 @@ function installWorktrunkArtifact(manifest, platform, targetRoot) {
|
|
|
129
140
|
});
|
|
130
141
|
}
|
|
131
142
|
ensureDir(extractedRoot);
|
|
132
|
-
extractArchive(archivePath, extractedRoot, artifact.archive);
|
|
143
|
+
await extractArchive(archivePath, extractedRoot, artifact.archive);
|
|
133
144
|
const extractedBinary = findBinary(extractedRoot);
|
|
134
145
|
if (!extractedBinary)
|
|
135
146
|
throw new AppError("tool_integrity_failed", "Pinned Worktrunk archive does not contain wt", 1, { platform });
|
|
136
147
|
fs.chmodSync(extractedBinary, 0o755);
|
|
137
|
-
verifyWorktrunkVersion(extractedBinary, manifest.version);
|
|
148
|
+
await verifyWorktrunkVersion(extractedBinary, manifest.version);
|
|
138
149
|
const binaryChecksum = sha256File(extractedBinary);
|
|
139
150
|
const stagedRoot = path.join(tempRoot, "managed");
|
|
140
151
|
ensureDir(stagedRoot);
|
|
@@ -186,7 +197,7 @@ function verifyCachedWorktrunk(context, manifest, platform) {
|
|
|
186
197
|
actual_binary_sha256: actualBinaryChecksum
|
|
187
198
|
});
|
|
188
199
|
}
|
|
189
|
-
|
|
200
|
+
// The admitted binary checksum binds the version probe performed at install.
|
|
190
201
|
return {
|
|
191
202
|
bin,
|
|
192
203
|
version: manifest.version,
|
|
@@ -195,23 +206,23 @@ function verifyCachedWorktrunk(context, manifest, platform) {
|
|
|
195
206
|
binary_sha256: actualBinaryChecksum
|
|
196
207
|
};
|
|
197
208
|
}
|
|
198
|
-
function extractArchive(archive, destination, format) {
|
|
209
|
+
async function extractArchive(archive, destination, format) {
|
|
199
210
|
if (format === "tar.xz") {
|
|
200
|
-
const listing =
|
|
201
|
-
if (listing.
|
|
211
|
+
const listing = await commandResult("tar", ["-tJf", archive], { startupMs: SETUP_STARTUP_MS });
|
|
212
|
+
if (listing.exit_code !== 0 || listing.stdout.split("\n").some(unsafeArchivePath)) {
|
|
202
213
|
throw new AppError("tool_integrity_failed", "Pinned Worktrunk archive has an unsafe or unreadable file list", 1);
|
|
203
214
|
}
|
|
204
|
-
const extracted =
|
|
205
|
-
if (extracted.
|
|
215
|
+
const extracted = await commandResult("tar", ["-xJvf", archive, "-C", destination], { startupMs: SETUP_STARTUP_MS });
|
|
216
|
+
if (extracted.exit_code !== 0)
|
|
206
217
|
throw new AppError("tool_integrity_failed", "Pinned Worktrunk archive extraction failed", 1, { stderr: sanitize(extracted.stderr) });
|
|
207
218
|
return;
|
|
208
219
|
}
|
|
209
|
-
const listing =
|
|
210
|
-
if (listing.
|
|
220
|
+
const listing = await commandResult("unzip", ["-Z1", archive], { startupMs: SETUP_STARTUP_MS });
|
|
221
|
+
if (listing.exit_code !== 0 || listing.stdout.split("\n").some(unsafeArchivePath)) {
|
|
211
222
|
throw new AppError("tool_integrity_failed", "Pinned Worktrunk archive has an unsafe or unreadable file list", 1);
|
|
212
223
|
}
|
|
213
|
-
const extracted =
|
|
214
|
-
if (extracted.
|
|
224
|
+
const extracted = await commandResult("unzip", [archive, "-d", destination], { startupMs: SETUP_STARTUP_MS });
|
|
225
|
+
if (extracted.exit_code !== 0)
|
|
215
226
|
throw new AppError("tool_integrity_failed", "Pinned Worktrunk archive extraction failed", 1, { stderr: sanitize(extracted.stderr) });
|
|
216
227
|
}
|
|
217
228
|
function findBinary(root) {
|
|
@@ -229,13 +240,11 @@ function findBinary(root) {
|
|
|
229
240
|
}
|
|
230
241
|
return null;
|
|
231
242
|
}
|
|
232
|
-
function verifyWorktrunkVersion(bin, expected) {
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
if (result.status !== 0 || !output.includes(expected)) {
|
|
243
|
+
async function verifyWorktrunkVersion(bin, expected) {
|
|
244
|
+
const output = await commandText(bin, ['--version'], { startupMs: SETUP_STARTUP_MS, phase: 'native-version' });
|
|
245
|
+
if (!output.includes(expected)) {
|
|
236
246
|
throw new AppError("tool_integrity_failed", "Managed Worktrunk version verification failed", 1, {
|
|
237
247
|
expected_version: expected,
|
|
238
|
-
status: result.status,
|
|
239
248
|
output: sanitize(output)
|
|
240
249
|
});
|
|
241
250
|
}
|