@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,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,104 @@
1
+ /**
2
+ * Result types and terminal formatting for `epic-implementer driver-pass`.
3
+ *
4
+ * This module is deliberately dependency-light: it imports nothing, so the CLI
5
+ * can still print a full "unavailable" result when the command module itself
6
+ * (and the HTTP client behind it) fails to load.
7
+ *
8
+ * Every public field is present in every result, in every variant. A fact that
9
+ * could not be read is the literal `"unknown"`. A fact that this read-only
10
+ * command cannot compute at all, because it needs memory across calls, is the
11
+ * literal `"unavailable"`. The second kind is intentional and never lowers the
12
+ * result's completeness.
13
+ *
14
+ * Nothing here ever carries a recommendation, a command to run, a policy
15
+ * judgment, exception text, or a raw upstream string. Every string value comes
16
+ * from a closed vocabulary below, a validated identifier, or a normalized
17
+ * timestamp.
18
+ */
19
+ /** Closed failure and unknown-reason tokens. Never built from upstream text. */
20
+ export const DRIVER_PASS_REASONS = [
21
+ "credentials_unavailable",
22
+ "explain_unreadable",
23
+ "state_unreadable",
24
+ "readiness_unreadable",
25
+ "run_identity_mismatch",
26
+ "computation_failed",
27
+ "server_clock_unreadable",
28
+ "ticket_not_in_explain",
29
+ "ticket_not_in_state",
30
+ "jobs_unreadable",
31
+ "progress_basis_unreadable",
32
+ "progress_basis_in_future",
33
+ "queue_timestamp_unreadable",
34
+ "heartbeat_unreadable",
35
+ "heartbeat_in_future",
36
+ "park_unreadable",
37
+ "park_in_future",
38
+ ];
39
+ const REASON_SET = new Set(DRIVER_PASS_REASONS);
40
+ /** True when `value` is one of the closed reason tokens. */
41
+ export function isDriverPassReason(value) {
42
+ return typeof value === "string" && REASON_SET.has(value);
43
+ }
44
+ /** An all-unknown ticket record carrying one reason on every unreadable fact. */
45
+ export function buildUnknownDriverPassTicket(ticketKey, reason) {
46
+ return {
47
+ ticket_key: ticketKey,
48
+ no_progress: "unknown",
49
+ bound_reached: "unknown",
50
+ basis: "unknown",
51
+ bound_paused: "unknown",
52
+ evidence_unreliable: "unknown",
53
+ attach_window: "unknown",
54
+ stale_minutes: "unavailable",
55
+ transient_streak: "unavailable",
56
+ charged_interventions: "unavailable",
57
+ reasons: { progress: reason, pause: reason, attach_window: reason },
58
+ };
59
+ }
60
+ /**
61
+ * Build the full-schema result for a command that read nothing. Needs no
62
+ * credentials, no response payload and no HTTP module. When a ticket filter
63
+ * was supplied, the single requested ticket appears as an unknown record.
64
+ */
65
+ export function buildUnavailableDriverPassResult(epicRunId, reason, ticketKey) {
66
+ return {
67
+ epic_run_id: epicRunId,
68
+ status: "unavailable",
69
+ generated_at: "unknown",
70
+ reconciler: { stale: "unknown", last_tick_age_s: "unknown" },
71
+ overdue_claims: "unavailable",
72
+ checkpoint_due: "unavailable",
73
+ reasons: [reason],
74
+ tickets: ticketKey === undefined ? [] : [buildUnknownDriverPassTicket(ticketKey, reason)],
75
+ };
76
+ }
77
+ function token(value) {
78
+ return value === null ? "null" : String(value);
79
+ }
80
+ function compareKeys(a, b) {
81
+ return a < b ? -1 : a > b ? 1 : 0;
82
+ }
83
+ /**
84
+ * Render a result as plain key/value lines: run status first, reconciler facts
85
+ * second, grouped per-ticket facts last. Machine tokens are printed verbatim.
86
+ * The text never contains advice, a command, or any upstream string.
87
+ */
88
+ export function formatDriverPassResult(result) {
89
+ const lines = [
90
+ `status: ${result.status}`,
91
+ `epic_run_id: ${result.epic_run_id}`,
92
+ `generated_at: ${result.generated_at}`,
93
+ `reasons: ${result.reasons.length === 0 ? "none" : [...result.reasons].sort().join(",")}`,
94
+ `reconciler.stale: ${token(result.reconciler.stale)}`,
95
+ `reconciler.last_tick_age_s: ${token(result.reconciler.last_tick_age_s)}`,
96
+ `overdue_claims: ${result.overdue_claims}`,
97
+ `checkpoint_due: ${result.checkpoint_due}`,
98
+ ];
99
+ const tickets = [...result.tickets].sort((a, b) => compareKeys(a.ticket_key, b.ticket_key));
100
+ for (const ticket of tickets) {
101
+ lines.push("", `ticket: ${ticket.ticket_key}`, ` no_progress: ${token(ticket.no_progress)}`, ` bound_reached: ${token(ticket.bound_reached)}`, ` basis: ${ticket.basis}`, ` bound_paused: ${token(ticket.bound_paused)}`, ` evidence_unreliable: ${token(ticket.evidence_unreliable)}`, ` attach_window: ${ticket.attach_window}`, ` stale_minutes: ${ticket.stale_minutes}`, ` transient_streak: ${ticket.transient_streak}`, ` charged_interventions: ${ticket.charged_interventions}`, ` reason.progress: ${ticket.reasons.progress ?? "none"}`, ` reason.pause: ${ticket.reasons.pause ?? "none"}`, ` reason.attach_window: ${ticket.reasons.attach_window ?? "none"}`);
102
+ }
103
+ return lines.join("\n");
104
+ }