@bridge_gpt/mcp-server 0.2.72 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -11,7 +11,7 @@
11
11
  * AN INCIDENT is one of:
12
12
  * - a park, identified by `(ticket_key, parked_at)`;
13
13
  * - a ticket with a non-null `needs_human_reason`;
14
- * - a failed or dead-letter executor job, identified by its id;
14
+ * - a dead-letter executor job, identified by its id;
15
15
  * - a paused or stopped run-control state;
16
16
  * - a run status other than `active`.
17
17
  *
@@ -31,7 +31,7 @@ import { createHash } from "node:crypto";
31
31
  export const WAIT_RUN_ATTENTION_TOKEN_PATTERN = /^a1:[0-9a-f]{16}$/;
32
32
  /** At most this many incidents are listed in one wake result. */
33
33
  export const WAIT_RUN_MAX_INCIDENTS = 20;
34
- const FAILED_JOB_STATUSES = new Set(["failed", "dead_letter"]);
34
+ const FAILED_JOB_STATUSES = new Set(["dead_letter"]);
35
35
  function compareStrings(a, b) {
36
36
  return a < b ? -1 : a > b ? 1 : 0;
37
37
  }
@@ -26,10 +26,21 @@
26
26
  * something changed since that token, never what, so that result carries no
27
27
  * field history.
28
28
  *
29
- * THE WAIT. The window is governed entirely by the shared {@link boundedWait}
30
- * primitive (BAPI-1104): its immediate first probe, its 15 s / 30 s polling
31
- * curve, its per-probe cap, and its three-consecutive-failure transient rule.
32
- * This module adds no deadline logic of its own.
29
+ * THE WAIT. A single window is governed entirely by the shared
30
+ * {@link boundedWait} primitive (BAPI-1104): its immediate first probe, its
31
+ * 15 s / 30 s polling curve, its per-probe cap, and its three-consecutive-failure
32
+ * transient rule. A legacy call (no `--watch`) is exactly one such window and adds
33
+ * no deadline logic of its own.
34
+ *
35
+ * WATCH (BAPI-1641). `--watch` repeats attention-mode windows under ONE absolute
36
+ * deadline (`--max-minutes`, default 20, at most 60) so a supervisor can run the
37
+ * command as a single background task and be woken only by a new incident, a
38
+ * finished run, a non-transient failure, or that deadline. The deadline is fixed
39
+ * once, before access resolution; every inner window and every retry sleep is
40
+ * clamped to what remains of it, and no state read starts after it. The attention
41
+ * baseline lives outside the window loop, and the token and run status a deadline
42
+ * result reports come only from the last COMPLETE observation. Watch still reads
43
+ * only the state route, writes nothing, and prints one final stdout line.
33
44
  *
34
45
  * OUTPUT. A successful result is ONE final stdout write (one JSON line with
35
46
  * `--json`, or one status line plus at most 20 change lines) and exits 0. A
@@ -41,6 +52,7 @@ import { createHash } from "node:crypto";
41
52
  import { boundedWait as defaultBoundedWait, } from "../bounded-wait.js";
42
53
  import { ConductorBridgeApiError, fetchEpicRunState, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
43
54
  import { ConductorValidationError } from "./errors.js";
55
+ import { DRIVER_GENERATION_PATTERN } from "./driver-session-state.js";
44
56
  import { writeJsonDocument } from "./json-output.js";
45
57
  import { WAIT_RUN_ATTENTION_TOKEN_PATTERN, WAIT_RUN_MAX_INCIDENTS, attentionIds, buildWaitRunAttention, buildWaitRunAttentionToken, executorJobEvidenceReadable, newIncidents, } from "./wait-run-attention.js";
46
58
  // ---------------------------------------------------------------------------
@@ -50,6 +62,18 @@ import { WAIT_RUN_ATTENTION_TOKEN_PATTERN, WAIT_RUN_MAX_INCIDENTS, attentionIds,
50
62
  export const WAIT_RUN_DEFAULT_TIMEOUT_SECONDS = 110;
51
63
  /** Largest accepted window, in seconds — the bounded-wait primitive's own ceiling. */
52
64
  export const WAIT_RUN_MAX_TIMEOUT_SECONDS = 240;
65
+ /** BAPI-1641 — each inner window of a `--watch` call, in seconds. `--timeout` may lower it. */
66
+ export const WAIT_RUN_WATCH_WINDOW_SECONDS = 240;
67
+ /** BAPI-1641 — the default total `--watch` duration, in minutes. */
68
+ export const WAIT_RUN_WATCH_DEFAULT_MAX_MINUTES = 20;
69
+ /** BAPI-1641 — the largest accepted `--max-minutes`; larger values clamp to it. */
70
+ export const WAIT_RUN_WATCH_MAX_MINUTES = 60;
71
+ /**
72
+ * BAPI-1641 — the pause before another window starts after a window ended in
73
+ * `UPSTREAM_TRANSIENT`. It matches the primitive's initial polling delay and is
74
+ * always clamped to the time left before the watch deadline.
75
+ */
76
+ export const WAIT_RUN_WATCH_RETRY_DELAY_MS = 15_000;
53
77
  /** At most this many change lines are rendered per result. */
54
78
  export const WAIT_RUN_MAX_CHANGES = 20;
55
79
  /** BAPI-1532 — at most this many tickets are listed in a since-mismatch `current` block. */
@@ -75,8 +99,24 @@ const WAIT_RUN_VALUE_FLAGS = new Set([
75
99
  "--since",
76
100
  "--timeout",
77
101
  "--until",
102
+ "--max-minutes",
103
+ "--driver-generation",
78
104
  ]);
79
- const WAIT_RUN_BOOL_FLAGS = new Set(["--json", "--help"]);
105
+ const WAIT_RUN_BOOL_FLAGS = new Set(["--json", "--help", "--watch"]);
106
+ /**
107
+ * Parse a `--max-minutes` spelling into whole minutes, 1..60. The same
108
+ * overflow-safe shape as {@link parseTimeoutSeconds}: a very long digit string
109
+ * clamps rather than overflowing.
110
+ */
111
+ function parseMaxMinutes(raw) {
112
+ if (!/^[0-9]+$/.test(raw) || /^0+$/.test(raw)) {
113
+ throw new ConductorValidationError('Flag "--max-minutes" must be a positive whole number of minutes.');
114
+ }
115
+ const digits = raw.replace(/^0+/, "");
116
+ if (digits.length > 6)
117
+ return WAIT_RUN_WATCH_MAX_MINUTES;
118
+ return Math.min(Number(digits), WAIT_RUN_WATCH_MAX_MINUTES);
119
+ }
80
120
  /**
81
121
  * Parse a `--timeout` spelling into the effective window in seconds.
82
122
  *
@@ -101,6 +141,7 @@ function parseTimeoutSeconds(raw) {
101
141
  export function parseWaitRunArgs(argv) {
102
142
  const values = new Map();
103
143
  let json = false;
144
+ let watch = false;
104
145
  for (let i = 0; i < argv.length; i += 1) {
105
146
  const token = argv[i];
106
147
  if (token === "-h" || token === "--help") {
@@ -109,6 +150,8 @@ export function parseWaitRunArgs(argv) {
109
150
  epicRunId: "",
110
151
  timeoutSeconds: WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
111
152
  json: false,
153
+ watch: false,
154
+ maxMinutes: WAIT_RUN_WATCH_DEFAULT_MAX_MINUTES,
112
155
  until: "change",
113
156
  };
114
157
  }
@@ -121,7 +164,10 @@ export function parseWaitRunArgs(argv) {
121
164
  if (eq >= 0) {
122
165
  throw new ConductorValidationError("A wait-run boolean flag does not take a value.");
123
166
  }
124
- json = true;
167
+ if (name === "--watch")
168
+ watch = true;
169
+ else
170
+ json = true;
125
171
  continue;
126
172
  }
127
173
  if (!WAIT_RUN_VALUE_FLAGS.has(name)) {
@@ -148,17 +194,32 @@ export function parseWaitRunArgs(argv) {
148
194
  const parsed = {
149
195
  help: false,
150
196
  epicRunId: epicRunId.trim(),
151
- timeoutSeconds: WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
197
+ timeoutSeconds: watch ? WAIT_RUN_WATCH_WINDOW_SECONDS : WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
152
198
  json,
153
- until: "change",
199
+ watch,
200
+ maxMinutes: WAIT_RUN_WATCH_DEFAULT_MAX_MINUTES,
201
+ until: watch ? "attention" : "change",
154
202
  };
155
203
  const until = values.get("--until");
156
204
  if (until !== undefined) {
157
205
  if (until !== "change" && until !== "attention") {
158
206
  throw new ConductorValidationError('Flag "--until" must be "change" or "attention".');
159
207
  }
208
+ // Watch is attention-only. The default "change" is not an explicit choice,
209
+ // so only a SUPPLIED `--until change` is refused.
210
+ if (watch && until === "change") {
211
+ throw new ConductorValidationError('Flag "--watch" runs in attention mode; "--until change" cannot be used with it.');
212
+ }
160
213
  parsed.until = until;
161
214
  }
215
+ const maxMinutes = values.get("--max-minutes");
216
+ if (maxMinutes !== undefined) {
217
+ const minutes = parseMaxMinutes(maxMinutes);
218
+ if (!watch) {
219
+ throw new ConductorValidationError('Flag "--max-minutes" requires "--watch".');
220
+ }
221
+ parsed.maxMinutes = minutes;
222
+ }
162
223
  const ticketKey = values.get("--ticket-key");
163
224
  if (ticketKey !== undefined) {
164
225
  if (ticketKey.trim().length === 0) {
@@ -181,12 +242,19 @@ export function parseWaitRunArgs(argv) {
181
242
  if (timeout !== undefined) {
182
243
  parsed.timeoutSeconds = parseTimeoutSeconds(timeout);
183
244
  }
245
+ const driverGeneration = values.get("--driver-generation");
246
+ if (driverGeneration !== undefined) {
247
+ if (!DRIVER_GENERATION_PATTERN.test(driverGeneration)) {
248
+ throw new ConductorValidationError('Flag "--driver-generation" must be the generation driver-register printed (32 hex characters).');
249
+ }
250
+ parsed.driverGeneration = driverGeneration;
251
+ }
184
252
  return parsed;
185
253
  }
186
254
  /** Command-specific help. Printing it resolves no credentials and makes no request. */
187
255
  export function getWaitRunUsage() {
188
256
  return [
189
- "Usage: epic-implementer wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>] [--until change|attention] [--json]",
257
+ "Usage: epic-implementer wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>] [--until change|attention] [--json] [--watch [--max-minutes <minutes>]] [--driver-generation <g>]",
190
258
  "",
191
259
  "Read-only. Wait until an epic run's observable state changes, the run finishes,",
192
260
  "or the window closes. Reads only the run's state route; changes nothing.",
@@ -199,13 +267,26 @@ export function getWaitRunUsage() {
199
267
  " bounded Current state (up to 20 tickets, parked first), not a diff",
200
268
  ` --timeout <seconds> Wait window (default ${WAIT_RUN_DEFAULT_TIMEOUT_SECONDS}; values above ${WAIT_RUN_MAX_TIMEOUT_SECONDS} are clamped to ${WAIT_RUN_MAX_TIMEOUT_SECONDS})`,
201
269
  " --until <mode> change (default): wake on any projected change. attention: wake only",
202
- " when a NEW incident appears (a park, a needs-human reason, a failed or",
270
+ " when a NEW incident appears (a park, a needs-human reason, a",
203
271
  " dead-letter job, a paused or stopped run, a non-active run). Attention",
204
272
  " tokens start with a1:; reuse one only with the same run, ticket and mode",
273
+ " --watch Repeat attention windows under one absolute deadline and print one",
274
+ " result when a new incident appears, the run finishes, a read fails",
275
+ " for good, or the deadline passes. Implies --until attention (an",
276
+ " explicit --until attention is accepted; --until change is rejected).",
277
+ " Each inner window defaults to 240 seconds; --timeout may lower it",
278
+ " --max-minutes <n> With --watch only: the total duration (default 20; values above 60",
279
+ " are clamped to 60). Without --watch it is rejected. Every window",
280
+ " and pause is clamped to the time left, and no read starts after it.",
281
+ " Under --watch, window_seconds is this configured total (minutes x 60),",
282
+ " not elapsed time and not the last inner window",
205
283
  " --json Print one JSON line",
284
+ " --driver-generation <g> The generation driver-register printed. An inert label the",
285
+ " driver guard recognizes the waiter by; it changes nothing about the wait",
206
286
  "",
207
287
  "Outcomes (all exit 0): changed, terminal (run done or abandoned), pending",
208
- "(WAIT_WINDOW_ELAPSED or UPSTREAM_TRANSIENT — run wait-run again).",
288
+ "(WAIT_WINDOW_ELAPSED or UPSTREAM_TRANSIENT — read the result, then run wait-run again).",
289
+ "A --watch pending result carries the token of the last complete observation.",
209
290
  "Failures exit 1 with one line on stderr and nothing on stdout.",
210
291
  "",
211
292
  "Example:",
@@ -626,6 +707,10 @@ function describeTerminalReadFailure(err) {
626
707
  }
627
708
  return UNEXPECTED_FAILURE_MESSAGE;
628
709
  }
710
+ /** The production monotonic clock, as in the bounded-wait primitive. */
711
+ const monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function"
712
+ ? performance.now()
713
+ : Date.now();
629
714
  /** Reject promptly when the bounded wait aborts this probe, so a hung read costs one probe. */
630
715
  function untilAborted(work, signal) {
631
716
  if (signal.aborted)
@@ -677,8 +762,61 @@ export async function runWaitRunCommand(argv, deps = {}) {
677
762
  return 0;
678
763
  return fail("wait-run: the help text could not be written to stdout.");
679
764
  }
680
- const resolveAccess = deps.resolveAccess ?? (() => resolveConductorBridgeApiAccess());
681
- const accessResult = await resolveAccess();
765
+ // BAPI-1641: ONE clock and ONE absolute deadline for the whole watch, fixed
766
+ // before access resolution or any other asynchronous setup. A legacy call never
767
+ // reads either.
768
+ const clock = deps.now ?? deps.waitDeps?.now ?? monotonicNow;
769
+ const watchDeadlineMs = parsed.watch ? clock() + parsed.maxMinutes * 60_000 : 0;
770
+ const watchTimers = {
771
+ setTimer: deps.waitDeps?.setTimer ?? ((cb, ms) => setTimeout(cb, ms)),
772
+ clearTimer: deps.waitDeps?.clearTimer ?? ((handle) => clearTimeout(handle)),
773
+ };
774
+ // `window_seconds` is the configured total under --watch (not elapsed time, not
775
+ // the last inner window) and the single window otherwise.
776
+ const windowSeconds = parsed.watch ? parsed.maxMinutes * 60 : parsed.timeoutSeconds;
777
+ // The last token and run status reported. Under --watch they are the last
778
+ // COMPLETE observation only, and start empty rather than copying `--since`.
779
+ let latestToken = parsed.watch ? null : (parsed.since ?? null);
780
+ let latestRunStatus = null;
781
+ // BAPI-1641: true from a failed or incomplete read until the next complete
782
+ // observation. It outlives each inner window, which resets its own counter.
783
+ let failedSinceGood = false;
784
+ const deadlinePending = () => ({
785
+ outcome: "pending",
786
+ reason: failedSinceGood ? "UPSTREAM_TRANSIENT" : "WAIT_WINDOW_ELAPSED",
787
+ token: latestToken,
788
+ window_seconds: windowSeconds,
789
+ run_status: latestRunStatus,
790
+ });
791
+ const finish = async (result) => {
792
+ if (await writeStdout(renderWaitRunResult(result, parsed.json)))
793
+ return 0;
794
+ return fail("wait-run: the result could not be written to stdout.");
795
+ };
796
+ const resolveAccess = deps.resolveAccess ?? (() => resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true }));
797
+ let accessResult;
798
+ if (parsed.watch) {
799
+ // Setup is bounded by the same deadline: a resolver that outlasts it yields
800
+ // the pending result, never a state read.
801
+ let setupTimer;
802
+ const expired = new Promise((resolve) => {
803
+ setupTimer = watchTimers.setTimer(() => resolve("deadline"), Math.max(1, watchDeadlineMs - clock()));
804
+ });
805
+ try {
806
+ accessResult = await Promise.race([resolveAccess(), expired]);
807
+ }
808
+ finally {
809
+ watchTimers.clearTimer(setupTimer);
810
+ }
811
+ if (accessResult !== "deadline" && accessResult.ok && clock() >= watchDeadlineMs) {
812
+ accessResult = "deadline";
813
+ }
814
+ }
815
+ else {
816
+ accessResult = await resolveAccess();
817
+ }
818
+ if (accessResult === "deadline")
819
+ return await finish(deadlinePending());
682
820
  if (!accessResult.ok) {
683
821
  // The shared resolver's messages are fixed, secret-free text.
684
822
  return fail(`wait-run: ${accessResult.error}`);
@@ -686,9 +824,6 @@ export async function runWaitRunCommand(argv, deps = {}) {
686
824
  const access = accessResult.access;
687
825
  const fetchState = deps.fetchState ?? ((a, id) => fetchEpicRunState(a, id));
688
826
  const wait = deps.boundedWait ?? defaultBoundedWait;
689
- const windowSeconds = parsed.timeoutSeconds;
690
- let latestToken = parsed.since ?? null;
691
- let latestRunStatus = null;
692
827
  let baseline = null;
693
828
  let readFailure = null;
694
829
  // BAPI-1557: attention mode compares the incident set it OBSERVES against the
@@ -697,7 +832,11 @@ export async function runWaitRunCommand(argv, deps = {}) {
697
832
  const observeAttention = (snapshot) => {
698
833
  const attention = buildWaitRunAttention(snapshot);
699
834
  const token = buildWaitRunAttentionToken(attention);
700
- latestRunStatus = snapshot.run.status;
835
+ // Legacy calls record the status at once. Under --watch it is recorded only
836
+ // after the evidence check below, so an incomplete read never becomes the
837
+ // checkpoint a deadline result reports.
838
+ if (!parsed.watch)
839
+ latestRunStatus = snapshot.run.status;
701
840
  // A finished run outranks everything, as in change mode.
702
841
  if (TERMINAL_RUN_STATUSES.has(snapshot.run.status)) {
703
842
  latestToken = token;
@@ -712,9 +851,12 @@ export async function runWaitRunCommand(argv, deps = {}) {
712
851
  // Missing job evidence is not an empty failure set. Report it to the
713
852
  // primitive as a transient failure so the baseline is never cleared by it.
714
853
  if (!executorJobEvidenceReadable(snapshot.executor_jobs_state)) {
854
+ failedSinceGood = true;
715
855
  throw new ConductorBridgeApiError("server", 503);
716
856
  }
717
857
  latestToken = token;
858
+ latestRunStatus = snapshot.run.status;
859
+ failedSinceGood = false;
718
860
  let added;
719
861
  if (attentionBaseline === null) {
720
862
  if (parsed.since !== undefined && parsed.since === token) {
@@ -750,16 +892,26 @@ export async function runWaitRunCommand(argv, deps = {}) {
750
892
  attentionBaseline = attentionIds(attention);
751
893
  return { kind: "observation", ready: false };
752
894
  };
895
+ // BAPI-1613 R7: an epic key resolves only to a live run, so after the first
896
+ // good read every probe names the run id that read returned.
897
+ let probeRunId = parsed.epicRunId;
753
898
  const probe = async (signal) => {
899
+ // No state read starts after the watch deadline. The window budget is already
900
+ // clamped to it, so this is the belt to that brace.
901
+ if (parsed.watch && clock() >= watchDeadlineMs) {
902
+ return { kind: "observation", ready: false };
903
+ }
754
904
  let body;
755
905
  try {
756
- body = await untilAborted(fetchState(access, parsed.epicRunId), signal);
906
+ body = await untilAborted(fetchState(access, probeRunId), signal);
757
907
  }
758
908
  catch (err) {
759
909
  // A transient failure is thrown back to the primitive, which counts it
760
910
  // toward its three-in-a-row rule. Its text never reaches a result.
761
- if (isTransientReadFailure(err))
911
+ if (isTransientReadFailure(err)) {
912
+ failedSinceGood = true;
762
913
  throw err;
914
+ }
763
915
  readFailure = describeTerminalReadFailure(err);
764
916
  return { kind: "terminal" };
765
917
  }
@@ -776,6 +928,9 @@ export async function runWaitRunCommand(argv, deps = {}) {
776
928
  : UNEXPECTED_FAILURE_MESSAGE;
777
929
  return { kind: "terminal" };
778
930
  }
931
+ const resolvedRunId = body.epic_run.epic_run_id;
932
+ if (typeof resolvedRunId === "string" && resolvedRunId.trim().length > 0)
933
+ probeRunId = resolvedRunId;
779
934
  if (parsed.until === "attention") {
780
935
  return observeAttention(snapshot);
781
936
  }
@@ -821,6 +976,39 @@ export async function runWaitRunCommand(argv, deps = {}) {
821
976
  }
822
977
  return { kind: "observation", ready: false };
823
978
  };
979
+ if (parsed.watch) {
980
+ const windowDeps = { ...(deps.waitDeps ?? {}), now: clock };
981
+ const sleep = deps.sleep ??
982
+ ((ms) => new Promise((resolve) => {
983
+ const handle = watchTimers.setTimer(() => {
984
+ watchTimers.clearTimer(handle);
985
+ resolve();
986
+ }, ms);
987
+ }));
988
+ const innerWindowMs = parsed.timeoutSeconds * 1000;
989
+ while (true) {
990
+ const remainingMs = watchDeadlineMs - clock();
991
+ // Below one millisecond the primitive would reject the budget as invalid.
992
+ if (remainingMs < 1)
993
+ return await finish(deadlinePending());
994
+ const outcome = await wait({
995
+ budgetMs: Math.min(innerWindowMs, remainingMs),
996
+ probe,
997
+ deps: windowDeps,
998
+ });
999
+ if (outcome.state === "ready")
1000
+ return await finish(outcome.result);
1001
+ if (outcome.state === "error")
1002
+ return fail(readFailure ?? UNEXPECTED_FAILURE_MESSAGE);
1003
+ if (outcome.reason === "UPSTREAM_TRANSIENT") {
1004
+ // The window gave up after its own three failures. Pause, bounded by the
1005
+ // deadline, before opening another.
1006
+ const pauseMs = Math.min(WAIT_RUN_WATCH_RETRY_DELAY_MS, watchDeadlineMs - clock());
1007
+ if (pauseMs > 0)
1008
+ await sleep(pauseMs);
1009
+ }
1010
+ }
1011
+ }
824
1012
  const outcome = await wait({
825
1013
  budgetMs: windowSeconds * 1000,
826
1014
  probe,
@@ -842,9 +1030,7 @@ export async function runWaitRunCommand(argv, deps = {}) {
842
1030
  else {
843
1031
  return fail(readFailure ?? UNEXPECTED_FAILURE_MESSAGE);
844
1032
  }
845
- if (await writeStdout(renderWaitRunResult(result, parsed.json)))
846
- return 0;
847
- return fail("wait-run: the result could not be written to stdout.");
1033
+ return await finish(result);
848
1034
  }
849
1035
  catch {
850
1036
  return fail(UNEXPECTED_FAILURE_MESSAGE);
@@ -6,6 +6,17 @@
6
6
  * Nothing about it changed in the move: `conductor doctor` still builds it the
7
7
  * same way, through this module.
8
8
  */
9
+ /** The Bridge seed values, used only when a caller passes no declaration (see the factory). */
10
+ const LEGACY_SEED = {
11
+ workerRole: "bridge_epic_worker",
12
+ protectedDatabases: ["bridgeapi"],
13
+ envNames: ["DATABASE_URL"],
14
+ migrateCommand: {
15
+ argv: [".venv/bin/alembic", "-c", "alembic.ini", "upgrade", "head"],
16
+ timeoutSeconds: 120,
17
+ headCheck: "alembic",
18
+ },
19
+ };
9
20
  /** Inner budget for the doctor's worker-database inspection (doctor adds its own hard ceiling). */
10
21
  const WORKER_DATABASE_DOCTOR_BUDGET_MS = 15_000;
11
22
  /**
@@ -19,7 +30,21 @@ const WORKER_DATABASE_DOCTOR_BUDGET_MS = 15_000;
19
30
  * dropped, swept, or written.
20
31
  */
21
32
  export function createWorkerDatabaseDoctorInspector(options) {
22
- return async () => {
33
+ return async (config) => {
34
+ // BAPI-1598: a caller that read the declaration (`doctor`) passes it. Only a
35
+ // disposable declaration is inspected; anything else gets an all-unknown
36
+ // inspection and NO Postgres probe. A caller that passes nothing at all (the
37
+ // `drive-epic` launch advisory, whose gating is a later change) keeps the
38
+ // inspection it always had, against the Bridge seed values.
39
+ if (config !== undefined && (config.status !== "configured" || config.mode !== "disposable_postgres" || !config.workerRole)) {
40
+ return {
41
+ role: { state: "unknown" },
42
+ boundary: { state: "unknown" },
43
+ alembic: { state: "unknown" },
44
+ inventory: { state: "unknown" },
45
+ };
46
+ }
47
+ const declared = config?.status === "configured" ? config : undefined;
23
48
  const [{ spawnSync }, os, workerDatabase, containment, registry] = await Promise.all([
24
49
  import("node:child_process"),
25
50
  import("node:os"),
@@ -40,11 +65,17 @@ export function createWorkerDatabaseDoctorInspector(options) {
40
65
  tmpdir: os.tmpdir,
41
66
  platform: process.platform,
42
67
  });
43
- return workerDatabase.inspectWorkerDatabaseReadiness({
68
+ const inspect = options.inspectReadiness ?? workerDatabase.inspectWorkerDatabaseReadiness;
69
+ return inspect({
44
70
  operatorRepositoryRoot,
71
+ workerRole: declared?.workerRole ?? LEGACY_SEED.workerRole,
72
+ protectedDatabases: declared?.protectedDatabases ?? LEGACY_SEED.protectedDatabases,
73
+ envNames: declared?.envNames ?? LEGACY_SEED.envNames,
74
+ migrateCommand: declared?.migrateCommand ?? LEGACY_SEED.migrateCommand,
45
75
  ciHarnessOwnerRole: options.env[workerDatabase.HARNESS_CI_OWNER_ENV],
46
76
  hostDigest: containment.hostIdentityDigest(os.hostname()),
47
77
  budgetMs: WORKER_DATABASE_DOCTOR_BUDGET_MS,
78
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
48
79
  }, workerDatabase.createDefaultWorkerDatabaseDeps({ stateDir, env: options.env }));
49
80
  };
50
81
  }
@@ -0,0 +1,27 @@
1
+ export const VERIFICATION_HANDOFF_DEFAULT_CODE = "verification_handoff_default_effective";
2
+ export const WORKER_DATABASE_STATUS_CODE = "worker_database_status";
3
+ /**
4
+ * The tally entries for a successful readiness read of the gate profile. A server
5
+ * that did not report a field (older server) contributes no entry for it: absence
6
+ * is never written as an explicit value.
7
+ */
8
+ export function workerSetupTallyEntries(gateProfile) {
9
+ const entries = [];
10
+ const handoff = gateProfile?.verification_handoff_default;
11
+ if (handoff !== undefined) {
12
+ entries.push({
13
+ code: VERIFICATION_HANDOFF_DEFAULT_CODE,
14
+ message: `verification hand-off default: ${handoff}`,
15
+ });
16
+ }
17
+ const database = gateProfile?.worker_database;
18
+ if (database !== undefined) {
19
+ const status = database.mode === "disposable_postgres"
20
+ ? "disposable_postgres"
21
+ : database.protected_databases.length > 0
22
+ ? "none_protected"
23
+ : "not_configured";
24
+ entries.push({ code: WORKER_DATABASE_STATUS_CODE, message: `worker database: ${status}` });
25
+ }
26
+ return entries;
27
+ }
@@ -1419,6 +1419,76 @@ export async function upsertBapiCredential(repoName, apiKey, deps, options = {})
1419
1419
  return { ok: true, path: primaryPath, target, action, migratedFallback };
1420
1420
  }, (error) => ({ ok: false, path: primaryPath, target, kind: "lock-error", error }), false);
1421
1421
  }
1422
+ /**
1423
+ * Generic bundle upsert (BAPI-1545): store `values` as the WHOLE entry for
1424
+ * `target` in the primary credential store. Used by the MCP grant setup item to
1425
+ * move an imported host server's env values out of any config file and into the
1426
+ * store, under a grant-specific target the grant then references by name.
1427
+ *
1428
+ * Same contract as {@link upsertBapiCredential}: the shared lock (when a lock
1429
+ * primitive is available), fallback seeding on the first primary write, temp
1430
+ * write with mode `0600`, atomic rename, and fixed errors that never echo a
1431
+ * value. `createOnly` refuses to touch an existing target, so a bundle the
1432
+ * current grant already references is never overwritten.
1433
+ */
1434
+ export async function upsertCredentialBundle(target, values, deps, options = {}) {
1435
+ const primaryPath = getPrimaryCredentialStorePath(deps);
1436
+ const trimmedTarget = (target ?? "").trim();
1437
+ if (trimmedTarget.length === 0 || trimmedTarget !== target) {
1438
+ return { ok: false, path: primaryPath, target: "", kind: "invalid-target", error: "Cannot store a credential bundle: the target is empty or padded." };
1439
+ }
1440
+ const keys = Object.keys(values);
1441
+ if (keys.length === 0 || keys.some((k) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || typeof values[k] !== "string")) {
1442
+ return { ok: false, path: primaryPath, target, kind: "invalid-values", error: `Cannot store the credential bundle ${target}: its key names or values are not usable.` };
1443
+ }
1444
+ return withCredentialStoreLock(deps, async () => {
1445
+ const primary = await readCredentialStoreJsonIfPresent(primaryPath, deps);
1446
+ if (primary.state === "error")
1447
+ return { ok: false, path: primaryPath, target, kind: primary.kind, error: primary.error };
1448
+ const base = primary.state === "present" ? { ...primary.value } : (await mergeFallbackCredentialStoreOnFirstPrimaryWrite(deps)).base;
1449
+ const existing = base[target];
1450
+ if (existing !== undefined && options.createOnly === true) {
1451
+ return { ok: false, path: primaryPath, target, kind: "exists", error: `The credential bundle ${target} already exists; it was left unchanged.` };
1452
+ }
1453
+ const nextEntry = {};
1454
+ for (const key of keys)
1455
+ nextEntry[key] = values[key];
1456
+ if (existing !== undefined && JSON.stringify(existing) === JSON.stringify(nextEntry)) {
1457
+ return { ok: true, path: primaryPath, target, action: "unchanged" };
1458
+ }
1459
+ const next = { ...base, [target]: nextEntry };
1460
+ if (deps.open) {
1461
+ const durable = await durablyReplaceCredentialStoreJson(primaryPath, next, deps);
1462
+ if (!durable.ok && durable.kind !== "post-rename-uncertain") {
1463
+ return { ok: false, path: primaryPath, target, kind: durable.kind, error: `Failed to write credentials file at ${primaryPath}.` };
1464
+ }
1465
+ }
1466
+ else {
1467
+ const dir = path.dirname(primaryPath);
1468
+ const tempPath = path.join(dir, `${path.basename(primaryPath)}.${(deps.tempSuffix ?? defaultTempSuffix)()}.tmp`);
1469
+ const isPosix = deps.platform !== "win32";
1470
+ try {
1471
+ await deps.mkdir(dir, { recursive: true });
1472
+ await deps.writeFile(tempPath, formatCredentialStoreJson(next), isPosix ? { encoding: "utf-8", mode: 0o600 } : { encoding: "utf-8" });
1473
+ if (isPosix)
1474
+ await deps.chmod(tempPath, 0o600);
1475
+ await deps.rename(tempPath, primaryPath);
1476
+ }
1477
+ catch {
1478
+ if (deps.unlink) {
1479
+ try {
1480
+ await deps.unlink(tempPath);
1481
+ }
1482
+ catch {
1483
+ /* cleanup failure must not mask the write error */
1484
+ }
1485
+ }
1486
+ return { ok: false, path: primaryPath, target, kind: "write-error", error: `Failed to write credentials file at ${primaryPath}.` };
1487
+ }
1488
+ }
1489
+ return { ok: true, path: primaryPath, target, action: existing === undefined ? "created" : "updated" };
1490
+ }, (error) => ({ ok: false, path: primaryPath, target, kind: "lock-error", error }), false);
1491
+ }
1422
1492
  // ---------------------------------------------------------------------------
1423
1493
  // Epic-launch credential binding (BAPI-1260)
1424
1494
  // ---------------------------------------------------------------------------
@@ -1432,7 +1502,7 @@ export async function upsertBapiCredential(repoName, apiKey, deps, options = {})
1432
1502
  */
1433
1503
  export const BAPI_EPIC_LAUNCH_BOUND_BASE_URL_FIELD = "BAPI_EPIC_LAUNCH_BOUND_BASE_URL";
1434
1504
  /** Trim and drop trailing slashes — the executor's own base-URL normalization. */
1435
- function normalizeBoundBaseUrl(raw) {
1505
+ export function normalizeBoundBaseUrl(raw) {
1436
1506
  if (typeof raw !== "string")
1437
1507
  return null;
1438
1508
  const normalized = raw.trim().replace(/\/+$/, "");
@@ -155,3 +155,58 @@ export function sameDependencyInstall(a, b) {
155
155
  function canonicalEntry(entry) {
156
156
  return { cwd: entry.cwd, argv: [...entry.argv], lockfiles: [...entry.lockfiles] };
157
157
  }
158
+ // ---------------------------------------------------------------------------
159
+ // BAPI-1580 — must-order paths
160
+ // ---------------------------------------------------------------------------
161
+ /** The most entries a `must_order_paths` declaration may hold (mirrors `MAX_MUST_ORDER_PATHS`). */
162
+ export const MAX_MUST_ORDER_PATHS = 32;
163
+ const MUST_ORDER_GLOB_CHARS = /[*?[\]]/;
164
+ /**
165
+ * True when `value` is one acceptable must-order entry, exactly as
166
+ * `validate_must_order_paths` checks it: no glob character, and after removing
167
+ * one trailing `/` (a directory prefix) a safe repository-relative path.
168
+ */
169
+ export function isValidMustOrderPath(value) {
170
+ if (typeof value !== "string" || MUST_ORDER_GLOB_CHARS.test(value))
171
+ return false;
172
+ return isSafeRepoRelativePath(value.endsWith("/") ? value.slice(0, -1) : value);
173
+ }
174
+ /** Code-point order, the order Python's `sorted` gives the server's list. */
175
+ export function compareCodePoints(a, b) {
176
+ const left = Array.from(a);
177
+ const right = Array.from(b);
178
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
179
+ const diff = (left[i].codePointAt(0) ?? 0) - (right[i].codePointAt(0) ?? 0);
180
+ if (diff !== 0)
181
+ return diff;
182
+ }
183
+ return left.length - right.length;
184
+ }
185
+ /** The canonical (sorted, distinct) form of a must-order list. */
186
+ export function canonicalMustOrderPaths(paths) {
187
+ return [...new Set(paths)].sort(compareCodePoints);
188
+ }
189
+ /**
190
+ * The client's fail-closed parse of `must_order_paths`: the canonical sorted
191
+ * list, or `null` when any entry is invalid, duplicated, or the list is over
192
+ * the bound. `undefined` (an absent field) reads as no declarations.
193
+ */
194
+ export function parseMustOrderPathsStrict(raw) {
195
+ if (raw === undefined)
196
+ return [];
197
+ if (!Array.isArray(raw) || raw.length > MAX_MUST_ORDER_PATHS)
198
+ return null;
199
+ const seen = new Set();
200
+ for (const entry of raw) {
201
+ if (!isValidMustOrderPath(entry) || seen.has(entry))
202
+ return null;
203
+ seen.add(entry);
204
+ }
205
+ return canonicalMustOrderPaths([...seen]);
206
+ }
207
+ /** True when two must-order lists hold the same entries (order never matters). */
208
+ export function sameMustOrderPaths(a, b) {
209
+ const left = canonicalMustOrderPaths(a);
210
+ const right = canonicalMustOrderPaths(b);
211
+ return left.length === right.length && left.every((p, i) => p === right[i]);
212
+ }