@bridge_gpt/mcp-server 0.2.71 → 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 (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -0,0 +1,277 @@
1
+ /**
2
+ * `epic-implementer driver-guard` — the `/drive-epic-run` Stop hook (BAPI-1642).
3
+ *
4
+ * Claude Code runs it at every turn end of a session that invoked
5
+ * `/drive-epic-run` (the hook is declared in that command's frontmatter, so it
6
+ * never runs in any other session). It reads the hook JSON on stdin and decides,
7
+ * locally and within a few seconds, whether the driving session may stop.
8
+ *
9
+ * ALWAYS EXITS 0. Stdout is empty to allow, and exactly
10
+ * `{"decision":"block","reason":"..."}` to block. Any error, timeout, missing
11
+ * field, or unreadable state allows the stop and records why when it safely can.
12
+ * It makes no network call and runs no LLM, git read, or `explain_run`.
13
+ *
14
+ * DECISION ORDER.
15
+ * 1. `BRIDGE_EI_DRIVER_GUARD=off`: allow.
16
+ * 2. No registration for this session: allow, no record, nothing written.
17
+ * 3. Malformed registration: allow (uncertainty). Generation differs from the
18
+ * run's `driver-current.json`: allow, the registration is stale.
19
+ * 4. This generation is released: allow.
20
+ * 5. `background_tasks` missing or malformed: allow, `supervision_unknown`.
21
+ * An older Claude Code without the field is unknown, never "nothing running".
22
+ * 6. A running shell task whose command equals the registered waiter
23
+ * (optionally followed by `--since '<token>'`): allow, `waiter_verified`.
24
+ * The only thing that re-arms the cap.
25
+ * 7. A running task naming `wait-run` with this run and generation but not an
26
+ * exact match: allow, `waiter_unrecognized`. No re-arm.
27
+ * 8. Otherwise block, at most three times per episode. The fourth attempt
28
+ * allows, records `supervision_lapse`, and starts the detached owner FYI;
29
+ * the episode then stays allowed until a verified waiter or a new
30
+ * generation. `stop_hook_active` is never permission on its own.
31
+ *
32
+ * The worker lifecycle hook (`claude-hook.ts`) is separate and unchanged.
33
+ */
34
+ import { appendFile } from "node:fs/promises";
35
+ import path from "node:path";
36
+ import { BRIDGE_DEFAULT_LAUNCHER } from "../bridge-permissions.js";
37
+ import { isRegisteredWaiterCommand, renderDeclareBlockedTemplate, renderReleaseCommand, parseWaiterInvocation, } from "./driver-commands.js";
38
+ import { closeLapseEpisode, launchLapseFyi, transcribeLapseResult } from "./driver-lapse.js";
39
+ import { DRIVER_GUARD_BLOCK_CAP, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, currentPointerPath, ensurePrivateDir, formatDriverTallyLine, generationFilePath, generationLabel, parseCapState, parseCurrentPointer, parseRegistration, parseReleaseMarker, readDriverJson, registrationPath, resolveDriverStateRoots, withDriverLock, writeDriverJsonAtomic, } from "./driver-session-state.js";
40
+ /** The off switch. `off` (any case) disables the guard; anything else leaves it on. */
41
+ export const DRIVER_GUARD_OFF_ENV = "BRIDGE_EI_DRIVER_GUARD";
42
+ /** The guard's own deadline, under the hook's timeout. Past it, the stop is allowed. */
43
+ export const DRIVER_GUARD_DEADLINE_MS = 4_000;
44
+ /** Hook stdin larger than this is not parsed. */
45
+ export const DRIVER_GUARD_MAX_STDIN_BYTES = 256 * 1024;
46
+ /** How long the runner waits for its own guard_error line after a crash or the deadline. */
47
+ const DRIVER_GUARD_RECORD_GRACE_MS = 500;
48
+ function isRecord(value) {
49
+ return value !== null && typeof value === "object" && !Array.isArray(value);
50
+ }
51
+ /** The launcher prefix the registered waiter was rendered with. */
52
+ function launcherFromWaiter(waiter) {
53
+ const at = waiter.indexOf(" epic-implementer wait-run ");
54
+ return at > 0 ? waiter.slice(0, at) : BRIDGE_DEFAULT_LAUNCHER;
55
+ }
56
+ /** The corrective message: what is wrong, the exact waiter, then the only other exits. */
57
+ export function renderBlockMessage(registration, attempt) {
58
+ const launcher = launcherFromWaiter(registration.waiter_command);
59
+ return [
60
+ `Supervision is not armed: run ${registration.epic_key} is still active and no waiter is running for ` +
61
+ `this session (guard block ${attempt} of ${DRIVER_GUARD_BLOCK_CAP}).`,
62
+ "Start this exact command as a background task (append --since '<token>' when you have one), then end the turn:",
63
+ registration.waiter_command,
64
+ "If a real stop-list blocker (entries 1-5) or a wedge stops progress, check it first with:",
65
+ renderDeclareBlockedTemplate(launcher, registration.epic_run_id),
66
+ "Filing a blocker never releases the session; keep the waiter running afterwards.",
67
+ "This session may stop without a waiter only after one of:",
68
+ `${renderReleaseCommand(launcher, "done", registration.epic_run_id)} (the run is done or abandoned)`,
69
+ `${renderReleaseCommand(launcher, "handoff", registration.epic_run_id)} (the hand-off report is published)`,
70
+ `${renderReleaseCommand(launcher, "owner", registration.epic_run_id)} (only when the owner explicitly says to stop driving)`,
71
+ ].join("\n");
72
+ }
73
+ /**
74
+ * Classify `background_tasks` against the registration. Never throws. A list
75
+ * that is missing, not an array, or holds an entry whose shape cannot be read is
76
+ * `unknown`: an unreadable entry might be the waiter, so it is never read as
77
+ * "nothing running".
78
+ */
79
+ export function classifyBackgroundTasks(tasks, registration) {
80
+ if (!Array.isArray(tasks))
81
+ return "unknown";
82
+ let unrecognized = false;
83
+ let unreadable = false;
84
+ for (const task of tasks) {
85
+ if (!isRecord(task) || typeof task.type !== "string" || typeof task.status !== "string" ||
86
+ (task.type === "shell" && typeof task.command !== "string")) {
87
+ unreadable = true;
88
+ continue;
89
+ }
90
+ if (task.type !== "shell" || task.status !== "running")
91
+ continue;
92
+ const command = task.command;
93
+ if (isRegisteredWaiterCommand(command, registration.waiter_command))
94
+ return "verified";
95
+ const named = parseWaiterInvocation(command);
96
+ if (named && named.generation === registration.generation &&
97
+ (named.epicRunId === registration.epic_run_id || named.epicRunId === registration.epic_key)) {
98
+ unrecognized = true;
99
+ }
100
+ }
101
+ return unrecognized ? "unrecognized" : unreadable ? "unknown" : "none";
102
+ }
103
+ async function recordDecision(roots, registration, outcome, now) {
104
+ const fields = {
105
+ decision: outcome.decision, reason: outcome.reason, generation: generationLabel(registration.generation),
106
+ };
107
+ if (outcome.decision === "block")
108
+ fields.attempt = outcome.attempt;
109
+ if (outcome.decision === "allow" && outcome.detail)
110
+ fields.detail = outcome.detail;
111
+ await appendDriverTallyLine(roots, registration.epic_key, formatDriverTallyLine("driver-guard", fields, now));
112
+ }
113
+ /** A bounded uncertainty line kept beside the session's guard state when no tally can be trusted. */
114
+ async function recordUncertainty(roots, sessionId, detail, now) {
115
+ const dir = path.join(roots.guardRoot, sessionId);
116
+ await ensurePrivateDir(dir);
117
+ await appendFile(path.join(dir, "guard-uncertain.log"), formatDriverTallyLine("driver-guard", { decision: "allow", reason: "guard_error", detail }, now), { encoding: "utf-8", mode: 0o600 });
118
+ }
119
+ /** Steps 6-8 under the generation's lock: re-arm, or count a block, or lapse. */
120
+ async function decideUnderCap(roots, registration, match, deps, now) {
121
+ const capPath = generationFilePath(roots, registration.session_id, registration.generation, "cap.json");
122
+ const lockPath = generationFilePath(roots, registration.session_id, registration.generation, "lock");
123
+ const locked = await withDriverLock(lockPath, async () => {
124
+ const read = await readDriverJson(capPath);
125
+ const cap = read.state === "ok" ? parseCapState(read.value) : null;
126
+ // A missing or corrupt counter for a registered generation is never a fresh zero.
127
+ if (!cap || cap.generation !== registration.generation) {
128
+ return { decision: "allow", reason: "guard_error", detail: "cap_unreadable" };
129
+ }
130
+ if (match === "verified") {
131
+ if (cap.blocks !== 0 || cap.lapsed) {
132
+ const rearmed = { version: DRIVER_STATE_VERSION, generation: cap.generation, blocks: 0, lapsed: false };
133
+ await writeDriverJsonAtomic(capPath, rearmed);
134
+ }
135
+ // A new episode starts here: a later lapse must send its own FYI.
136
+ if (cap.lapsed)
137
+ await closeLapseEpisode(roots, registration, now).catch(() => undefined);
138
+ return { decision: "allow", reason: "waiter_verified" };
139
+ }
140
+ if (cap.lapsed)
141
+ return { decision: "allow", reason: "lapse_open" };
142
+ if (cap.blocks < DRIVER_GUARD_BLOCK_CAP) {
143
+ const attempt = cap.blocks + 1;
144
+ // Persisted before the block is returned, so a crash cannot hand out a free block.
145
+ await writeDriverJsonAtomic(capPath, { ...cap, blocks: attempt });
146
+ return { decision: "block", reason: "no_waiter", attempt, message: renderBlockMessage(registration, attempt) };
147
+ }
148
+ await writeDriverJsonAtomic(capPath, { ...cap, lapsed: true });
149
+ const launch = await launchLapseFyi(roots, registration, { now, ...deps.lapse }).catch(() => "launch_failed");
150
+ return { decision: "allow", reason: "supervision_lapse", detail: `fyi_${launch}` };
151
+ });
152
+ return locked.state === "held" ? locked.value : { decision: "allow", reason: "guard_error", detail: "lock_contended" };
153
+ }
154
+ /**
155
+ * Decide one Stop event. Pure of process I/O: reads and writes only the
156
+ * driver state files. Errors propagate to {@link runDriverGuardCommand}, which
157
+ * turns every one of them into an allow.
158
+ */
159
+ export async function evaluateDriverGuard(payload, deps = {}, context = {}) {
160
+ const env = deps.env ?? process.env;
161
+ const now = deps.now ?? (() => new Date());
162
+ if ((env[DRIVER_GUARD_OFF_ENV] ?? "").trim().toLowerCase() === "off")
163
+ return { decision: "allow", reason: "off" };
164
+ if (!isRecord(payload))
165
+ return { decision: "allow", reason: "unregistered" };
166
+ if (payload.hook_event_name !== undefined && payload.hook_event_name !== "Stop") {
167
+ return { decision: "allow", reason: "not_stop" };
168
+ }
169
+ const sessionId = payload.session_id;
170
+ if (typeof sessionId !== "string" || !DRIVER_SESSION_ID_PATTERN.test(sessionId)) {
171
+ return { decision: "allow", reason: "unregistered" };
172
+ }
173
+ // The hook's own session must be the process's session when the host says so.
174
+ const processSession = env.CLAUDE_CODE_SESSION_ID?.trim();
175
+ if (processSession && processSession !== sessionId)
176
+ return { decision: "allow", reason: "unregistered" };
177
+ const roots = resolveDriverStateRoots(deps.homeDir);
178
+ const regRead = await readDriverJson(registrationPath(roots, sessionId));
179
+ if (regRead.state === "absent")
180
+ return { decision: "allow", reason: "unregistered" };
181
+ const registration = regRead.state === "ok" ? parseRegistration(regRead.value) : null;
182
+ if (!registration || registration.session_id !== sessionId) {
183
+ await recordUncertainty(roots, sessionId, "registration_unreadable", now()).catch(() => undefined);
184
+ return { decision: "allow", reason: "guard_error", detail: "registration_unreadable" };
185
+ }
186
+ context.roots = roots;
187
+ context.registration = registration;
188
+ const pointerRead = await readDriverJson(currentPointerPath(roots, registration.epic_key));
189
+ const pointer = pointerRead.state === "ok" ? parseCurrentPointer(pointerRead.value) : null;
190
+ let outcome;
191
+ if (!pointer) {
192
+ outcome = { decision: "allow", reason: "guard_error", detail: "pointer_unreadable" };
193
+ }
194
+ else if (pointer.generation !== registration.generation || pointer.session_id !== sessionId) {
195
+ outcome = { decision: "allow", reason: "stale_registration" };
196
+ }
197
+ else {
198
+ await transcribeLapseResult(roots, registration, now).catch(() => undefined);
199
+ const releaseRead = await readDriverJson(generationFilePath(roots, sessionId, registration.generation, "release.json"));
200
+ const release = releaseRead.state === "ok" ? parseReleaseMarker(releaseRead.value) : null;
201
+ if (release && release.generation === registration.generation) {
202
+ outcome = { decision: "allow", reason: "released", detail: release.reason };
203
+ }
204
+ else {
205
+ const match = classifyBackgroundTasks(payload.background_tasks, registration);
206
+ if (match === "unknown")
207
+ outcome = { decision: "allow", reason: "supervision_unknown" };
208
+ else if (match === "unrecognized")
209
+ outcome = { decision: "allow", reason: "waiter_unrecognized" };
210
+ else
211
+ outcome = await decideUnderCap(roots, registration, match, deps, now);
212
+ }
213
+ }
214
+ context.recorded = true;
215
+ await recordDecision(roots, registration, outcome, now()).catch(() => undefined);
216
+ return outcome;
217
+ }
218
+ /** Read hook stdin, bounded in bytes. */
219
+ async function readProcessStdin(maxBytes) {
220
+ if (process.stdin.isTTY)
221
+ return "";
222
+ const chunks = [];
223
+ let total = 0;
224
+ for await (const chunk of process.stdin) {
225
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
226
+ total += buffer.length;
227
+ if (total > maxBytes)
228
+ throw new Error("stdin too large");
229
+ chunks.push(buffer);
230
+ }
231
+ return Buffer.concat(chunks).toString("utf-8");
232
+ }
233
+ /**
234
+ * Run the Stop hook. Always resolves 0. Prints the block JSON only for an
235
+ * intentional block; every failure, and the deadline, allow silently.
236
+ */
237
+ export async function runDriverGuardCommand(_argv = [], deps = {}) {
238
+ const write = deps.writeStdout ?? ((text) => process.stdout.write(text));
239
+ const now = deps.now ?? (() => new Date());
240
+ const context = {};
241
+ let timer;
242
+ const deadline = new Promise((resolve) => {
243
+ timer = setTimeout(() => resolve("deadline"), deps.deadlineMs ?? DRIVER_GUARD_DEADLINE_MS);
244
+ timer.unref?.();
245
+ });
246
+ const work = (async () => {
247
+ const raw = await (deps.readStdin ?? readProcessStdin)(DRIVER_GUARD_MAX_STDIN_BYTES);
248
+ let payload;
249
+ try {
250
+ payload = JSON.parse(raw);
251
+ }
252
+ catch {
253
+ return null;
254
+ }
255
+ return (deps.evaluate ?? evaluateDriverGuard)(payload, deps, context);
256
+ })().catch(() => "exception");
257
+ try {
258
+ const outcome = await Promise.race([work, deadline]);
259
+ if (outcome !== null && typeof outcome === "object" && outcome.decision === "block") {
260
+ write(`${JSON.stringify({ decision: "block", reason: outcome.message })}\n`);
261
+ }
262
+ else if ((outcome === "deadline" || outcome === "exception") && context.registration && context.roots &&
263
+ !context.recorded) {
264
+ // Allow, and record why, without waiting past a short grace period.
265
+ const line = recordDecision(context.roots, context.registration, { decision: "allow", reason: "guard_error", detail: outcome }, now()).catch(() => undefined);
266
+ await Promise.race([line, new Promise((resolve) => setTimeout(resolve, DRIVER_GUARD_RECORD_GRACE_MS).unref?.())]);
267
+ }
268
+ }
269
+ catch {
270
+ // Allow.
271
+ }
272
+ finally {
273
+ if (timer)
274
+ clearTimeout(timer);
275
+ }
276
+ return 0;
277
+ }
@@ -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
+ }