@bridge_gpt/mcp-server 0.2.73 → 0.2.75

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 (123) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agent-launchers/prompt.js +9 -21
  4. package/build/agents.generated.js +4 -4
  5. package/build/authored-plan.js +542 -0
  6. package/build/bridge-config.js +7 -1
  7. package/build/bridge-permissions.js +11 -0
  8. package/build/command-provisioning.js +4 -3
  9. package/build/commands.generated.js +6 -6
  10. package/build/conductor/bridge-api-client.js +692 -47
  11. package/build/conductor/command-drift.js +1 -1
  12. package/build/conductor/declared-extras.js +335 -0
  13. package/build/conductor/doctor.js +2 -0
  14. package/build/conductor/driver-pass-output.js +104 -0
  15. package/build/conductor/driver-pass.js +571 -0
  16. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  17. package/build/conductor/epic-implementer-cli.js +370 -93
  18. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  19. package/build/conductor/epic-server-sfcc.js +58 -80
  20. package/build/conductor/epic-server.js +57 -4
  21. package/build/conductor/gate-discovery.js +253 -13
  22. package/build/conductor/gate-settings-review.js +58 -25
  23. package/build/conductor/launch-plan.js +58 -12
  24. package/build/conductor/open-decision-phrases.js +50 -0
  25. package/build/conductor/prerequisite-inputs.js +181 -14
  26. package/build/connect-github-api.js +18 -0
  27. package/build/connect-github.js +35 -18
  28. package/build/credential-delivery.js +280 -0
  29. package/build/credential-launch-safety.js +142 -0
  30. package/build/credential-materialization.js +91 -16
  31. package/build/credential-references-node-deps.js +29 -0
  32. package/build/credential-references.js +1394 -0
  33. package/build/credential-references.test-fixtures.js +211 -0
  34. package/build/credential-scan-conventions.js +145 -0
  35. package/build/credential-scan.js +517 -0
  36. package/build/credential-store.js +50 -0
  37. package/build/credentials-cli.js +252 -3
  38. package/build/dependency-install-declarations.js +47 -1
  39. package/build/docs.generated.js +8 -1
  40. package/build/doctor.js +41 -0
  41. package/build/drive-epic.js +684 -49
  42. package/build/epic-branch-ci-summary.js +18 -1
  43. package/build/epic-capability-statement.js +71 -3
  44. package/build/epic-ci-workflow-drift.js +52 -13
  45. package/build/epic-ci-workflow-install.js +31 -6
  46. package/build/epic-ci-workflow-v3.js +273 -0
  47. package/build/epic-ci-workflow.js +129 -7
  48. package/build/epic-implementer-bin.js +288 -83
  49. package/build/epic-implementer-bundle-cli.js +61 -0
  50. package/build/epic-implementer-claude-hook-bin.js +1 -1
  51. package/build/epic-implementer-env.js +3 -4
  52. package/build/epic-integration-pr.js +5 -2
  53. package/build/epic-launch-context.js +102 -7
  54. package/build/epic-server-record.js +30 -15
  55. package/build/executor/completion-contract.js +24 -1
  56. package/build/executor/credential-delivery-step.js +168 -0
  57. package/build/executor/deps.js +3 -1
  58. package/build/executor/env.js +39 -1
  59. package/build/executor/epic-server-context.js +23 -7
  60. package/build/executor/gate-qualification-job.js +193 -23
  61. package/build/executor/gate-qualification-tests-ran.js +232 -0
  62. package/build/executor/guarded-fast-forward-push.js +13 -8
  63. package/build/executor/job-runner.js +167 -738
  64. package/build/executor/job-type-wrappers.js +734 -0
  65. package/build/executor/permissions.js +85 -3
  66. package/build/executor/preflight.js +6 -2
  67. package/build/executor/process-containment.js +8 -1
  68. package/build/executor/prompt-spec.js +37 -3
  69. package/build/executor/required-verification.js +28 -2
  70. package/build/executor/runner.js +4 -1
  71. package/build/executor/types.js +9 -0
  72. package/build/executor/worker-database.js +6 -1
  73. package/build/executor/worker-guard-hook.js +24 -2
  74. package/build/executor-launch.js +4 -2
  75. package/build/generated/ticket-status.js +20 -0
  76. package/build/git-exclude-lock.js +187 -0
  77. package/build/index.js +589 -326
  78. package/build/install-bridge-conductor-answers.js +112 -22
  79. package/build/install-bridge-conductor-apply.js +38 -1
  80. package/build/install-bridge-conductor-assessment.js +482 -53
  81. package/build/install-bridge-conductor-compact.js +29 -2
  82. package/build/install-bridge-conductor-contracts.js +10 -1
  83. package/build/install-bridge-conductor-gate.js +379 -89
  84. package/build/install-bridge-conductor-setup.js +46 -8
  85. package/build/install-bridge-conductor-trial-report.js +170 -0
  86. package/build/install-bridge-conductor.js +925 -141
  87. package/build/install-bridge.js +88 -11
  88. package/build/install-doctor.js +38 -8
  89. package/build/install-sfcc-detection.js +120 -0
  90. package/build/install-sfcc-setup.js +185 -0
  91. package/build/mcp-grant-candidates.js +108 -96
  92. package/build/mcp-invoke.js +168 -4
  93. package/build/mcp-provisioning.js +21 -4
  94. package/build/mcp-server-invocation.js +13 -0
  95. package/build/merge-workflow-install.js +9 -1
  96. package/build/pipelines.generated.js +8 -7
  97. package/build/plan-generation.js +17 -0
  98. package/build/plane/status.js +8 -2
  99. package/build/printed-remedy-commands.js +59 -0
  100. package/build/project-root.js +40 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-state-paths.js +5 -2
  103. package/build/repository-toolchains.js +16 -7
  104. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  105. package/build/setup-epic.js +126 -16
  106. package/build/sfcc/credentials.js +3 -2
  107. package/build/sfcc/hostname.js +98 -2
  108. package/build/sfcc/tool-wrapper.js +6 -95
  109. package/build/start-tickets.js +193 -29
  110. package/build/test-support/executor-source-files.js +200 -0
  111. package/build/testing-config-client.js +25 -2
  112. package/build/third-party-mcp-targets.js +35 -4
  113. package/build/v2-readiness-requirements.js +5 -1
  114. package/build/version.generated.js +3 -3
  115. package/build/with-credentials.js +208 -0
  116. package/build/worker-guard-hook-bin.js +2 -2
  117. package/build/worktree-credential-delivery.js +340 -0
  118. package/docs/EPIC-IMPLEMENTER.md +4 -4
  119. package/docs/install/github-app.md +79 -92
  120. package/package.json +1 -1
  121. package/build/conductor/epic-reconcile.js +0 -603
  122. package/build/conductor/epic-runtime.js +0 -2020
  123. package/build/conductor/epic-state.js +0 -774
@@ -0,0 +1,571 @@
1
+ /**
2
+ * `epic-implementer driver-pass --epic-run-id <id> [--ticket-key <key>] [--json]`
3
+ * — a read-only report of the `/drive-epic-run` driver's clock facts.
4
+ *
5
+ * WHY THIS EXISTS. The driver prompt asks a model to do clock arithmetic: how
6
+ * long a ticket has gone without progress, whether a live job pauses that bound,
7
+ * whether the attach window is still open. This command does that arithmetic in
8
+ * code, from the server's own clock, so the model reads facts instead of
9
+ * computing them.
10
+ *
11
+ * WHAT IT IS NOT. It has no authority. It never decides a stop, never names a
12
+ * verb to run, and never changes anything. It performs three existing GET reads
13
+ * (explain-run, run state, conductor readiness) and writes nothing: no server
14
+ * write, no local state file, no tally, no notes log.
15
+ *
16
+ * THE SERVER CLOCK. "Now" is explain-run's `generated_at`. The local clock and
17
+ * the HTTP `Date` header are never used, so a skewed laptop cannot move a bound.
18
+ *
19
+ * FAIL OPEN, PER FIELD. A failed read, a malformed field, or a missing field
20
+ * makes only the facts that depend on it `"unknown"`, each with a closed reason
21
+ * token. The other facts survive. Credential, transport, parsing and
22
+ * computation failures all exit 0 with `status` set to `partial` or
23
+ * `unavailable`; only a usage error exits non-zero. No credential, response
24
+ * body, URL or exception text is ever printed.
25
+ *
26
+ * MEMORY-DEPENDENT FIELDS. `stale_minutes`, `transient_streak`,
27
+ * `overdue_claims`, `charged_interventions` and `checkpoint_due` need state
28
+ * across calls. A read-only command has none, so they are the literal
29
+ * `"unavailable"`. That is intentional and never lowers `status`.
30
+ *
31
+ * BAPI-1682: CLI-only and read-only. It is not an MCP tool and not a sanctioned
32
+ * verb, and nothing in the prompt calls it yet.
33
+ */
34
+ import { fetchConductorReadiness, fetchEpicRunState, fetchExplainRun, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
35
+ import { ConductorValidationError } from "./errors.js";
36
+ import { writeJsonDocument } from "./json-output.js";
37
+ import { buildUnavailableDriverPassResult, buildUnknownDriverPassTicket, formatDriverPassResult, } from "./driver-pass-output.js";
38
+ // ---------------------------------------------------------------------------
39
+ // Thresholds. Each mirrors a rule in the /drive-epic-run prompt
40
+ // (commands/src/drive-epic-run.md), counted in whole seconds.
41
+ // ---------------------------------------------------------------------------
42
+ /** Budget rule: two hours of no forward progress reaches the bound. */
43
+ export const DRIVER_PASS_PROGRESS_BOUND_SECONDS = 2 * 60 * 60;
44
+ /** Budget rule: a running job heartbeating within 10 minutes pauses the bound. */
45
+ export const DRIVER_PASS_HEARTBEAT_ALIVE_SECONDS = 10 * 60;
46
+ /** Budget rule: a heartbeat more than 2 minutes in the future is clock skew, unreliable evidence. */
47
+ export const DRIVER_PASS_HEARTBEAT_FUTURE_TOLERANCE_SECONDS = 2 * 60;
48
+ /** Guarded-holds rule: finished work gets a five-minute window to attach by itself. */
49
+ export const DRIVER_PASS_ATTACH_WINDOW_SECONDS = 5 * 60;
50
+ /** The park a finished-work attach applies to (Guarded-holds rule). */
51
+ const ATTACH_PARK_REASON = "required_work_park:required_work_incomplete";
52
+ const RUN_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
53
+ const TICKET_KEY_PATTERN = /^[A-Z][A-Z0-9_]{0,19}-\d+$/;
54
+ const TIMESTAMP_WITH_ZONE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/;
55
+ /** Command help. Printing it resolves no credentials and makes no request. */
56
+ export function getDriverPassUsage() {
57
+ return [
58
+ "Usage: epic-implementer driver-pass --epic-run-id <id> [--ticket-key <key>] [--json]",
59
+ "",
60
+ "Read-only. Report the driver's clock facts for an epic run from the server's own clock.",
61
+ "Changes nothing and decides nothing.",
62
+ "",
63
+ "Options:",
64
+ " --epic-run-id <id> Run id or epic key (required)",
65
+ " --ticket-key <key> Report one ticket instead of every ticket",
66
+ " --json Print compact JSON",
67
+ ].join("\n");
68
+ }
69
+ /**
70
+ * Parse `driver-pass` flags. Every message is fixed text: a rejected value is
71
+ * never echoed, so a hostile or secret-bearing argument cannot reach stderr.
72
+ */
73
+ export function parseDriverPassArgs(argv) {
74
+ const values = new Map();
75
+ let json = false;
76
+ for (let i = 0; i < argv.length; i += 1) {
77
+ const token = argv[i];
78
+ if (token === "-h" || token === "--help")
79
+ return { help: true };
80
+ if (!token.startsWith("--")) {
81
+ throw new ConductorValidationError("driver-pass takes no positional arguments.");
82
+ }
83
+ const eq = token.indexOf("=");
84
+ const name = eq >= 0 ? token.slice(0, eq) : token;
85
+ if (name === "--json") {
86
+ if (eq >= 0)
87
+ throw new ConductorValidationError("A driver-pass boolean flag does not take a value.");
88
+ if (json)
89
+ throw new ConductorValidationError('Flag "--json" may be given only once.');
90
+ json = true;
91
+ continue;
92
+ }
93
+ if (name !== "--epic-run-id" && name !== "--ticket-key") {
94
+ throw new ConductorValidationError('Unknown driver-pass option. Run "epic-implementer driver-pass --help" for usage.');
95
+ }
96
+ if (values.has(name)) {
97
+ throw new ConductorValidationError(`Flag "${name}" may be given only once.`);
98
+ }
99
+ let value;
100
+ if (eq >= 0) {
101
+ value = token.slice(eq + 1);
102
+ }
103
+ else {
104
+ const next = argv[i + 1];
105
+ if (next === undefined)
106
+ throw new ConductorValidationError(`Flag "${name}" requires a value.`);
107
+ value = next;
108
+ i += 1;
109
+ }
110
+ values.set(name, value);
111
+ }
112
+ const epicRunId = values.get("--epic-run-id")?.trim();
113
+ if (epicRunId === undefined || epicRunId.length === 0) {
114
+ throw new ConductorValidationError('Flag "--epic-run-id" is required for driver-pass and must be non-empty.');
115
+ }
116
+ if (!RUN_REF_PATTERN.test(epicRunId)) {
117
+ throw new ConductorValidationError('Flag "--epic-run-id" must be a run id or epic key.');
118
+ }
119
+ const parsed = { epicRunId, json };
120
+ const ticketKey = values.get("--ticket-key")?.trim();
121
+ if (values.has("--ticket-key")) {
122
+ if (ticketKey === undefined || !TICKET_KEY_PATTERN.test(ticketKey)) {
123
+ throw new ConductorValidationError('Flag "--ticket-key" must be a ticket key such as PROJ-123.');
124
+ }
125
+ parsed.ticketKey = ticketKey;
126
+ }
127
+ return parsed;
128
+ }
129
+ const MISSING = { kind: "missing" };
130
+ const NULL_TS = { kind: "null" };
131
+ const MALFORMED = { kind: "malformed" };
132
+ function isRecord(value) {
133
+ return typeof value === "object" && value !== null && !Array.isArray(value);
134
+ }
135
+ /**
136
+ * Read one timestamp field. A timestamp must carry an explicit zone: a zoneless
137
+ * string would be read in the local zone and silently shift a bound.
138
+ */
139
+ export function readTimestamp(source, key) {
140
+ if (!isRecord(source) || !(key in source))
141
+ return MISSING;
142
+ const raw = source[key];
143
+ if (raw === undefined)
144
+ return MISSING;
145
+ if (raw === null)
146
+ return NULL_TS;
147
+ if (typeof raw !== "string" || !TIMESTAMP_WITH_ZONE.test(raw))
148
+ return MALFORMED;
149
+ const ms = Date.parse(raw);
150
+ return Number.isFinite(ms) ? { kind: "valid", ms } : MALFORMED;
151
+ }
152
+ function readJobStatus(raw) {
153
+ if (typeof raw !== "string")
154
+ return "unreadable";
155
+ return raw === "queued" ? "queued" : raw === "running" ? "running" : "other";
156
+ }
157
+ function readJobFacts(raw) {
158
+ return {
159
+ status: readJobStatus(raw.status),
160
+ created_at: readTimestamp(raw, "created_at"),
161
+ started_at: readTimestamp(raw, "started_at"),
162
+ heartbeat_at: readTimestamp(raw, "heartbeat_at"),
163
+ };
164
+ }
165
+ function readJobs(block) {
166
+ if (!isRecord(block) || block.state !== "available" || !Array.isArray(block.jobs))
167
+ return "unreadable";
168
+ const jobs = [];
169
+ for (const raw of block.jobs) {
170
+ if (!isRecord(raw))
171
+ return "unreadable";
172
+ jobs.push(readJobFacts(raw));
173
+ }
174
+ return jobs;
175
+ }
176
+ /**
177
+ * Read the run-state `executor_jobs` block into per-ticket job history.
178
+ *
179
+ * Only the block as a whole can make history unreadable: it must be an object whose `state`
180
+ * is `"available"` and whose `jobs` is an array. Past that, one bad entry never poisons the
181
+ * rest. An entry that is not an object, or has no valid ticket key, belongs to no ticket and is
182
+ * dropped. An accepted job keeps its own timestamp distinctions (missing, null, malformed,
183
+ * valid), so an unreadable `created_at` stays attributable to its ticket. State jobs need no
184
+ * heartbeat; that evidence belongs to explain's outstanding jobs.
185
+ */
186
+ export function readStateJobs(block) {
187
+ if (!isRecord(block) || block.state !== "available" || !Array.isArray(block.jobs))
188
+ return "unreadable";
189
+ const byTicket = new Map();
190
+ for (const raw of block.jobs) {
191
+ if (!isRecord(raw) || typeof raw.ticket_key !== "string" || !TICKET_KEY_PATTERN.test(raw.ticket_key))
192
+ continue;
193
+ const jobs = byTicket.get(raw.ticket_key) ?? [];
194
+ jobs.push(readJobFacts(raw));
195
+ byTicket.set(raw.ticket_key, jobs);
196
+ }
197
+ return byTicket;
198
+ }
199
+ function readParkReason(raw) {
200
+ if (!("needs_human_reason" in raw) || raw.needs_human_reason === undefined)
201
+ return "unreadable";
202
+ const value = raw.needs_human_reason;
203
+ if (value === null)
204
+ return null;
205
+ return typeof value === "string" ? value : "unreadable";
206
+ }
207
+ /** A run reference matches the response's run id, or its epic key when it has one. */
208
+ function runIdentityMatches(ref, runId, epicKey) {
209
+ if (typeof runId !== "string" || runId.length === 0)
210
+ return false;
211
+ return ref === runId || (typeof epicKey === "string" && ref === epicKey);
212
+ }
213
+ /**
214
+ * Normalize an explain-run response. Returns a closed failure when the response
215
+ * is not an object or names a different run. Tickets are indexed by validated
216
+ * key, never by array position; an entry with an unusable key is dropped.
217
+ */
218
+ export function normalizeExplain(body, epicRunRef) {
219
+ if (!isRecord(body) || !isRecord(body.run) || !Array.isArray(body.tickets)) {
220
+ return { ok: false, reason: "explain_unreadable" };
221
+ }
222
+ if (!runIdentityMatches(epicRunRef, body.run.epic_run_id, body.run.epic_key)) {
223
+ return { ok: false, reason: "run_identity_mismatch" };
224
+ }
225
+ const tickets = new Map();
226
+ for (const raw of body.tickets) {
227
+ if (!isRecord(raw) || typeof raw.ticket_key !== "string" || !TICKET_KEY_PATTERN.test(raw.ticket_key))
228
+ continue;
229
+ tickets.set(raw.ticket_key, {
230
+ jobs: readJobs(raw.outstanding_jobs),
231
+ park_reason: readParkReason(raw),
232
+ parked_at: readTimestamp(raw, "parked_at"),
233
+ });
234
+ }
235
+ return { ok: true, generated_at: readTimestamp(body, "generated_at"), tickets };
236
+ }
237
+ /** Normalize a run-state response the same way. */
238
+ export function normalizeState(body, epicRunRef) {
239
+ if (!isRecord(body) || !isRecord(body.epic_run) || !Array.isArray(body.ticket_statuses)) {
240
+ return { ok: false, reason: "state_unreadable" };
241
+ }
242
+ if (!runIdentityMatches(epicRunRef, body.epic_run.epic_run_id, body.epic_run.epic_key)) {
243
+ return { ok: false, reason: "run_identity_mismatch" };
244
+ }
245
+ const tickets = new Map();
246
+ for (const raw of body.ticket_statuses) {
247
+ if (!isRecord(raw) || typeof raw.ticket_key !== "string" || !TICKET_KEY_PATTERN.test(raw.ticket_key))
248
+ continue;
249
+ tickets.set(raw.ticket_key, {
250
+ last_progress_at: readTimestamp(raw, "last_progress_at"),
251
+ created_at: readTimestamp(raw, "created_at"),
252
+ });
253
+ }
254
+ return { ok: true, tickets, executor_jobs: readStateJobs(body.executor_jobs) };
255
+ }
256
+ /**
257
+ * Normalize the readiness response. Readiness is scoped to the repository, not
258
+ * to a run, and carries no run identifier, so none is checked or invented. The
259
+ * reconciler's `stale` is meaningful only when its liveness read succeeded.
260
+ */
261
+ export function normalizeReadiness(body) {
262
+ if (!isRecord(body) || !isRecord(body.reconciler))
263
+ return { ok: false, reason: "readiness_unreadable" };
264
+ const r = body.reconciler;
265
+ const readable = r.liveness_readable === true;
266
+ const age = r.last_tick_age_seconds;
267
+ return {
268
+ ok: true,
269
+ stale: readable && typeof r.stale === "boolean" ? r.stale : "unknown",
270
+ last_tick_age_s: readable && typeof age === "number" && Number.isFinite(age) && age >= 0 ? age : "unknown",
271
+ };
272
+ }
273
+ const UNKNOWN_PROGRESS = (reason) => ({
274
+ no_progress: "unknown",
275
+ bound_reached: "unknown",
276
+ basis: "unknown",
277
+ reason,
278
+ });
279
+ /**
280
+ * Latest job by greatest valid `created_at`, whatever its status. A missing, null or malformed
281
+ * `created_at` on ANY job makes the choice unreadable: skipping that job could select an older
282
+ * one and report the wrong queue wait as fact.
283
+ */
284
+ function selectLatestJob(jobs) {
285
+ if (jobs === "unreadable")
286
+ return { kind: "unreadable" };
287
+ let best = { kind: "none" };
288
+ for (const job of jobs) {
289
+ if (job.created_at.kind !== "valid")
290
+ return { kind: "unreadable" };
291
+ if (best.kind !== "job" || job.created_at.ms > best.createdMs) {
292
+ best = { kind: "job", job, createdMs: job.created_at.ms };
293
+ }
294
+ }
295
+ return best;
296
+ }
297
+ function computeProgress(clockMs, explainTicket, stateTicket, stateJobs, explainReason, stateReason) {
298
+ if (stateReason)
299
+ return UNKNOWN_PROGRESS(stateReason);
300
+ if (explainReason)
301
+ return UNKNOWN_PROGRESS(explainReason);
302
+ if (clockMs === null)
303
+ return UNKNOWN_PROGRESS("server_clock_unreadable");
304
+ if (!stateTicket)
305
+ return UNKNOWN_PROGRESS("ticket_not_in_state");
306
+ if (!explainTicket)
307
+ return UNKNOWN_PROGRESS("ticket_not_in_explain");
308
+ // Effective basis: last_progress_at; created_at only when it is explicitly null.
309
+ let basis;
310
+ let basisMs;
311
+ const progress = stateTicket.last_progress_at;
312
+ if (progress.kind === "valid") {
313
+ basis = "last_progress_at";
314
+ basisMs = progress.ms;
315
+ }
316
+ else if (progress.kind === "null" && stateTicket.created_at.kind === "valid") {
317
+ basis = "created_at";
318
+ basisMs = stateTicket.created_at.ms;
319
+ }
320
+ else {
321
+ return UNKNOWN_PROGRESS("progress_basis_unreadable");
322
+ }
323
+ if (basisMs > clockMs)
324
+ return UNKNOWN_PROGRESS("progress_basis_in_future");
325
+ // Subtract the latest job's queue wait only when it was created strictly after the basis.
326
+ // The job comes from the state read's complete history (finished jobs included), not from
327
+ // explain, which lists only outstanding jobs. Explain still has to name the ticket above.
328
+ const latest = selectLatestJob(stateJobs);
329
+ if (latest.kind === "unreadable") {
330
+ return UNKNOWN_PROGRESS(stateJobs === "unreadable" ? "jobs_unreadable" : "queue_timestamp_unreadable");
331
+ }
332
+ let queueWaitMs = 0;
333
+ if (latest.kind === "job" && latest.createdMs > basisMs) {
334
+ // A job that never started, or whose start is missing, null or malformed, waited for an
335
+ // unknown time: subtract nothing rather than discard the whole calculation.
336
+ const started = latest.job.started_at;
337
+ if (started.kind === "valid")
338
+ queueWaitMs = Math.max(0, started.ms - latest.createdMs);
339
+ }
340
+ const elapsed = Math.max(0, Math.floor((clockMs - basisMs - queueWaitMs) / 1000));
341
+ return {
342
+ no_progress: elapsed,
343
+ bound_reached: elapsed >= DRIVER_PASS_PROGRESS_BOUND_SECONDS,
344
+ basis,
345
+ reason: null,
346
+ };
347
+ }
348
+ /** Pause evidence reads explain's OUTSTANDING jobs only; state-read history never reaches it. */
349
+ function computePause(clockMs, explainTicket, explainReason) {
350
+ const unknown = (reason) => ({
351
+ bound_paused: "unknown",
352
+ evidence_unreliable: "unknown",
353
+ reason,
354
+ });
355
+ if (explainReason)
356
+ return unknown(explainReason);
357
+ if (!explainTicket)
358
+ return unknown("ticket_not_in_explain");
359
+ const latest = selectLatestJob(explainTicket.jobs);
360
+ if (latest.kind === "unreadable") {
361
+ return unknown(explainTicket.jobs === "unreadable" ? "jobs_unreadable" : "queue_timestamp_unreadable");
362
+ }
363
+ if (latest.kind === "none")
364
+ return { bound_paused: null, evidence_unreliable: false, reason: null };
365
+ const { job } = latest;
366
+ // A status that is missing or not a string is no evidence either way. A readable but
367
+ // unfamiliar string ("other") is a confirmed non-running job and falls through below.
368
+ if (job.status === "unreadable")
369
+ return { bound_paused: "unknown", evidence_unreliable: true, reason: "jobs_unreadable" };
370
+ if (job.status === "queued")
371
+ return { bound_paused: "queued", evidence_unreliable: false, reason: null };
372
+ if (job.status !== "running")
373
+ return { bound_paused: null, evidence_unreliable: false, reason: null };
374
+ // A running job: judge its heartbeat against the server clock.
375
+ if (job.heartbeat_at.kind !== "valid") {
376
+ return { bound_paused: "unknown", evidence_unreliable: true, reason: "heartbeat_unreadable" };
377
+ }
378
+ if (clockMs === null)
379
+ return unknown("server_clock_unreadable");
380
+ const ageSeconds = (clockMs - job.heartbeat_at.ms) / 1000;
381
+ if (ageSeconds < -DRIVER_PASS_HEARTBEAT_FUTURE_TOLERANCE_SECONDS) {
382
+ return { bound_paused: "unknown", evidence_unreliable: true, reason: "heartbeat_in_future" };
383
+ }
384
+ return {
385
+ bound_paused: ageSeconds < DRIVER_PASS_HEARTBEAT_ALIVE_SECONDS ? "job_alive" : null,
386
+ evidence_unreliable: false,
387
+ reason: null,
388
+ };
389
+ }
390
+ function computeAttachWindow(clockMs, explainTicket, explainReason) {
391
+ if (explainReason)
392
+ return { value: "unknown", reason: explainReason };
393
+ if (!explainTicket)
394
+ return { value: "unknown", reason: "ticket_not_in_explain" };
395
+ const parkReason = explainTicket.park_reason;
396
+ if (parkReason === "unreadable")
397
+ return { value: "unknown", reason: "park_unreadable" };
398
+ // Only the required-work park has a window; any other confirmed reason (or no park) has none.
399
+ const applies = parkReason === ATTACH_PARK_REASON || parkReason?.startsWith(`${ATTACH_PARK_REASON} `) === true;
400
+ if (!applies)
401
+ return { value: "not_applicable", reason: null };
402
+ if (explainTicket.parked_at.kind !== "valid")
403
+ return { value: "unknown", reason: "park_unreadable" };
404
+ if (clockMs === null)
405
+ return { value: "unknown", reason: "server_clock_unreadable" };
406
+ const ageSeconds = (clockMs - explainTicket.parked_at.ms) / 1000;
407
+ if (ageSeconds < 0)
408
+ return { value: "unknown", reason: "park_in_future" };
409
+ return { value: ageSeconds < DRIVER_PASS_ATTACH_WINDOW_SECONDS ? "open" : "elapsed", reason: null };
410
+ }
411
+ function ticketFactsKnown(t) {
412
+ return [
413
+ t.no_progress !== "unknown",
414
+ t.bound_reached !== "unknown",
415
+ t.bound_paused !== "unknown",
416
+ t.evidence_unreliable !== "unknown",
417
+ t.attach_window !== "unknown",
418
+ ];
419
+ }
420
+ /**
421
+ * Compute the full result from already-normalized reads. Pure: it never touches
422
+ * the network, the filesystem, or any clock. Reads join only by validated run
423
+ * identity and ticket key.
424
+ */
425
+ export function calculateDriverPassResult(reads) {
426
+ const explainOk = reads.explain.ok ? reads.explain : null;
427
+ const stateOk = reads.state.ok ? reads.state : null;
428
+ const explainReason = reads.explain.ok ? null : reads.explain.reason;
429
+ const stateReason = reads.state.ok ? null : reads.state.reason;
430
+ // Each response was already checked against the requested run; a mismatch is a run-level reason.
431
+ const runReasons = new Set();
432
+ if (!reads.explain.ok)
433
+ runReasons.add(reads.explain.reason);
434
+ if (!reads.state.ok)
435
+ runReasons.add(reads.state.reason);
436
+ if (!reads.readiness.ok)
437
+ runReasons.add(reads.readiness.reason);
438
+ const clock = explainOk?.generated_at;
439
+ const clockMs = clock && clock.kind === "valid" ? clock.ms : null;
440
+ if (explainOk && clockMs === null)
441
+ runReasons.add("server_clock_unreadable");
442
+ const keys = new Set();
443
+ if (reads.ticketKey !== undefined) {
444
+ keys.add(reads.ticketKey);
445
+ }
446
+ else {
447
+ for (const k of explainOk?.tickets.keys() ?? [])
448
+ keys.add(k);
449
+ for (const k of stateOk?.tickets.keys() ?? [])
450
+ keys.add(k);
451
+ }
452
+ const tickets = [];
453
+ for (const key of [...keys].sort()) {
454
+ const explainTicket = explainOk?.tickets.get(key);
455
+ const stateTicket = stateOk?.tickets.get(key);
456
+ // A requested ticket neither readable response lists has unestablished membership.
457
+ if (reads.ticketKey !== undefined && !explainTicket && !stateTicket) {
458
+ const reason = explainReason ?? stateReason ?? "ticket_not_in_explain";
459
+ tickets.push(buildUnknownDriverPassTicket(key, reason));
460
+ continue;
461
+ }
462
+ // A confirmed absent entry in an available history is an empty collection; an unavailable
463
+ // history is not. Only progress depends on it.
464
+ const stateJobs = stateOk === null || stateOk.executor_jobs === "unreadable"
465
+ ? "unreadable"
466
+ : (stateOk.executor_jobs.get(key) ?? []);
467
+ const progress = computeProgress(clockMs, explainTicket, stateTicket, stateJobs, explainReason, stateReason);
468
+ const pause = computePause(clockMs, explainTicket, explainReason);
469
+ const attach = computeAttachWindow(clockMs, explainTicket, explainReason);
470
+ tickets.push({
471
+ ticket_key: key,
472
+ no_progress: progress.no_progress,
473
+ bound_reached: progress.bound_reached,
474
+ basis: progress.basis,
475
+ bound_paused: pause.bound_paused,
476
+ evidence_unreliable: pause.evidence_unreliable,
477
+ attach_window: attach.value,
478
+ stale_minutes: "unavailable",
479
+ transient_streak: "unavailable",
480
+ charged_interventions: "unavailable",
481
+ reasons: { progress: progress.reason, pause: pause.reason, attach_window: attach.reason },
482
+ });
483
+ }
484
+ const reconciler = reads.readiness.ok
485
+ ? { stale: reads.readiness.stale, last_tick_age_s: reads.readiness.last_tick_age_s }
486
+ : { stale: "unknown", last_tick_age_s: "unknown" };
487
+ // Status counts applicable facts only; the memory-dependent fields never count.
488
+ const known = [reconciler.stale !== "unknown", reconciler.last_tick_age_s !== "unknown"];
489
+ for (const t of tickets)
490
+ known.push(...ticketFactsKnown(t));
491
+ const knownCount = known.filter(Boolean).length;
492
+ // A failed read makes its facts unavailable even when no ticket record exists to show it.
493
+ const allReadsOk = reads.explain.ok && reads.state.ok && reads.readiness.ok;
494
+ const status = knownCount === 0 ? "unavailable" : knownCount === known.length && allReadsOk ? "complete" : "partial";
495
+ return {
496
+ epic_run_id: reads.epicRunId,
497
+ status,
498
+ generated_at: clockMs === null ? "unknown" : new Date(clockMs).toISOString(),
499
+ reconciler,
500
+ overdue_claims: "unavailable",
501
+ checkpoint_due: "unavailable",
502
+ reasons: [...runReasons].sort(),
503
+ tickets,
504
+ };
505
+ }
506
+ async function guardedRead(read, normalize, failure) {
507
+ try {
508
+ return normalize(await read());
509
+ }
510
+ catch {
511
+ // The reason is a fixed token; the thrown value is never inspected or printed.
512
+ return { ok: false, reason: failure };
513
+ }
514
+ }
515
+ /**
516
+ * Run `driver-pass`. Never throws. Returns 0 for every outcome except a usage
517
+ * error, which returns 1 with a fixed message.
518
+ */
519
+ export async function runDriverPassCommand(argv, deps = {}) {
520
+ const writeStdout = deps.writeStdout ?? ((text) => writeJsonDocument(text));
521
+ const writeStderr = deps.writeStderr ?? ((line) => console.error(line));
522
+ let args;
523
+ try {
524
+ args = parseDriverPassArgs(argv);
525
+ }
526
+ catch (err) {
527
+ writeStderr(`Error: ${err instanceof ConductorValidationError ? err.message : "driver-pass: invalid arguments."}`);
528
+ return 1;
529
+ }
530
+ if ("help" in args) {
531
+ await writeStdout(getDriverPassUsage());
532
+ return 0;
533
+ }
534
+ const emit = async (result) => {
535
+ try {
536
+ await writeStdout(args.json ? JSON.stringify(result) : formatDriverPassResult(result));
537
+ }
538
+ catch {
539
+ // Advisory output: a closed pipe never turns into a failure.
540
+ }
541
+ return 0;
542
+ };
543
+ const unavailable = (reason) => emit(buildUnavailableDriverPassResult(args.epicRunId, reason, args.ticketKey));
544
+ try {
545
+ let access = null;
546
+ try {
547
+ const resolved = await (deps.resolveAccess ??
548
+ (() => resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true })))();
549
+ access = resolved.ok ? resolved.access : null;
550
+ }
551
+ catch {
552
+ access = null;
553
+ }
554
+ if (!access)
555
+ return await unavailable("credentials_unavailable");
556
+ const ref = args.epicRunId;
557
+ const fetchExplain = deps.fetchExplain ?? ((a, id) => fetchExplainRun(a, id));
558
+ const fetchState = deps.fetchState ?? ((a, id) => fetchEpicRunState(a, id));
559
+ const fetchReadiness = deps.fetchReadiness ?? ((a) => fetchConductorReadiness(a));
560
+ const [explain, state, readiness] = await Promise.all([
561
+ guardedRead(() => fetchExplain(access, ref), (b) => normalizeExplain(b, ref), "explain_unreadable"),
562
+ guardedRead(() => fetchState(access, ref), (b) => normalizeState(b, ref), "state_unreadable"),
563
+ guardedRead(() => fetchReadiness(access), normalizeReadiness, "readiness_unreadable"),
564
+ ]);
565
+ return await emit(calculateDriverPassResult({ epicRunId: ref, ticketKey: args.ticketKey, explain, state, readiness }));
566
+ }
567
+ catch {
568
+ // Any unexpected failure becomes the standard unavailable schema, never text.
569
+ return await unavailable("computation_failed");
570
+ }
571
+ }