@deksden-com/dd-flow-cli 0.9.0-beta.9 → 0.9.0-beta.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +467 -0
  2. package/README.md +65 -0
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/command-inputs.js +305 -0
  5. package/dist/cli/help.js +89 -13
  6. package/dist/cli/hook-ingress.js +82 -0
  7. package/dist/cli/input-preparation.js +116 -0
  8. package/dist/cli/run-cli.js +1421 -384
  9. package/dist/cli.js +6 -2
  10. package/dist/harness-runtime/bin/dd-agy.mjs +37 -0
  11. package/dist/harness-runtime/bin/dd-codex.mjs +25 -0
  12. package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
  13. package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
  14. package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
  15. package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
  16. package/dist/harness-runtime/lib/daemon-operations.mjs +215 -0
  17. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +423 -0
  18. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  19. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  20. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +146 -0
  21. package/dist/harness-runtime/lib/dd-codex.mjs +562 -0
  22. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
  23. package/dist/harness-runtime/lib/dd-droid.mjs +471 -0
  24. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +274 -0
  25. package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
  26. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +198 -0
  27. package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
  28. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +644 -0
  29. package/dist/harness-runtime/lib/dd-zcode.mjs +910 -0
  30. package/dist/harness-runtime/lib/delegation-instructions.d.mts +10 -0
  31. package/dist/harness-runtime/lib/delegation-instructions.mjs +130 -0
  32. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  33. package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
  34. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  35. package/dist/harness-runtime/lib/managed-daemon.mjs +260 -0
  36. package/dist/harness-runtime/lib/model-observations.mjs +77 -0
  37. package/dist/harness-runtime/lib/native-hook-command.d.mts +1 -0
  38. package/dist/harness-runtime/lib/native-hook-command.mjs +34 -0
  39. package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
  40. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  41. package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
  42. package/dist/harness-runtime/lib/process-json.mjs +70 -0
  43. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  44. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  45. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  46. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  47. package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
  48. package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
  49. package/dist/schemas/agent-profile.schema.json +1 -1
  50. package/dist/schemas/code-review-result.schema.json +2 -2
  51. package/dist/schemas/code-work-batch.schema.json +4 -3
  52. package/dist/schemas/code-work-result.schema.json +4 -4
  53. package/dist/schemas/plan-review-result.schema.json +2 -2
  54. package/dist/schemas/run-control-receipt.schema.json +99 -0
  55. package/dist/schemas/run-control-request.schema.json +36 -0
  56. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  57. package/dist/services/canon.js +11 -8
  58. package/dist/services/cleanup.js +57 -13
  59. package/dist/services/cli-operation-classifier.js +22 -24
  60. package/dist/services/code-checks.js +543 -96
  61. package/dist/services/codex-hook-delivery.js +28 -0
  62. package/dist/services/command-context.js +80 -0
  63. package/dist/services/config.js +11 -8
  64. package/dist/services/continuation-outcome.js +20 -0
  65. package/dist/services/controller-fanout.js +132 -0
  66. package/dist/services/dashboard.js +103 -31
  67. package/dist/services/engines.js +121 -76
  68. package/dist/services/eval-snapshots.js +750 -73
  69. package/dist/services/execution-policy.js +170 -0
  70. package/dist/services/external-work-launch.js +110 -0
  71. package/dist/services/harness-adapter.js +147 -24
  72. package/dist/services/harness-config.js +2 -0
  73. package/dist/services/hooks.js +587 -299
  74. package/dist/services/lanes.js +61 -53
  75. package/dist/services/lifecycle-command.js +103 -17
  76. package/dist/services/lifecycle-contract.js +30 -0
  77. package/dist/services/lifecycle-invocations.js +1122 -0
  78. package/dist/services/managed-daemon-binding.js +38 -0
  79. package/dist/services/managed-processes.js +283 -27
  80. package/dist/services/merge-queue.js +179 -104
  81. package/dist/services/merge-server.js +73 -28
  82. package/dist/services/migrations.js +14 -9
  83. package/dist/services/native-daemon-history.js +49 -0
  84. package/dist/services/native-session-control.js +39 -0
  85. package/dist/services/plan-runtime.js +19 -8
  86. package/dist/services/plans.js +28 -25
  87. package/dist/services/projects.js +18 -5
  88. package/dist/services/prompts.js +23 -16
  89. package/dist/services/protocols.js +64 -20
  90. package/dist/services/recovery-observation-budget.js +61 -0
  91. package/dist/services/recovery-snapshot-database.js +107 -0
  92. package/dist/services/repair-intents.js +40 -0
  93. package/dist/services/run-control-receipt.js +56 -0
  94. package/dist/services/run-control-worker.js +363 -0
  95. package/dist/services/run-control.js +876 -0
  96. package/dist/services/run-controller-adapter.js +222 -0
  97. package/dist/services/run-controller-capture.js +134 -0
  98. package/dist/services/run-controller-process.js +189 -0
  99. package/dist/services/run-controller-recovery.js +222 -0
  100. package/dist/services/run-controller-state.js +36 -0
  101. package/dist/services/run-controller.js +793 -0
  102. package/dist/services/run-engine-bindings.js +1 -1
  103. package/dist/services/run-fork.js +138 -0
  104. package/dist/services/run-observations.js +112 -0
  105. package/dist/services/run-recovery-runtime.js +69 -0
  106. package/dist/services/run-recovery.js +343 -0
  107. package/dist/services/runs.js +368 -74
  108. package/dist/services/runtime-budget.js +434 -0
  109. package/dist/services/runtime-command.js +43 -0
  110. package/dist/services/runtime-scope-capture.js +50 -0
  111. package/dist/services/runtime-scope-control.js +450 -0
  112. package/dist/services/runtime-scope-resume.js +565 -0
  113. package/dist/services/runtime-scope-stop.js +99 -0
  114. package/dist/services/runtime-scope-worker.js +243 -0
  115. package/dist/services/runtime-service.js +97 -0
  116. package/dist/services/schema-validation.js +10 -8
  117. package/dist/services/sessions.js +35 -69
  118. package/dist/services/stage-blocker.js +17 -7
  119. package/dist/services/stage-context.js +44 -18
  120. package/dist/services/stage-lifecycle.js +99 -102
  121. package/dist/services/stage-pause.js +84 -55
  122. package/dist/services/stage-work-graph.js +35 -0
  123. package/dist/services/usage.js +37 -93
  124. package/dist/services/vnext-code-review.js +195 -88
  125. package/dist/services/vnext-code.js +285 -252
  126. package/dist/services/vnext-execution-profile.js +5 -3
  127. package/dist/services/vnext-fanout.js +160 -17
  128. package/dist/services/vnext-merge.js +291 -104
  129. package/dist/services/vnext-plan-review.js +139 -81
  130. package/dist/services/vnext-plan.js +138 -69
  131. package/dist/services/vnext-protocolize.js +129 -56
  132. package/dist/services/vnext-specify.js +88 -65
  133. package/dist/services/work-registry.js +716 -168
  134. package/dist/services/workspace-bootstrap.js +76 -0
  135. package/dist/services/worktrees.js +85 -35
  136. package/dist/shared/entity-references.js +8 -0
  137. package/dist/shared/errors.js +12 -0
  138. package/dist/storage/database.js +459 -32
  139. package/dist/storage/paths.js +17 -4
  140. package/dist/storage/work-references.js +23 -0
  141. package/dist/storage/writer-contract.js +77 -0
  142. package/dist/storage/writer-migration.js +102 -0
  143. package/package.json +24 -13
  144. package/tools/repair-paused-run-status.mjs +59 -0
@@ -0,0 +1,76 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { AppError } from "../shared/errors.js";
5
+ import { assertRunMutationAllowed } from "./run-recovery.js";
6
+ import { codeExecutionEnvironment, reconcileWorkspaceOwnership, runCheck, workspaceOperationId } from "./code-checks.js";
7
+ import { confirmManagedProcess, finishManagedProcess, heartbeatManagedProcess, managedOwnerIsAlive, managedProcessStatus, processTreeIsAlive, registerManagedProcess } from "./managed-processes.js";
8
+ /** CODE and MERGE prepare their own checkout through the same managed executor.
9
+ * Bootstrap is a project operation, not an alias classified by the engine as a test. */
10
+ export async function runWorkspaceBootstrap(context, input) {
11
+ reconcileWorkspaceOwnership(context, input.workspaceRoot);
12
+ const generation = assertRunMutationAllowed(context, input.projectId, input.runId);
13
+ const operationId = workspaceOperationId(input.workspaceRoot);
14
+ const identity = crypto.createHash("sha256").update(JSON.stringify([input.projectId, input.runId, generation, path.resolve(input.workspaceRoot), input.command])).digest("hex");
15
+ const pending = managedProcessStatus(context).find(item => item.operation_id === operationId && ["starting", "running", "stopping"].includes(item.state));
16
+ if (pending) {
17
+ if (pending.kind !== "workspace-bootstrap")
18
+ throw new AppError("bootstrap_in_progress", "A check currently owns this workspace; wait for it before bootstrapping", 2, { process_id: pending.id, stdout_path: pending.stdout_path, stderr_path: pending.stderr_path });
19
+ if (processTreeIsAlive(pending) || (pending.state === "starting" && managedOwnerIsAlive(pending) !== false)) {
20
+ throw new AppError("bootstrap_in_progress", "Workspace preparation is still running; inspect its logs and wait for the existing process, do not launch another copy", 2, { process_id: pending.id, stdout_path: pending.stdout_path, stderr_path: pending.stderr_path });
21
+ }
22
+ let pendingIdentity = null;
23
+ try {
24
+ const metadata = JSON.parse(pending.metadata_json);
25
+ pendingIdentity = typeof metadata.bootstrap_identity === "string" ? metadata.bootstrap_identity : null;
26
+ }
27
+ catch { /* Legacy records have no usable identity. */ }
28
+ if (pendingIdentity !== identity) {
29
+ finishManagedProcess(context, { id: pending.id, leaseToken: pending.lease_token, state: "failed", reason: "bootstrap_identity_superseded" });
30
+ }
31
+ else {
32
+ const completionPath = path.join(path.dirname(pending.stdout_path), "completion.json");
33
+ let completion = null;
34
+ try {
35
+ completion = JSON.parse(fs.readFileSync(completionPath, "utf8"));
36
+ }
37
+ catch { /* Interrupted shell has no terminal marker. */ }
38
+ const exitCode = typeof completion?.exit_code === "number" ? completion.exit_code : null;
39
+ const error = exitCode === null ? "bootstrap ended without a completion marker; inspect retained logs before retrying" : null;
40
+ finishManagedProcess(context, { id: pending.id, leaseToken: pending.lease_token, state: exitCode === 0 ? "stopped" : "failed", reason: error ?? "bootstrap_completion_reconciled" });
41
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
42
+ return result(pending.id, pending.stdout_path, pending.stderr_path, completionPath, exitCode, error);
43
+ }
44
+ }
45
+ const directory = path.join(input.runHome, input.artifactDir, `bootstrap-${crypto.randomUUID()}`);
46
+ fs.mkdirSync(directory, { recursive: true });
47
+ const stdoutPath = path.join(directory, "stdout.log"), stderrPath = path.join(directory, "stderr.log"), completionPath = path.join(directory, "completion.json");
48
+ const managed = registerManagedProcess(context, { kind: "workspace-bootstrap", ownerId: `${operationId}:${identity}`, ownerPid: process.pid, operationId, uniqueActiveOperation: true, projectId: input.projectId, runId: input.runId, stdoutPath, stderrPath, metadata: { command: input.command, workspace_root: input.workspaceRoot, bootstrap_identity: identity } });
49
+ const stdout = fs.openSync(stdoutPath, "a"), stderr = fs.openSync(stderrPath, "a");
50
+ try {
51
+ try {
52
+ input.progress?.(`workspace bootstrap preparing: ${input.command}; logs: ${directory}`);
53
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
54
+ }
55
+ catch (error) {
56
+ finishManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, state: "failed", reason: "dispatch_fenced_before_spawn" });
57
+ throw error;
58
+ }
59
+ const completed = await runCheck(input.command, input.workspaceRoot, { ...codeExecutionEnvironment(input.workspaceRoot), DD_FLOW_CHECK_COMPLETION_FILE: completionPath }, stdout, stderr, elapsed => input.progress?.(`workspace bootstrap still running (${elapsed}s); logs: ${directory}; next report in 15s`), pid => confirmManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, pid, processGroupId: process.platform === "win32" ? null : pid }), () => heartbeatManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token }));
60
+ const current = managedProcessStatus(context).find(item => item.id === managed.id);
61
+ if (processTreeIsAlive(current))
62
+ throw new AppError("bootstrap_tree_not_settled", "Bootstrap shell exited but still owns live processes; resources were retained for inspection", 2, { process_id: managed.id, stdout_path: stdoutPath, stderr_path: stderrPath });
63
+ assertRunMutationAllowed(context, input.projectId, input.runId, generation);
64
+ finishManagedProcess(context, { id: managed.id, leaseToken: managed.lease_token, state: completed.exitCode === 0 && !completed.error ? "stopped" : "failed", reason: completed.error });
65
+ return result(managed.id, stdoutPath, stderrPath, completionPath, completed.exitCode, completed.error);
66
+ }
67
+ finally {
68
+ fs.closeSync(stdout);
69
+ fs.closeSync(stderr);
70
+ }
71
+ }
72
+ function result(id, stdout, stderr, completion, exitCode, error) {
73
+ // Full logs remain on disk; keep the returned prompt bounded.
74
+ const excerpt = (file) => fs.existsSync(file) ? fs.readFileSync(file, "utf8").slice(-64_000) : "";
75
+ return { exit_code: exitCode, stdout: excerpt(stdout), stderr: excerpt(stderr), error, process_id: id, stdout_path: stdout, stderr_path: stderr, completion_path: completion };
76
+ }
@@ -4,7 +4,7 @@ import { spawnSync } from "node:child_process";
4
4
  import { flowContractForState } from "../domain/flow-contract.js";
5
5
  import { requireStage } from "../domain/validation.js";
6
6
  import { AppError } from "../shared/errors.js";
7
- import { projectCheckoutRoot, resolveProjectRoot } from "../storage/paths.js";
7
+ import { canonicalPath, projectCheckoutRoot, resolveProjectRoot } from "../storage/paths.js";
8
8
  import { appendAudit } from "./audit.js";
9
9
  import { persistProtocolState, readProtocolRuntimeState, requireProtocol } from "./protocols.js";
10
10
  import { requireProjectByRoot } from "./projects.js";
@@ -28,7 +28,7 @@ export function planWorktree(context, input) {
28
28
  worktrunk: inspectManagedWorktrunk(context)
29
29
  };
30
30
  }
31
- export function createWorktreeRecord(context, input) {
31
+ export function prepareWorktreeCreate(context, input) {
32
32
  const protocol = scopedProtocol(context, input.projectRoot, input.protocolId);
33
33
  const existing = activeWorktreeRecord(context, protocol.project_id, protocol.id);
34
34
  if (existing) {
@@ -37,17 +37,56 @@ export function createWorktreeRecord(context, input) {
37
37
  worktree_path: existing.worktree_path
38
38
  });
39
39
  }
40
- const created = createManagedWorktree(context, { projectRoot: protocol.project_root, branch: input.branch, base: input.base, path: input.path });
41
- recordManagedWorktree(context, { protocolId: protocol.id, projectRoot: protocol.project_root, branch: input.branch, base: input.base, created });
40
+ return prepareManagedWorktree({ ...input, projectRoot: protocol.project_root });
41
+ }
42
+ export function createWorktreeRecord(context, input, prepared = prepareWorktreeCreate(context, input)) {
43
+ const protocol = scopedProtocol(context, input.projectRoot, input.protocolId);
44
+ if (activeWorktreeRecord(context, protocol.project_id, protocol.id))
45
+ throw new AppError("worktree_already_exists", "Protocol already has an active worktree record", 1);
46
+ const created = createManagedWorktree(context, prepared, prepared);
47
+ recordManagedWorktree(context, { protocolId: protocol.id, projectRoot: protocol.project_root, branch: prepared.branch, base: prepared.base, created });
42
48
  return { ok: true, worktree: activeWorktreeRecord(context, protocol.project_id, protocol.id) };
43
49
  }
44
- /** Creates the checkout before a PRT exists. PROTOCOLIZE materializes the PRT only inside this checkout. */
45
- export function createManagedWorktree(context, input) {
50
+ export function prepareManagedWorktree(input) {
46
51
  const projectRoot = resolveProjectRoot(input.projectRoot);
52
+ const invalid = (message) => { throw new AppError("validation", message, 2, { phase: "prepare", effect: "no_effect", recoverable: true }); };
53
+ for (const key of ["branch", "base", "path"])
54
+ if (typeof input[key] !== "string" || !input[key].trim() || input[key].includes("\0"))
55
+ invalid(`--${key} must be a non-empty value without NUL`);
56
+ const git = (args) => {
57
+ const result = spawnSync("git", ["-C", projectRoot, ...args], { encoding: "utf8", env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } });
58
+ if (result.error)
59
+ throw result.error;
60
+ return result;
61
+ };
62
+ const branch = git(["check-ref-format", "--branch", input.branch]);
63
+ if (input.branch.startsWith("-") || branch.status !== 0 || branch.stdout.trim() !== input.branch)
64
+ invalid("--branch must be a literal valid Git branch name");
65
+ const base = git(["rev-parse", "--verify", "--end-of-options", `${input.base}^{commit}`]);
66
+ if (base.status !== 0)
67
+ invalid("--base must resolve to an existing Git commit");
68
+ if (git(["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`]).status === 0)
69
+ invalid("--branch already exists; choose a new feature branch");
70
+ const destination = canonicalPath(input.path, false);
71
+ if (isTrackedProjectPath(canonicalPath(projectRoot), destination))
72
+ invalid("--path must be outside the project checkout");
73
+ if (fs.existsSync(destination) && (!fs.statSync(destination).isDirectory() || fs.readdirSync(destination).length))
74
+ invalid("--path must be an absent or empty directory");
75
+ let parent = path.dirname(destination);
76
+ while (!fs.existsSync(parent) && path.dirname(parent) !== parent)
77
+ parent = path.dirname(parent);
78
+ if (!fs.statSync(parent).isDirectory())
79
+ invalid("--path has a parent that is not a directory");
80
+ fs.accessSync(parent, fs.constants.W_OK | fs.constants.X_OK);
81
+ return { projectRoot, branch: input.branch, base: base.stdout.trim(), path: destination };
82
+ }
83
+ /** Creates the checkout before a PRT exists. PROTOCOLIZE materializes the PRT only inside this checkout. */
84
+ export function createManagedWorktree(context, input, prepared = prepareManagedWorktree(input)) {
85
+ const { projectRoot } = prepared;
47
86
  const worktrunk = ensureManagedWorktrunk(context);
48
87
  // Worktrunk owns creation; the CLI supplies its project-scoped service path
49
88
  // as a one-shot config override rather than relying on a developer's user config.
50
- const command = [worktrunk.bin, "-C", projectRoot, "--config-set", `worktree-path = ${JSON.stringify(path.resolve(input.path))}`, "switch", "--create", input.branch, "--base", input.base, "--no-cd", "--format=json", "-y"];
89
+ const command = [worktrunk.bin, "-C", projectRoot, "--config-set", `worktree-path = ${JSON.stringify(prepared.path)}`, "switch", "--create", prepared.branch, "--base", prepared.base, "--no-cd", "--format=json", "-y"];
51
90
  const result = runExternal(command);
52
91
  if (result.exit_code !== 0)
53
92
  throw new AppError("worktrunk_command_unavailable", "Worktrunk switch failed", 1, { command: sanitizeCommand(command), result });
@@ -76,14 +115,29 @@ export function recordManagedWorktree(context, input) {
76
115
  appendAudit(context, { protocolId: protocol.id, projectId: protocol.project_id, eventType: "worktree.created", payload: { protocol_id: protocol.id, feature_branch: input.branch, base: input.base, path: input.created.worktreePath } });
77
116
  }
78
117
  /** Bootstrap a just-created RUN workspace before a durable PRT exists. */
79
- export function bootstrapManagedWorktree(context, input) {
80
- const projectRoot = resolveProjectRoot(input.projectRoot);
81
- const worktreePath = path.resolve(input.worktreePath);
118
+ export function prepareManagedWorktreeBootstrapSources(root) {
119
+ const projectRoot = resolveProjectRoot(root);
82
120
  const includeFile = path.join(projectRoot, ".worktreeinclude");
83
121
  const configFile = path.join(projectRoot, ".config", "wt.toml");
84
122
  if (!fs.existsSync(includeFile) || !fs.existsSync(configFile)) {
85
123
  throw new AppError("bootstrap_unavailable", "Project-owned Worktrunk bootstrap files are required", 1, { include_file: includeFile, config_file: configFile });
86
124
  }
125
+ for (const file of [includeFile, configFile]) {
126
+ if (!fs.statSync(file).isFile())
127
+ throw new AppError("bootstrap_unavailable", "Project-owned bootstrap inputs must be regular files", 1, { file });
128
+ fs.accessSync(file, fs.constants.R_OK);
129
+ }
130
+ return projectRoot;
131
+ }
132
+ export function prepareManagedWorktreeBootstrap(input) {
133
+ const projectRoot = prepareManagedWorktreeBootstrapSources(input.projectRoot);
134
+ const worktreePath = path.resolve(input.worktreePath);
135
+ if (!fs.statSync(worktreePath).isDirectory())
136
+ throw new AppError("bootstrap_unavailable", "Bootstrap worktree must be a directory", 1, { worktree_path: worktreePath });
137
+ return { projectRoot, worktreePath };
138
+ }
139
+ export function bootstrapManagedWorktree(context, input, prepared = prepareManagedWorktreeBootstrap(input)) {
140
+ const { worktreePath } = prepared;
87
141
  const worktrunk = ensureManagedWorktrunk(context);
88
142
  const commands = [
89
143
  [worktrunk.bin, "-C", worktreePath, "step", "copy-ignored", "--require-include"],
@@ -103,38 +157,30 @@ export function getWorktreeStatus(context, input) {
103
157
  const protocol = scopedProtocol(context, input.projectRoot, input.protocolId);
104
158
  return { ok: true, protocol_id: protocol.id, worktree: worktreeRecord(context, protocol.project_id, protocol.id), worktrunk: inspectManagedWorktrunk(context) };
105
159
  }
106
- export function bootstrapWorktree(context, input) {
160
+ export function prepareWorktreeBootstrap(context, input) {
107
161
  const protocol = scopedProtocol(context, input.projectRoot, input.protocolId);
108
162
  const record = activeWorktreeRecord(context, protocol.project_id, protocol.id);
109
163
  if (!record) {
110
164
  throw new AppError("not_found", `Worktree record is not active for protocol: ${protocol.id}`, 1);
111
165
  }
112
- const includeFile = path.join(protocol.project_root, ".worktreeinclude");
113
- const configFile = path.join(protocol.project_root, ".config", "wt.toml");
114
- if (!fs.existsSync(includeFile) || !fs.existsSync(configFile)) {
115
- throw new AppError("bootstrap_unavailable", "Project-owned Worktrunk bootstrap files are required", 1, {
116
- include_file: includeFile,
117
- config_file: configFile,
118
- next_action: "Add .worktreeinclude and .config/wt.toml before bootstrapping the workspace."
119
- });
166
+ return { protocol, record, managed: prepareManagedWorktreeBootstrap({ projectRoot: protocol.project_root, worktreePath: record.worktree_path }) };
167
+ }
168
+ export function bootstrapWorktree(context, input, prepared = prepareWorktreeBootstrap(context, input)) {
169
+ const { protocol, record } = prepared;
170
+ const active = activeWorktreeRecord(context, protocol.project_id, protocol.id);
171
+ if (!active || active.worktree_path !== record.worktree_path)
172
+ throw new AppError("worktree_active", "Worktree changed after bootstrap preparation", 1);
173
+ let result;
174
+ try {
175
+ result = bootstrapManagedWorktree(context, prepared.managed, prepared.managed);
120
176
  }
121
- const worktrunk = ensureManagedWorktrunk(context);
122
- const commands = [
123
- [worktrunk.bin, "-C", record.worktree_path, "step", "copy-ignored", "--require-include"],
124
- [worktrunk.bin, "-C", record.worktree_path, "hook", "pre-start", "--yes"]
125
- ];
126
- const results = [];
127
- for (const command of commands) {
128
- const result = runExternal(command);
129
- results.push({ command: sanitizeCommand(command), ...result });
130
- if (result.exit_code !== 0) {
131
- const failed = { command: sanitizeCommand(command), result, results };
132
- markBootstrapFailed(context, protocol, record, failed);
133
- throw new AppError("bootstrap_failed", "Project-owned Worktrunk bootstrap failed", 1, failed);
134
- }
177
+ catch (error) {
178
+ if (error instanceof AppError && error.code === "bootstrap_failed")
179
+ markBootstrapFailed(context, protocol, record, error.details);
180
+ throw error;
135
181
  }
136
182
  const now = context.now();
137
- const result = { commands: results, status: "succeeded" };
183
+ const results = result.commands;
138
184
  context.db.run(`UPDATE worktree_records
139
185
  SET bootstrap_status = 'succeeded', last_command_result_json = ?, updated_at = ?
140
186
  WHERE project_id = ? AND protocol_id = ?`, [JSON.stringify(result), now, protocol.project_id, protocol.id]);
@@ -155,7 +201,7 @@ export function bootstrapWorktree(context, input) {
155
201
  });
156
202
  return { ok: true, worktree: worktreeRecord(context, protocol.project_id, protocol.id) };
157
203
  }
158
- export function closeWorktree(context, input) {
204
+ export function prepareWorktreeClose(context, input) {
159
205
  if (!["keep", "remove"].includes(input.mode)) {
160
206
  throw new AppError("validation", "--mode must be keep or remove", 2);
161
207
  }
@@ -171,6 +217,10 @@ export function closeWorktree(context, input) {
171
217
  stage: state.stage
172
218
  });
173
219
  }
220
+ return { protocol, record };
221
+ }
222
+ export function closeWorktree(context, input) {
223
+ const { protocol, record } = prepareWorktreeClose(context, input);
174
224
  const now = context.now();
175
225
  const nextStatus = input.mode === "keep" ? "kept" : fs.existsSync(record.worktree_path) ? "kept" : "removed";
176
226
  context.db.run(`UPDATE worktree_records SET status = ?, updated_at = ?, closed_at = ? WHERE project_id = ? AND protocol_id = ?`, [nextStatus, now, now, protocol.project_id, protocol.id]);
@@ -0,0 +1,8 @@
1
+ /** Stable model-facing reference for persisted project, RUN and Work IDs. */
2
+ export function shortEntityReference(id) {
3
+ return /^(?:PRJ|RUN|WRK)-\d{3,}(?:-|$)/.exec(id)?.[0]?.replace(/-$/, "") ?? id;
4
+ }
5
+ /** Accepted spellings of one already-resolved entity. Wrong full slugs stay distinct. */
6
+ export function entityReferenceVariants(id) {
7
+ return [...new Set([id, shortEntityReference(id)])];
8
+ }
@@ -9,6 +9,18 @@ export class AppError extends Error {
9
9
  this.details = details;
10
10
  }
11
11
  }
12
+ /** Error fields must cross JSON boundaries as data: Error.message is not enumerable. */
13
+ export function errorRecord(error, depth = 0) {
14
+ const value = error;
15
+ const details = value?.details && typeof value.details === "object" && !Array.isArray(value.details) ? value.details : {};
16
+ return {
17
+ code: typeof value?.code === "string" ? value.code : "unexpected",
18
+ message: typeof value?.message === "string" ? value.message : String(error),
19
+ exitCode: typeof value?.exitCode === "number" ? value.exitCode : 1,
20
+ details,
21
+ ...(value?.cause && depth < 3 ? { cause: errorRecord(value.cause, depth + 1) } : {})
22
+ };
23
+ }
12
24
  export function isAppError(error) {
13
25
  return error instanceof AppError;
14
26
  }