@bridge_gpt/mcp-server 0.2.72 → 0.2.73

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 (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -0,0 +1,321 @@
1
+ /**
2
+ * The driver guard's lapse FYI (BAPI-1642).
3
+ *
4
+ * When a registered driving session tries to stop a fourth time in one episode
5
+ * with no waiter, the guard allows the stop and the owner gets one FYI. The
6
+ * guard must answer within seconds and makes no network call, so delivery runs
7
+ * in a DETACHED child process:
8
+ *
9
+ * 1. the guard creates `lapse-pending.json` once per lapse episode
10
+ * ({@link launchLapseFyi}) and spawns the packaged
11
+ * `epic-implementer escalate --lapse-record <path>` with Node's detached
12
+ * spawn and `unref()`, then returns at once;
13
+ * 2. that child ({@link runLapseRecord}) resolves credentials through the
14
+ * shared resolver, reads the run state once, picks the target ticket, sends
15
+ * one `intervention_ended` escalation with fixed text, and writes
16
+ * `lapse-result.json` atomically;
17
+ * 3. the next guard run, or the next `driver-register`, copies the result into
18
+ * the run's tally ({@link transcribeLapseResult}) exactly once.
19
+ *
20
+ * TARGET TICKET (Investigation 3). The escalate route is per ticket and refuses
21
+ * a ticket outside the run. The child picks the most recently parked non-terminal
22
+ * ticket, else the first non-terminal ticket in the state route's order (ticket
23
+ * key; the state route carries no plan order). A terminal run is a release, not a
24
+ * lapse, so no FYI is sent.
25
+ *
26
+ * NOT A HOLD. The escalation writes one notification row and has no park or
27
+ * run-control effect (Investigation 2). Its response may say `driver_enforced`
28
+ * for a healthy ticket; the `/drive-epic-run` prompt states that a guard lapse
29
+ * FYI is never a hold. The text below says the notice is about the session.
30
+ *
31
+ * `delivery_status: queued` means the outbox accepted it, not that anyone read it.
32
+ */
33
+ import { spawn as nodeSpawn } from "node:child_process";
34
+ import { closeSync, openSync } from "node:fs";
35
+ import { unlink } from "node:fs/promises";
36
+ import path from "node:path";
37
+ import { DRIVER_DELIVERY_STATUS_PATTERN, DRIVER_KEY_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, createDriverJsonExclusive, formatDriverTallyLine, generationFilePath, generationLabel, parseLapseResult, parsePendingLapse, readDriverJson, resolveDriverStateRoots, writeDriverJsonAtomic, } from "./driver-session-state.js";
38
+ /** The escalation cause a lapse FYI is sent under. */
39
+ export const LAPSE_ESCALATION_CAUSE = "intervention_ended";
40
+ const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
41
+ const TERMINAL_TICKET_STATUSES = new Set(["done", "abandoned"]);
42
+ /** The fixed FYI text. Always at most 300 characters (the escalate route's cap). */
43
+ export function renderLapseActionNeeded(epicKey) {
44
+ return `FYI: not a hold. The /drive-epic-run session for ${epicKey} stopped after 3 guard ` +
45
+ "corrections with no waiter. The run keeps going unsupervised. To re-attach, run " +
46
+ `/drive-epic-run ${epicKey} in a new session. This is about the session, not this ticket.`;
47
+ }
48
+ /**
49
+ * Pick the lapse target: the most recently parked non-terminal ticket, else the
50
+ * first non-terminal ticket in the state route's order. `null` when every ticket
51
+ * is terminal.
52
+ */
53
+ export function selectLapseTicket(rows) {
54
+ let parked = null;
55
+ let first = null;
56
+ for (const row of rows) {
57
+ if (row === null || typeof row !== "object")
58
+ continue;
59
+ const r = row;
60
+ if (typeof r.ticket_key !== "string" || !DRIVER_KEY_PATTERN.test(r.ticket_key))
61
+ continue;
62
+ if (typeof r.status !== "string" || TERMINAL_TICKET_STATUSES.has(r.status))
63
+ continue;
64
+ first ??= r.ticket_key;
65
+ const at = typeof r.parked_at === "string" ? Date.parse(r.parked_at) : Number.NaN;
66
+ if (!Number.isNaN(at) && (parked === null || at > parked.at))
67
+ parked = { key: r.ticket_key, at };
68
+ }
69
+ return parked?.key ?? first;
70
+ }
71
+ /**
72
+ * The argv that re-enters this packaged CLI's `escalate`. The npm bin
73
+ * `epic-implementer-bin.js` takes the subcommand directly; the package entry
74
+ * takes `epic-implementer` first.
75
+ */
76
+ export function lapseEntryArgs(entryScript) {
77
+ return /epic-implementer-bin\.[cm]?js$/.test(entryScript)
78
+ ? [entryScript, "escalate"]
79
+ : [entryScript, "epic-implementer", "escalate"];
80
+ }
81
+ /**
82
+ * Create this episode's pending record once and start the detached FYI. Never
83
+ * waits for it. A second call in the same episode finds the record and launches
84
+ * nothing; {@link closeLapseEpisode} clears a finished episode when the cap is
85
+ * re-armed, so a later lapse sends its own FYI.
86
+ */
87
+ export async function launchLapseFyi(roots, registration, deps = {}) {
88
+ const now = deps.now ?? (() => new Date());
89
+ const pendingPath = generationFilePath(roots, registration.session_id, registration.generation, "lapse-pending.json");
90
+ const pending = {
91
+ version: DRIVER_STATE_VERSION,
92
+ session_id: registration.session_id,
93
+ generation: registration.generation,
94
+ epic_run_id: registration.epic_run_id,
95
+ epic_key: registration.epic_key,
96
+ created_at: now().toISOString(),
97
+ };
98
+ if (!(await createDriverJsonExclusive(pendingPath, pending))) {
99
+ // A previous episode whose FYI was still in flight at re-arm may have finished
100
+ // since: close it and start this episode's own FYI.
101
+ if ((await closeLapseEpisode(roots, registration, now)) !== "closed" ||
102
+ !(await createDriverJsonExclusive(pendingPath, pending))) {
103
+ return "already_pending";
104
+ }
105
+ }
106
+ // Clear anything a crashed close left behind, so this episode's result is its own.
107
+ for (const name of ["lapse-result.json", "lapse-transcribed.json", "lapse-output.log"]) {
108
+ await unlink(generationFilePath(roots, registration.session_id, registration.generation, name)).catch(() => undefined);
109
+ }
110
+ const entryScript = "entryScript" in deps ? deps.entryScript : process.argv[1];
111
+ if (!entryScript)
112
+ return "launch_failed";
113
+ const outputPath = generationFilePath(roots, registration.session_id, registration.generation, "lapse-output.log");
114
+ let fd;
115
+ try {
116
+ fd = openSync(outputPath, "a", 0o600);
117
+ const child = (deps.spawn ?? nodeSpawn)(deps.execPath ?? process.execPath, [...lapseEntryArgs(entryScript), "--lapse-record", pendingPath], {
118
+ detached: true,
119
+ shell: false,
120
+ windowsHide: true,
121
+ stdio: ["ignore", fd, fd],
122
+ env: deps.env ?? process.env,
123
+ });
124
+ child.unref();
125
+ return "launched";
126
+ }
127
+ catch {
128
+ return "launch_failed";
129
+ }
130
+ finally {
131
+ if (fd !== undefined)
132
+ closeSync(fd);
133
+ }
134
+ }
135
+ function failureReason(error) {
136
+ const e = error;
137
+ if (e && typeof e === "object") {
138
+ if (e.status === 422)
139
+ return "escalate_422";
140
+ if (e.status === 404)
141
+ return "ticket_not_in_run";
142
+ if (e.kind === "timeout")
143
+ return "escalate_timeout";
144
+ }
145
+ return "escalate_failed";
146
+ }
147
+ /**
148
+ * Validate that `pendingPath` is a `lapse-pending.json` inside this user's
149
+ * guard root and return its directory's two identifiers.
150
+ */
151
+ function pendingLocation(roots, pendingPath) {
152
+ const resolved = path.resolve(pendingPath);
153
+ const relative = path.relative(roots.guardRoot, resolved);
154
+ const parts = relative.split(path.sep);
155
+ if (relative.startsWith("..") || path.isAbsolute(relative) || parts.length !== 3 ||
156
+ parts[2] !== "lapse-pending.json") {
157
+ return null;
158
+ }
159
+ return { sessionId: parts[0], generation: parts[1] };
160
+ }
161
+ /**
162
+ * The detached child: deliver one pending lapse and write its result. Returns
163
+ * an exit code and never throws. Only fixed, closed-valued text reaches its
164
+ * redirected output.
165
+ */
166
+ export async function runLapseRecord(pendingPath, deps = {}) {
167
+ const now = deps.now ?? (() => new Date());
168
+ const roots = resolveDriverStateRoots(deps.homeDir);
169
+ const location = pendingLocation(roots, pendingPath);
170
+ if (!location) {
171
+ console.error("Error: --lapse-record must name a lapse-pending.json in the driver guard state directory.");
172
+ return 1;
173
+ }
174
+ let resultPath;
175
+ let pending;
176
+ try {
177
+ resultPath = generationFilePath(roots, location.sessionId, location.generation, "lapse-result.json");
178
+ const read = await readDriverJson(pendingPath);
179
+ pending = read.state === "ok" ? parsePendingLapse(read.value) : null;
180
+ }
181
+ catch {
182
+ console.error("Error: the lapse record could not be read.");
183
+ return 1;
184
+ }
185
+ if (!pending || pending.session_id !== location.sessionId || pending.generation !== location.generation) {
186
+ console.error("Error: the lapse record is not valid.");
187
+ return 1;
188
+ }
189
+ if ((await readDriverJson(resultPath)).state !== "absent")
190
+ return 0;
191
+ const finish = async (fields) => {
192
+ const result = {
193
+ version: DRIVER_STATE_VERSION, generation: pending.generation, ...fields, finished_at: now().toISOString(),
194
+ };
195
+ try {
196
+ await writeDriverJsonAtomic(resultPath, result);
197
+ }
198
+ catch {
199
+ console.error("Error: the lapse result could not be written.");
200
+ return 1;
201
+ }
202
+ console.log(`lapse fyi: ${result.outcome}${result.failure_reason ? ` (${result.failure_reason})` : ""}`);
203
+ return result.outcome === "failed" ? 1 : 0;
204
+ };
205
+ const failed = (reason) => finish({
206
+ outcome: "failed", ticket_key: null, notification_id: null, delivery_status: null, failure_reason: reason,
207
+ });
208
+ const client = () => import("./bridge-api-client.js");
209
+ const resolveAccess = deps.resolveAccess ?? (async () => {
210
+ const resolved = await (await client()).resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
211
+ return resolved.ok ? resolved.access : null;
212
+ });
213
+ let access;
214
+ try {
215
+ access = await resolveAccess();
216
+ }
217
+ catch {
218
+ access = null;
219
+ }
220
+ if (!access)
221
+ return failed("credentials_unavailable");
222
+ let state;
223
+ try {
224
+ state = await (deps.fetchState ?? (async (a, id) => (await client()).fetchEpicRunState(a, id)))(access, pending.epic_run_id);
225
+ }
226
+ catch {
227
+ return failed("state_unreadable");
228
+ }
229
+ if (!state?.epic_run || state.epic_run.epic_run_id !== pending.epic_run_id)
230
+ return failed("run_mismatch");
231
+ if (TERMINAL_RUN_STATUSES.has(state.epic_run.status)) {
232
+ return finish({ outcome: "suppressed_terminal", ticket_key: null, notification_id: null,
233
+ delivery_status: null, failure_reason: null });
234
+ }
235
+ const ticketKey = selectLapseTicket(Array.isArray(state.ticket_statuses) ? state.ticket_statuses : []);
236
+ if (!ticketKey)
237
+ return failed("no_target_ticket");
238
+ try {
239
+ const response = await (deps.escalate ?? (async (a, r) => (await client()).escalateTicket(a, r)))(access, {
240
+ epicRunId: pending.epic_run_id,
241
+ ticketKey,
242
+ cause: LAPSE_ESCALATION_CAUSE,
243
+ actionNeeded: renderLapseActionNeeded(pending.epic_key),
244
+ });
245
+ const delivery = DRIVER_DELIVERY_STATUS_PATTERN.test(response.delivery_status)
246
+ ? response.delivery_status : "unknown: unrecognized";
247
+ return finish({ outcome: "escalated", ticket_key: ticketKey, notification_id: response.notification_id,
248
+ delivery_status: delivery, failure_reason: null });
249
+ }
250
+ catch (error) {
251
+ return failed(failureReason(error));
252
+ }
253
+ }
254
+ /**
255
+ * Close a finished lapse episode when a verified waiter re-arms the cap, so the
256
+ * next lapse in the same generation sends its own FYI. A finished result is
257
+ * transcribed first; only then are the episode's files removed. A delivery still
258
+ * in flight (pending, no result yet) is left alone and reported `in_flight`, so it
259
+ * is never orphaned. {@link launchLapseFyi} calls this again when it finds a pending
260
+ * record, so an FYI that was in flight at re-arm still lets a later lapse send its own.
261
+ */
262
+ export async function closeLapseEpisode(roots, registration, now = () => new Date()) {
263
+ const { session_id: sessionId, generation } = registration;
264
+ const file = (name) => generationFilePath(roots, sessionId, generation, name);
265
+ const pending = await readDriverJson(file("lapse-pending.json"));
266
+ if (pending.state === "absent")
267
+ return "none";
268
+ if ((await readDriverJson(file("lapse-result.json"))).state === "absent")
269
+ return "in_flight";
270
+ await transcribeLapseResult(roots, registration, now).catch(() => false);
271
+ if ((await readDriverJson(file("lapse-transcribed.json"))).state === "absent")
272
+ return "in_flight";
273
+ // The pending record goes first: a crash after it leaves only finished files,
274
+ // which the next launch clears, never a pending record with no FYI behind it.
275
+ for (const name of ["lapse-pending.json", "lapse-result.json", "lapse-output.log", "lapse-transcribed.json"]) {
276
+ await unlink(file(name)).catch(() => undefined);
277
+ }
278
+ return "closed";
279
+ }
280
+ // ---------------------------------------------------------------------------
281
+ // Transcription (guard and driver-register)
282
+ // ---------------------------------------------------------------------------
283
+ /** A delivery status as a closed tally token (`not delivered: x` -> `not_delivered:_x`). */
284
+ export function deliveryStatusToken(status) {
285
+ return status.replace(/[^A-Za-z0-9_.:-]+/g, "_").slice(0, 80);
286
+ }
287
+ /**
288
+ * Copy a finished lapse result into the run's tally exactly once. A marker is
289
+ * created first, so two overlapping callers cannot both append; a failed
290
+ * append removes it again, so the result is retried rather than lost.
291
+ */
292
+ export async function transcribeLapseResult(roots, registration, now = () => new Date()) {
293
+ const { session_id: sessionId, generation } = registration;
294
+ const read = await readDriverJson(generationFilePath(roots, sessionId, generation, "lapse-result.json"));
295
+ const result = read.state === "ok" ? parseLapseResult(read.value) : null;
296
+ if (!result || result.generation !== generation)
297
+ return false;
298
+ const marker = generationFilePath(roots, sessionId, generation, "lapse-transcribed.json");
299
+ if (!(await createDriverJsonExclusive(marker, { version: DRIVER_STATE_VERSION, at: now().toISOString() }))) {
300
+ return false;
301
+ }
302
+ const fields = { event: "lapse_fyi", outcome: result.outcome };
303
+ if (result.ticket_key)
304
+ fields.ticket = result.ticket_key;
305
+ if (result.notification_id !== null)
306
+ fields.notification_id = result.notification_id;
307
+ if (result.delivery_status)
308
+ fields.delivery_status = deliveryStatusToken(result.delivery_status);
309
+ if (result.failure_reason)
310
+ fields.failure = result.failure_reason;
311
+ fields.generation = generationLabel(generation);
312
+ try {
313
+ await appendDriverTallyLine(roots, registration.epic_key, formatDriverTallyLine("driver-guard", fields, now()));
314
+ }
315
+ catch (error) {
316
+ // Release the marker so a later guard run or registration retries.
317
+ await unlink(marker).catch(() => undefined);
318
+ throw error;
319
+ }
320
+ return true;
321
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * `epic-implementer driver-register --epic-run-id <id>` (BAPI-1642).
3
+ *
4
+ * Binds the current Claude Code driving session to one epic run so the Stop-hook
5
+ * guard (`driver-guard`) knows whose turn ends to check. The `/drive-epic-run`
6
+ * prompt runs it once after attach and confirmation, then starts the waiter it
7
+ * prints in the background.
8
+ *
9
+ * WHAT IT DOES. It reads `$CLAUDE_CODE_SESSION_ID`; when that is unset the host
10
+ * is not Claude Code, so it says the guard is not armed, writes nothing, and
11
+ * exits 0. Otherwise it reads the run once through the state route, mints a new
12
+ * random generation, provisions that generation's guard state, and atomically
13
+ * writes the session's registration and then the run's `driver-current.json`
14
+ * pointer. A re-attach always mints a new generation, so an old waiter or an old
15
+ * release can never clear the new one, and quiet time never expires it.
16
+ *
17
+ * WHAT IT IS NOT. It writes no run state, makes no other request, and never
18
+ * starts the waiter itself. A failure to arm is reported with the safe next
19
+ * step (keep monitoring in the foreground) and never stops the run.
20
+ */
21
+ import { randomBytes } from "node:crypto";
22
+ import { fetchEpicRunState, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
23
+ import { renderReleaseCommand, renderWaiterCommand, resolveDriverLauncher, } from "./driver-commands.js";
24
+ import { transcribeLapseResult } from "./driver-lapse.js";
25
+ import { DRIVER_KEY_PATTERN, DRIVER_RUN_REF_PATTERN, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, createDriverJsonExclusive, currentPointerPath, formatDriverTallyLine, generationFilePath, generationLabel, parseRegistration, readDriverJson, registrationPath, resolveDriverStateRoots, writeDriverJsonAtomic, } from "./driver-session-state.js";
26
+ const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
27
+ const NOT_ARMED_NEXT_STEP = "Keep monitoring in the foreground; do not end a turn while the run is active.";
28
+ export function getDriverRegisterUsage() {
29
+ return [
30
+ "Usage: epic-implementer driver-register --epic-run-id <id> [--json]",
31
+ "",
32
+ "Arm the /drive-epic-run Stop-hook guard for this Claude Code session and print the",
33
+ "exact background waiter to keep running. Outside Claude Code it arms nothing and exits 0.",
34
+ ].join("\n");
35
+ }
36
+ function parseArgs(argv) {
37
+ let epicRunId;
38
+ let json = false;
39
+ for (let i = 0; i < argv.length; i += 1) {
40
+ const token = argv[i];
41
+ if (token === "--help" || token === "-h")
42
+ return { help: true };
43
+ if (token === "--json") {
44
+ json = true;
45
+ continue;
46
+ }
47
+ if (token === "--epic-run-id" || token.startsWith("--epic-run-id=")) {
48
+ const value = token.includes("=") ? token.slice(token.indexOf("=") + 1) : argv[++i];
49
+ if (value === undefined)
50
+ throw new Error('Flag "--epic-run-id" requires a value.');
51
+ epicRunId = value.trim();
52
+ continue;
53
+ }
54
+ throw new Error('Unknown driver-register option. Run "epic-implementer driver-register --help" for usage.');
55
+ }
56
+ if (!epicRunId || !DRIVER_RUN_REF_PATTERN.test(epicRunId)) {
57
+ throw new Error('Flag "--epic-run-id" is required and must be a run id or epic key.');
58
+ }
59
+ return { help: false, epicRunId, json };
60
+ }
61
+ /** Provision the new generation's cap, then publish registration and pointer. */
62
+ async function publishRegistration(roots, registration) {
63
+ const cap = {
64
+ version: DRIVER_STATE_VERSION, generation: registration.generation, blocks: 0, lapsed: false,
65
+ };
66
+ const created = await createDriverJsonExclusive(generationFilePath(roots, registration.session_id, registration.generation, "cap.json"), cap);
67
+ if (!created)
68
+ throw new Error("generation collision");
69
+ await writeDriverJsonAtomic(registrationPath(roots, registration.session_id), registration);
70
+ const pointer = {
71
+ version: DRIVER_STATE_VERSION,
72
+ session_id: registration.session_id,
73
+ generation: registration.generation,
74
+ registered_at: registration.registered_at,
75
+ };
76
+ // Written last: until it lands, the guard sees a stale registration and allows.
77
+ await writeDriverJsonAtomic(currentPointerPath(roots, registration.epic_key), pointer);
78
+ }
79
+ /** Run `driver-register`. Never throws; returns the exit code. */
80
+ export async function runDriverRegisterCommand(argv, deps = {}) {
81
+ const env = deps.env ?? process.env;
82
+ const now = deps.now ?? (() => new Date());
83
+ const out = deps.writeStdout ?? ((text) => console.log(text));
84
+ const err = deps.writeStderr ?? ((line) => console.error(line));
85
+ const fail = (message) => {
86
+ err(`Error: ${message} The driver guard is not armed. ${NOT_ARMED_NEXT_STEP}`);
87
+ return 1;
88
+ };
89
+ let parsed;
90
+ try {
91
+ parsed = parseArgs(argv);
92
+ }
93
+ catch (error) {
94
+ err(`Error: ${error.message}`);
95
+ return 1;
96
+ }
97
+ if (parsed.help) {
98
+ out(getDriverRegisterUsage());
99
+ return 0;
100
+ }
101
+ const sessionId = env.CLAUDE_CODE_SESSION_ID?.trim() ?? "";
102
+ if (sessionId.length === 0) {
103
+ out("Driver guard not armed: this host is not Claude Code (CLAUDE_CODE_SESSION_ID is unset). " +
104
+ NOT_ARMED_NEXT_STEP);
105
+ return 0;
106
+ }
107
+ if (!DRIVER_SESSION_ID_PATTERN.test(sessionId)) {
108
+ // The value is never echoed: it may be anything.
109
+ return fail("the Claude Code session id is not a plain token (letters, digits, '-').");
110
+ }
111
+ const launcher = resolveDriverLauncher(env);
112
+ if (!launcher)
113
+ return fail("BAPI_MCP_CLI cannot be used as a command prefix.");
114
+ try {
115
+ const resolveAccess = deps.resolveAccess ?? (async () => {
116
+ const resolved = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
117
+ return resolved.ok ? resolved.access : null;
118
+ });
119
+ const access = await resolveAccess();
120
+ if (!access)
121
+ return fail("Bridge API credentials could not be resolved.");
122
+ const state = await (deps.fetchState ?? ((a, id) => fetchEpicRunState(a, id)))(access, parsed.epicRunId);
123
+ const run = state?.epic_run;
124
+ if (!run || !DRIVER_RUN_REF_PATTERN.test(run.epic_run_id) || !DRIVER_KEY_PATTERN.test(run.epic_key) ||
125
+ typeof run.repo_name !== "string" || run.repo_name.length === 0 ||
126
+ (parsed.epicRunId !== run.epic_run_id && parsed.epicRunId !== run.epic_key)) {
127
+ return fail("the run state read did not name this run.");
128
+ }
129
+ if (TERMINAL_RUN_STATUSES.has(run.status)) {
130
+ out(`Driver guard not armed: run ${run.epic_key} is ${run.status}; there is nothing left to supervise.`);
131
+ return 0;
132
+ }
133
+ const roots = resolveDriverStateRoots(deps.homeDir);
134
+ // Carry an earlier generation's finished lapse FYI into its own tally first.
135
+ const previous = await readDriverJson(registrationPath(roots, sessionId));
136
+ const previousRegistration = previous.state === "ok" ? parseRegistration(previous.value) : null;
137
+ if (previousRegistration)
138
+ await transcribeLapseResult(roots, previousRegistration, now).catch(() => undefined);
139
+ const generation = (deps.newGeneration ?? (() => randomBytes(16).toString("hex")))();
140
+ const registration = {
141
+ version: DRIVER_STATE_VERSION,
142
+ session_id: sessionId,
143
+ epic_run_id: run.epic_run_id,
144
+ epic_key: run.epic_key,
145
+ repo_name: run.repo_name,
146
+ generation,
147
+ waiter_command: renderWaiterCommand(launcher, run.epic_run_id, generation),
148
+ registered_at: now().toISOString(),
149
+ };
150
+ await publishRegistration(roots, registration);
151
+ await appendDriverTallyLine(roots, run.epic_key, formatDriverTallyLine("driver-guard", { event: "register", generation: generationLabel(generation) }, now())).catch(() => undefined);
152
+ if (parsed.json) {
153
+ out(JSON.stringify({
154
+ armed: true,
155
+ epic_key: run.epic_key,
156
+ epic_run_id: run.epic_run_id,
157
+ generation,
158
+ waiter_command: registration.waiter_command,
159
+ }));
160
+ return 0;
161
+ }
162
+ out([
163
+ `Driver guard armed for ${run.epic_key} (generation ${generationLabel(generation)}).`,
164
+ "Before any turn ends, keep this waiter running as a background task:",
165
+ registration.waiter_command,
166
+ "Release supervision only with one of:",
167
+ ` ${renderReleaseCommand(launcher, "done", run.epic_run_id)} # the run is done or abandoned`,
168
+ ` ${renderReleaseCommand(launcher, "handoff", run.epic_run_id)} # the hand-off report is published`,
169
+ ` ${renderReleaseCommand(launcher, "owner", run.epic_run_id)} # only on the owner's explicit instruction`,
170
+ ].join("\n"));
171
+ return 0;
172
+ }
173
+ catch {
174
+ return fail("the registration could not be written or the run could not be read.");
175
+ }
176
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * `epic-implementer driver-release --reason owner|done|handoff --epic-run-id <id>`
3
+ * (BAPI-1642).
4
+ *
5
+ * The only way a registered driving session may stop with no waiter running.
6
+ * `--reason` must come first, so permission rules can pre-authorize `done` and
7
+ * `handoff` for an unattended driver while `owner` still gets the host's own
8
+ * permission prompt (the BAPI-1448 `--user-consented` precedent).
9
+ *
10
+ * done the run is `done` or `abandoned`, read through the state route and
11
+ * matched to the registered run id;
12
+ * handoff the run's hand-off report is `published` (`run.handoff_report.state`
13
+ * from `explain_run`), the server's own proof the report was posted;
14
+ * owner recorded as a closed reason only. Use it only on the owner's
15
+ * explicit instruction to stop driving; a reply or a status question is
16
+ * never a release, and the guard never reads conversation text.
17
+ *
18
+ * A release is a marker in the guard-owned directory for this session's current
19
+ * generation. It lasts until the next `driver-register` and never touches the run.
20
+ * A refusal prints the registered waiter as the next step and exits 1; it pauses,
21
+ * parks, and holds nothing.
22
+ */
23
+ import { fetchEpicRunState, fetchExplainRun, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
24
+ import { DRIVER_RELEASE_REASONS, DRIVER_RUN_REF_PATTERN, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, currentPointerPath, formatDriverTallyLine, generationFilePath, generationLabel, parseCurrentPointer, parseRegistration, readDriverJson, registrationPath, resolveDriverStateRoots, writeDriverJsonAtomic, } from "./driver-session-state.js";
25
+ const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
26
+ export function getDriverReleaseUsage() {
27
+ return [
28
+ "Usage: epic-implementer driver-release --reason owner|done|handoff --epic-run-id <id>",
29
+ "",
30
+ "Release this Claude Code session from /drive-epic-run supervision. --reason comes first.",
31
+ " done only after the run is done or abandoned (checked on the server)",
32
+ " handoff only after the run's hand-off report is published (checked on the server)",
33
+ " owner only when the owner explicitly tells you to stop driving",
34
+ "A release changes nothing on the run and lasts until the next driver-register.",
35
+ ].join("\n");
36
+ }
37
+ function parseArgs(argv) {
38
+ if (argv.includes("--help") || argv.includes("-h"))
39
+ return { help: true };
40
+ if (argv.length !== 4 || argv[0] !== "--reason" || argv[2] !== "--epic-run-id") {
41
+ throw new Error('driver-release takes exactly "--reason <owner|done|handoff> --epic-run-id <id>", in that order.');
42
+ }
43
+ const reason = argv[1];
44
+ if (!DRIVER_RELEASE_REASONS.includes(reason)) {
45
+ throw new Error('Flag "--reason" must be owner, done, or handoff.');
46
+ }
47
+ const epicRunId = argv[3].trim();
48
+ if (!DRIVER_RUN_REF_PATTERN.test(epicRunId)) {
49
+ throw new Error('Flag "--epic-run-id" must be a run id or epic key.');
50
+ }
51
+ return { help: false, reason: reason, epicRunId };
52
+ }
53
+ async function checkReason(reason, registration, deps) {
54
+ if (reason === "owner")
55
+ return { ok: true };
56
+ const resolveAccess = deps.resolveAccess ?? (async () => {
57
+ const resolved = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
58
+ return resolved.ok ? resolved.access : null;
59
+ });
60
+ const access = await resolveAccess();
61
+ if (!access)
62
+ return { ok: false, why: "Bridge API credentials could not be resolved, so the release could not be checked." };
63
+ if (reason === "done") {
64
+ const state = await (deps.fetchState ?? ((a, id) => fetchEpicRunState(a, id)))(access, registration.epic_run_id);
65
+ const run = state?.epic_run;
66
+ if (!run || run.epic_run_id !== registration.epic_run_id) {
67
+ return { ok: false, why: "the state read did not name the registered run." };
68
+ }
69
+ return TERMINAL_RUN_STATUSES.has(run.status)
70
+ ? { ok: true }
71
+ : { ok: false, why: `the run is ${typeof run.status === "string" ? run.status.slice(0, 40) : "not terminal"}, not done or abandoned.` };
72
+ }
73
+ const explain = await (deps.fetchExplain ?? ((a, id) => fetchExplainRun(a, id)))(access, registration.epic_run_id);
74
+ const run = explain?.run;
75
+ if (!run || run.epic_run_id !== registration.epic_run_id) {
76
+ return { ok: false, why: "the explain read did not name the registered run." };
77
+ }
78
+ const state = run.handoff_report?.state;
79
+ return state === "published"
80
+ ? { ok: true }
81
+ : { ok: false, why: `the hand-off report is ${typeof state === "string" ? state.slice(0, 40) : "not readable"}, not published.` };
82
+ }
83
+ async function loadCurrentRegistration(roots, sessionId) {
84
+ const read = await readDriverJson(registrationPath(roots, sessionId));
85
+ if (read.state === "absent")
86
+ return "absent";
87
+ const registration = read.state === "ok" ? parseRegistration(read.value) : null;
88
+ if (!registration || registration.session_id !== sessionId)
89
+ return "unreadable";
90
+ const pointerRead = await readDriverJson(currentPointerPath(roots, registration.epic_key));
91
+ const pointer = pointerRead.state === "ok" ? parseCurrentPointer(pointerRead.value) : null;
92
+ if (!pointer)
93
+ return "unreadable";
94
+ return pointer.generation === registration.generation && pointer.session_id === sessionId ? registration : "stale";
95
+ }
96
+ /** Run `driver-release`. Never throws; returns the exit code. */
97
+ export async function runDriverReleaseCommand(argv, deps = {}) {
98
+ const env = deps.env ?? process.env;
99
+ const now = deps.now ?? (() => new Date());
100
+ const out = deps.writeStdout ?? ((text) => console.log(text));
101
+ const err = deps.writeStderr ?? ((line) => console.error(line));
102
+ let parsed;
103
+ try {
104
+ parsed = parseArgs(argv);
105
+ }
106
+ catch (error) {
107
+ err(`Error: ${error.message}`);
108
+ return 1;
109
+ }
110
+ if (parsed.help) {
111
+ out(getDriverReleaseUsage());
112
+ return 0;
113
+ }
114
+ const sessionId = env.CLAUDE_CODE_SESSION_ID?.trim() ?? "";
115
+ if (sessionId.length === 0) {
116
+ out("Nothing to release: this host is not Claude Code, so no driver guard was armed.");
117
+ return 0;
118
+ }
119
+ if (!DRIVER_SESSION_ID_PATTERN.test(sessionId)) {
120
+ err("Error: the Claude Code session id is not a plain token; nothing was released.");
121
+ return 1;
122
+ }
123
+ try {
124
+ const roots = resolveDriverStateRoots(deps.homeDir);
125
+ const registration = await loadCurrentRegistration(roots, sessionId);
126
+ if (registration === "absent") {
127
+ out("Nothing to release: this session is not registered as a driver.");
128
+ return 0;
129
+ }
130
+ if (registration === "stale") {
131
+ out("Nothing to release: this session's registration was replaced by a newer driver-register, " +
132
+ "so the guard no longer applies to it.");
133
+ return 0;
134
+ }
135
+ if (registration === "unreadable") {
136
+ err("Error: this session's registration could not be read; nothing was released. " +
137
+ "Run driver-register again to re-arm, then release.");
138
+ return 1;
139
+ }
140
+ if (parsed.epicRunId !== registration.epic_run_id && parsed.epicRunId !== registration.epic_key) {
141
+ err(`Error: this session is registered for ${registration.epic_key}, not the named run; nothing was released.`);
142
+ return 1;
143
+ }
144
+ const check = await checkReason(parsed.reason, registration, deps);
145
+ if (!check.ok) {
146
+ err(`Error: release refused (--reason ${parsed.reason}): ${check.why} Supervision continues. ` +
147
+ `Next step: keep this waiter running in the background: ${registration.waiter_command}`);
148
+ await appendDriverTallyLine(roots, registration.epic_key, formatDriverTallyLine("driver-guard", { event: "release_refused", reason: parsed.reason, generation: generationLabel(registration.generation) }, now())).catch(() => undefined);
149
+ return 1;
150
+ }
151
+ // Re-read the pointer immediately before committing: a re-attach since the
152
+ // check must not receive a release meant for the generation it replaced.
153
+ const again = await loadCurrentRegistration(roots, sessionId);
154
+ if (typeof again === "string" || again.generation !== registration.generation) {
155
+ err("Error: this session was re-registered during the release; nothing was released. Release again.");
156
+ return 1;
157
+ }
158
+ const marker = {
159
+ version: DRIVER_STATE_VERSION,
160
+ generation: registration.generation,
161
+ reason: parsed.reason,
162
+ released_at: now().toISOString(),
163
+ };
164
+ await writeDriverJsonAtomic(generationFilePath(roots, sessionId, registration.generation, "release.json"), marker);
165
+ await appendDriverTallyLine(roots, registration.epic_key, formatDriverTallyLine("driver-guard", { event: "release", reason: parsed.reason, generation: generationLabel(registration.generation) }, now())).catch(() => undefined);
166
+ out(`Released (--reason ${parsed.reason}): this session may now stop without a waiter. ` +
167
+ "The run itself is unchanged.");
168
+ return 0;
169
+ }
170
+ catch {
171
+ err("Error: the release could not be checked or recorded; nothing was released. Supervision continues.");
172
+ return 1;
173
+ }
174
+ }