@bridge_gpt/mcp-server 0.2.72 → 0.2.74

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 (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -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/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The one rendering of every command the driver guard prints or recognizes
3
+ * (BAPI-1642): the registered waiter, the `declare-blocked` template, and the
4
+ * `driver-release` exits.
5
+ *
6
+ * The launcher prefix is the same value the project permission rules are
7
+ * written for ({@link resolvePermissionLauncher}): `npx -y @bridge_gpt/mcp-server`
8
+ * by default, or a validated `BAPI_MCP_CLI`. The prefix stays unquoted so the
9
+ * printed command matches those exact-prefix rules; every argument value is
10
+ * single-quoted.
11
+ *
12
+ * RECOGNITION. The Stop hook compares a running task's `command` with the
13
+ * registered waiter byte for byte (`waiter_verified`). Investigation 4 found that
14
+ * Claude Code 2.1.312 reports the command exactly as the agent ran it, quotes
15
+ * included. {@link parseWaiterInvocation} is a deliberately small tokenizer for
16
+ * the near-miss case (`waiter_unrecognized`): plain words and single- or
17
+ * double-quoted words only. Anything with shell operators, substitutions, or
18
+ * escapes is not parsed, never guessed at.
19
+ */
20
+ import { resolvePermissionLauncher } from "../bridge-permissions.js";
21
+ /** The `--max-minutes` every registered waiter uses. */
22
+ export const DRIVER_WAITER_MAX_MINUTES = 20;
23
+ /** Quote one argument value for a POSIX shell. Values here never contain `'`. */
24
+ export function shellQuote(value) {
25
+ return `'${value.replaceAll("'", "'\\''")}'`;
26
+ }
27
+ /**
28
+ * The launcher prefix, or `null` when `BAPI_MCP_CLI` is set but unusable (a
29
+ * quote, a shell operator, or a credential-like value). A null launcher means no
30
+ * waiter can be printed, so registration refuses to arm.
31
+ */
32
+ export function resolveDriverLauncher(env) {
33
+ const resolved = resolvePermissionLauncher(env);
34
+ return resolved.ok ? resolved.prefix : null;
35
+ }
36
+ /** The exact registered waiter command. */
37
+ export function renderWaiterCommand(launcher, epicRunId, generation) {
38
+ return `${launcher} epic-implementer wait-run --epic-run-id ${shellQuote(epicRunId)} --watch ` +
39
+ `--max-minutes ${DRIVER_WAITER_MAX_MINUTES} --driver-generation ${shellQuote(generation)} --json`;
40
+ }
41
+ /** The unregistered watch waiter, for a host or session with no registration. */
42
+ export function renderPlainWaiterCommand(launcher, epicRunId) {
43
+ return `${launcher} epic-implementer wait-run --epic-run-id ${shellQuote(epicRunId)} --watch ` +
44
+ `--max-minutes ${DRIVER_WAITER_MAX_MINUTES} --json`;
45
+ }
46
+ /** The `declare-blocked` template the block message names; `<…>` are the driver's inputs. */
47
+ export function renderDeclareBlockedTemplate(launcher, epicRunId) {
48
+ return `${launcher} epic-implementer declare-blocked --epic-run-id ${shellQuote(epicRunId)} ` +
49
+ "--ticket-key <TICKET> --entry <1|2|3|4|5|wedge> --requirement '<what is needed>' " +
50
+ "--evidence '<current evidence>' --tried '<verbs already run>'";
51
+ }
52
+ /** One `driver-release` exit. `--reason` comes first so permission rules can tell them apart. */
53
+ export function renderReleaseCommand(launcher, reason, epicRunId) {
54
+ return `${launcher} epic-implementer driver-release --reason ${reason} --epic-run-id ${shellQuote(epicRunId)}`;
55
+ }
56
+ /** A `wait-run` result token (change mode `v1:`, attention mode `a1:`). */
57
+ const WAITER_SINCE_TOKEN = /^(?:v1|a1):[0-9a-f]{16}$/;
58
+ /**
59
+ * True when `command` is the registered waiter exactly, or exactly the
60
+ * registered waiter followed by ` --since '<token>'` with a valid token. The
61
+ * prompt passes the previous result's token on every re-arm, so this is the one
62
+ * structured variant the exact match accepts; nothing else is loosened.
63
+ */
64
+ export function isRegisteredWaiterCommand(command, waiterCommand) {
65
+ if (command === waiterCommand)
66
+ return true;
67
+ const prefix = `${waiterCommand} --since `;
68
+ if (!command.startsWith(prefix))
69
+ return false;
70
+ const rest = command.slice(prefix.length);
71
+ const token = rest.startsWith("'") && rest.endsWith("'") && rest.length > 2 ? rest.slice(1, -1) : rest;
72
+ return WAITER_SINCE_TOKEN.test(token);
73
+ }
74
+ /** At most this many characters of a task command are parsed. */
75
+ const MAX_PARSED_COMMAND_CHARS = 1000;
76
+ /** A word that needs no quoting and carries no shell meaning. */
77
+ const PLAIN_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
78
+ /**
79
+ * Split a command into words, accepting only plain words and whole single- or
80
+ * double-quoted words with no escapes, expansions or operators inside. Returns
81
+ * `null` for anything else.
82
+ */
83
+ export function tokenizeSimpleCommand(command) {
84
+ if (command.length === 0 || command.length > MAX_PARSED_COMMAND_CHARS)
85
+ return null;
86
+ const words = [];
87
+ for (const raw of command.trim().split(/[ \t]+/)) {
88
+ if (raw.length === 0)
89
+ continue;
90
+ if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
91
+ const inner = raw.slice(1, -1);
92
+ if (inner.includes("'"))
93
+ return null;
94
+ words.push(inner);
95
+ }
96
+ else if (raw.length >= 2 && raw.startsWith("\"") && raw.endsWith("\"")) {
97
+ const inner = raw.slice(1, -1);
98
+ if (/["$`\\]/.test(inner))
99
+ return null;
100
+ words.push(inner);
101
+ }
102
+ else if (PLAIN_WORD.test(raw)) {
103
+ words.push(raw);
104
+ }
105
+ else {
106
+ return null;
107
+ }
108
+ }
109
+ return words.length > 0 ? words : null;
110
+ }
111
+ /**
112
+ * Parse a task command as a `wait-run` invocation and return the run id and
113
+ * generation it names, or `null` when it is not a parseable `epic-implementer
114
+ * wait-run` call carrying both `--epic-run-id` and `--driver-generation`.
115
+ */
116
+ export function parseWaiterInvocation(command) {
117
+ const words = tokenizeSimpleCommand(command);
118
+ if (!words)
119
+ return null;
120
+ const at = words.indexOf("epic-implementer");
121
+ if (at < 0 || words[at + 1] !== "wait-run")
122
+ return null;
123
+ let epicRunId;
124
+ let generation;
125
+ for (let i = at + 2; i < words.length; i += 1) {
126
+ const word = words[i];
127
+ const [name, inline] = word.includes("=") ? [word.slice(0, word.indexOf("=")), word.slice(word.indexOf("=") + 1)] : [word, undefined];
128
+ if (name !== "--epic-run-id" && name !== "--driver-generation")
129
+ continue;
130
+ const value = inline ?? words[i + 1];
131
+ if (inline === undefined)
132
+ i += 1;
133
+ if (value === undefined)
134
+ return null;
135
+ if (name === "--epic-run-id")
136
+ epicRunId = value;
137
+ else
138
+ generation = value;
139
+ }
140
+ return epicRunId !== undefined && generation !== undefined ? { epicRunId, generation } : null;
141
+ }
@@ -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
+ }