@bridge_gpt/mcp-server 0.2.71 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `wait-run --until attention` — the incident projection and set comparison
3
+ * (BAPI-1557).
4
+ *
5
+ * The default `wait-run` wakes on ANY change in the run's stable projection,
6
+ * which includes routine churn (gates moving, attempt counters, active jobs
7
+ * starting and finishing). A supervisor that only needs to know when something
8
+ * needs a person wakes far too often that way. Attention mode wakes only when a
9
+ * NEW incident appears.
10
+ *
11
+ * AN INCIDENT is one of:
12
+ * - a park, identified by `(ticket_key, parked_at)`;
13
+ * - a ticket with a non-null `needs_human_reason`;
14
+ * - a dead-letter executor job, identified by its id;
15
+ * - a paused or stopped run-control state;
16
+ * - a run status other than `active`.
17
+ *
18
+ * Nothing else is in the projection: not gates, observations, attempt counters,
19
+ * active job ids, non-failure job-status movement, clocks, or diagnostic prose.
20
+ *
21
+ * THE TOKEN. `a1:` plus 16 hex characters of the SHA-256 of the sorted incident
22
+ * ids. The change-mode `v1:` token is untouched. The token is observation-based:
23
+ * a `--since` that does not match the current set is never read as "something was
24
+ * added since then" — an opaque digest cannot say that. The wait compares the
25
+ * incident set it OBSERVES against the baseline it observed first.
26
+ *
27
+ * This module is pure: it reads a {@link WaitRunSnapshot} and does no I/O.
28
+ */
29
+ import { createHash } from "node:crypto";
30
+ /** The attention token's exact shape: `a1:` and 16 lowercase hex characters. */
31
+ export const WAIT_RUN_ATTENTION_TOKEN_PATTERN = /^a1:[0-9a-f]{16}$/;
32
+ /** At most this many incidents are listed in one wake result. */
33
+ export const WAIT_RUN_MAX_INCIDENTS = 20;
34
+ const FAILED_JOB_STATUSES = new Set(["dead_letter"]);
35
+ function compareStrings(a, b) {
36
+ return a < b ? -1 : a > b ? 1 : 0;
37
+ }
38
+ function controlState(runControl) {
39
+ if (typeof runControl !== "object" || runControl === null || Array.isArray(runControl))
40
+ return null;
41
+ const state = runControl.state;
42
+ return state === "paused" || state === "stopped" ? state : null;
43
+ }
44
+ /** Reduce a snapshot to its attention incidents. Pure and deterministic. */
45
+ export function buildWaitRunAttention(snapshot) {
46
+ const incidents = [];
47
+ if (snapshot.run.status !== "active") {
48
+ incidents.push({
49
+ id: `run_status:${snapshot.run.status}`,
50
+ kind: "run_status",
51
+ ticket_key: null,
52
+ detail: snapshot.run.status,
53
+ });
54
+ }
55
+ const control = controlState(snapshot.run.run_control);
56
+ if (control !== null) {
57
+ incidents.push({ id: `run_control:${control}`, kind: "run_control", ticket_key: null, detail: control });
58
+ }
59
+ for (const ticket of snapshot.tickets) {
60
+ if (typeof ticket.parked_at === "string" && ticket.parked_at !== "") {
61
+ incidents.push({
62
+ id: `park:${ticket.ticket_key}:${ticket.parked_at}`,
63
+ kind: "park",
64
+ ticket_key: ticket.ticket_key,
65
+ detail: null,
66
+ });
67
+ }
68
+ if (ticket.needs_human_reason !== null && ticket.needs_human_reason !== undefined) {
69
+ incidents.push({
70
+ id: `needs_human:${ticket.ticket_key}`,
71
+ kind: "needs_human",
72
+ ticket_key: ticket.ticket_key,
73
+ detail: null,
74
+ });
75
+ }
76
+ }
77
+ for (const job of snapshot.jobs) {
78
+ if (FAILED_JOB_STATUSES.has(job.status)) {
79
+ incidents.push({
80
+ id: `job_failed:${job.id}`,
81
+ kind: "job_failed",
82
+ ticket_key: job.ticket_key,
83
+ detail: job.id,
84
+ });
85
+ }
86
+ }
87
+ incidents.sort((a, b) => compareStrings(a.id, b.id));
88
+ return { incidents };
89
+ }
90
+ /** `a1:` plus the first 16 hex characters of the SHA-256 of the sorted incident ids. */
91
+ export function buildWaitRunAttentionToken(attention) {
92
+ const canonical = JSON.stringify(attention.incidents.map((incident) => incident.id));
93
+ return `a1:${createHash("sha256").update(canonical).digest("hex").slice(0, 16)}`;
94
+ }
95
+ /** The identity set of an attention projection. */
96
+ export function attentionIds(attention) {
97
+ return new Set(attention.incidents.map((incident) => incident.id));
98
+ }
99
+ /**
100
+ * The incidents present now that the baseline did not hold. Removals are never
101
+ * reported: an incident that cleared simply is not in the result.
102
+ */
103
+ export function newIncidents(baseline, current) {
104
+ return current.incidents.filter((incident) => !baseline.has(incident.id));
105
+ }
106
+ /**
107
+ * Whether an executor-job block's state lets the job incidents be read at all.
108
+ * `available` carries a list, and `not_applicable` (or an absent block) means this
109
+ * source does not describe the run. `unavailable` and `unknown` are missing
110
+ * evidence, not an empty failure set: the caller treats them as a transient read
111
+ * failure so a job baseline is never silently cleared.
112
+ */
113
+ export function executorJobEvidenceReadable(state) {
114
+ return state === null || state === "available" || state === "not_applicable";
115
+ }
@@ -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,7 +52,9 @@ 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";
57
+ import { WAIT_RUN_ATTENTION_TOKEN_PATTERN, WAIT_RUN_MAX_INCIDENTS, attentionIds, buildWaitRunAttention, buildWaitRunAttentionToken, executorJobEvidenceReadable, newIncidents, } from "./wait-run-attention.js";
45
58
  // ---------------------------------------------------------------------------
46
59
  // Constants
47
60
  // ---------------------------------------------------------------------------
@@ -49,6 +62,18 @@ import { writeJsonDocument } from "./json-output.js";
49
62
  export const WAIT_RUN_DEFAULT_TIMEOUT_SECONDS = 110;
50
63
  /** Largest accepted window, in seconds — the bounded-wait primitive's own ceiling. */
51
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;
52
77
  /** At most this many change lines are rendered per result. */
53
78
  export const WAIT_RUN_MAX_CHANGES = 20;
54
79
  /** BAPI-1532 — at most this many tickets are listed in a since-mismatch `current` block. */
@@ -73,8 +98,25 @@ const WAIT_RUN_VALUE_FLAGS = new Set([
73
98
  "--ticket-key",
74
99
  "--since",
75
100
  "--timeout",
101
+ "--until",
102
+ "--max-minutes",
103
+ "--driver-generation",
76
104
  ]);
77
- 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
+ }
78
120
  /**
79
121
  * Parse a `--timeout` spelling into the effective window in seconds.
80
122
  *
@@ -99,6 +141,7 @@ function parseTimeoutSeconds(raw) {
99
141
  export function parseWaitRunArgs(argv) {
100
142
  const values = new Map();
101
143
  let json = false;
144
+ let watch = false;
102
145
  for (let i = 0; i < argv.length; i += 1) {
103
146
  const token = argv[i];
104
147
  if (token === "-h" || token === "--help") {
@@ -107,6 +150,9 @@ export function parseWaitRunArgs(argv) {
107
150
  epicRunId: "",
108
151
  timeoutSeconds: WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
109
152
  json: false,
153
+ watch: false,
154
+ maxMinutes: WAIT_RUN_WATCH_DEFAULT_MAX_MINUTES,
155
+ until: "change",
110
156
  };
111
157
  }
112
158
  if (!token.startsWith("--")) {
@@ -118,7 +164,10 @@ export function parseWaitRunArgs(argv) {
118
164
  if (eq >= 0) {
119
165
  throw new ConductorValidationError("A wait-run boolean flag does not take a value.");
120
166
  }
121
- json = true;
167
+ if (name === "--watch")
168
+ watch = true;
169
+ else
170
+ json = true;
122
171
  continue;
123
172
  }
124
173
  if (!WAIT_RUN_VALUE_FLAGS.has(name)) {
@@ -145,9 +194,32 @@ export function parseWaitRunArgs(argv) {
145
194
  const parsed = {
146
195
  help: false,
147
196
  epicRunId: epicRunId.trim(),
148
- timeoutSeconds: WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
197
+ timeoutSeconds: watch ? WAIT_RUN_WATCH_WINDOW_SECONDS : WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
149
198
  json,
199
+ watch,
200
+ maxMinutes: WAIT_RUN_WATCH_DEFAULT_MAX_MINUTES,
201
+ until: watch ? "attention" : "change",
150
202
  };
203
+ const until = values.get("--until");
204
+ if (until !== undefined) {
205
+ if (until !== "change" && until !== "attention") {
206
+ throw new ConductorValidationError('Flag "--until" must be "change" or "attention".');
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
+ }
213
+ parsed.until = until;
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
+ }
151
223
  const ticketKey = values.get("--ticket-key");
152
224
  if (ticketKey !== undefined) {
153
225
  if (ticketKey.trim().length === 0) {
@@ -157,8 +229,12 @@ export function parseWaitRunArgs(argv) {
157
229
  }
158
230
  const since = values.get("--since");
159
231
  if (since !== undefined) {
160
- if (!WAIT_RUN_TOKEN_PATTERN.test(since)) {
161
- throw new ConductorValidationError('Flag "--since" must be a token from a previous wait-run result (v1: plus 16 hex characters).');
232
+ // Attention mode accepts a token from either mode: one from the other mode
233
+ // simply establishes a fresh baseline. Change mode is unchanged and takes v1 only.
234
+ const acceptable = WAIT_RUN_TOKEN_PATTERN.test(since) ||
235
+ (parsed.until === "attention" && WAIT_RUN_ATTENTION_TOKEN_PATTERN.test(since));
236
+ if (!acceptable) {
237
+ throw new ConductorValidationError('Flag "--since" must be a token from a previous wait-run result (v1: or a1: plus 16 hex characters).');
162
238
  }
163
239
  parsed.since = since;
164
240
  }
@@ -166,12 +242,19 @@ export function parseWaitRunArgs(argv) {
166
242
  if (timeout !== undefined) {
167
243
  parsed.timeoutSeconds = parseTimeoutSeconds(timeout);
168
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
+ }
169
252
  return parsed;
170
253
  }
171
254
  /** Command-specific help. Printing it resolves no credentials and makes no request. */
172
255
  export function getWaitRunUsage() {
173
256
  return [
174
- "Usage: epic-implementer wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>] [--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>]",
175
258
  "",
176
259
  "Read-only. Wait until an epic run's observable state changes, the run finishes,",
177
260
  "or the window closes. Reads only the run's state route; changes nothing.",
@@ -183,10 +266,27 @@ export function getWaitRunUsage() {
183
266
  " run and the same --ticket-key; a mismatch reports changed with the",
184
267
  " bounded Current state (up to 20 tickets, parked first), not a diff",
185
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})`,
269
+ " --until <mode> change (default): wake on any projected change. attention: wake only",
270
+ " when a NEW incident appears (a park, a needs-human reason, a",
271
+ " dead-letter job, a paused or stopped run, a non-active run). Attention",
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",
186
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",
187
286
  "",
188
287
  "Outcomes (all exit 0): changed, terminal (run done or abandoned), pending",
189
- "(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.",
190
290
  "Failures exit 1 with one line on stderr and nothing on stdout.",
191
291
  "",
192
292
  "Example:",
@@ -540,6 +640,18 @@ export function renderWaitRunResult(result, json) {
540
640
  if (result.outcome === "terminal") {
541
641
  return `wait-run: terminal (run ${runStatus}, ${window}, token ${token})`;
542
642
  }
643
+ if ("mode" in result) {
644
+ const lines = [
645
+ `wait-run: attention (run ${runStatus}, ${window}, token ${token}` +
646
+ `${result.truncated ? `, first ${result.incidents.length} of ${result.total_count} incidents shown` : ""})`,
647
+ ];
648
+ for (const incident of result.incidents) {
649
+ const subject = incident.ticket_key === null ? "run" : displayString(incident.ticket_key);
650
+ const detail = incident.detail === null ? "" : ` ${displayString(String(incident.detail))}`;
651
+ lines.push(` ${subject} ${incident.kind}${detail}`);
652
+ }
653
+ return lines.join("\n");
654
+ }
543
655
  if ("baseline" in result) {
544
656
  // BAPI-1532: a labeled snapshot, stacked per ticket so a narrow terminal stays
545
657
  // readable. It is the state NOW; what changed since the token is not reported.
@@ -595,6 +707,10 @@ function describeTerminalReadFailure(err) {
595
707
  }
596
708
  return UNEXPECTED_FAILURE_MESSAGE;
597
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();
598
714
  /** Reject promptly when the bounded wait aborts this probe, so a hung read costs one probe. */
599
715
  function untilAborted(work, signal) {
600
716
  if (signal.aborted)
@@ -646,8 +762,61 @@ export async function runWaitRunCommand(argv, deps = {}) {
646
762
  return 0;
647
763
  return fail("wait-run: the help text could not be written to stdout.");
648
764
  }
649
- const resolveAccess = deps.resolveAccess ?? (() => resolveConductorBridgeApiAccess());
650
- 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());
651
820
  if (!accessResult.ok) {
652
821
  // The shared resolver's messages are fixed, secret-free text.
653
822
  return fail(`wait-run: ${accessResult.error}`);
@@ -655,21 +824,94 @@ export async function runWaitRunCommand(argv, deps = {}) {
655
824
  const access = accessResult.access;
656
825
  const fetchState = deps.fetchState ?? ((a, id) => fetchEpicRunState(a, id));
657
826
  const wait = deps.boundedWait ?? defaultBoundedWait;
658
- const windowSeconds = parsed.timeoutSeconds;
659
- let latestToken = parsed.since ?? null;
660
- let latestRunStatus = null;
661
827
  let baseline = null;
662
828
  let readFailure = null;
829
+ // BAPI-1557: attention mode compares the incident set it OBSERVES against the
830
+ // baseline it observed first. It never infers an addition from a token mismatch.
831
+ let attentionBaseline = null;
832
+ const observeAttention = (snapshot) => {
833
+ const attention = buildWaitRunAttention(snapshot);
834
+ const token = buildWaitRunAttentionToken(attention);
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;
840
+ // A finished run outranks everything, as in change mode.
841
+ if (TERMINAL_RUN_STATUSES.has(snapshot.run.status)) {
842
+ latestToken = token;
843
+ const value = {
844
+ outcome: "terminal",
845
+ token,
846
+ window_seconds: windowSeconds,
847
+ run_status: snapshot.run.status,
848
+ };
849
+ return { kind: "observation", ready: true, value };
850
+ }
851
+ // Missing job evidence is not an empty failure set. Report it to the
852
+ // primitive as a transient failure so the baseline is never cleared by it.
853
+ if (!executorJobEvidenceReadable(snapshot.executor_jobs_state)) {
854
+ failedSinceGood = true;
855
+ throw new ConductorBridgeApiError("server", 503);
856
+ }
857
+ latestToken = token;
858
+ latestRunStatus = snapshot.run.status;
859
+ failedSinceGood = false;
860
+ let added;
861
+ if (attentionBaseline === null) {
862
+ if (parsed.since !== undefined && parsed.since === token) {
863
+ // A matching token means the caller already saw this set: keep sleeping.
864
+ attentionBaseline = attentionIds(attention);
865
+ added = [];
866
+ }
867
+ else {
868
+ // No token, or one that no longer matches (the set changed since the
869
+ // caller looked, or it came from the other mode): report every
870
+ // incident present now, so none is lost between driver passes.
871
+ attentionBaseline = new Set();
872
+ added = newIncidents(attentionBaseline, attention);
873
+ }
874
+ }
875
+ else {
876
+ added = newIncidents(attentionBaseline, attention);
877
+ }
878
+ if (added.length > 0) {
879
+ const value = {
880
+ outcome: "changed",
881
+ token,
882
+ mode: "attention",
883
+ window_seconds: windowSeconds,
884
+ run_status: snapshot.run.status,
885
+ incidents: added.slice(0, WAIT_RUN_MAX_INCIDENTS),
886
+ total_count: added.length,
887
+ ...(added.length > WAIT_RUN_MAX_INCIDENTS ? { truncated: true } : {}),
888
+ };
889
+ return { kind: "observation", ready: true, value };
890
+ }
891
+ // Incidents that cleared leave the baseline silently: removals never wake.
892
+ attentionBaseline = attentionIds(attention);
893
+ return { kind: "observation", ready: false };
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;
663
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
+ }
664
904
  let body;
665
905
  try {
666
- body = await untilAborted(fetchState(access, parsed.epicRunId), signal);
906
+ body = await untilAborted(fetchState(access, probeRunId), signal);
667
907
  }
668
908
  catch (err) {
669
909
  // A transient failure is thrown back to the primitive, which counts it
670
910
  // toward its three-in-a-row rule. Its text never reaches a result.
671
- if (isTransientReadFailure(err))
911
+ if (isTransientReadFailure(err)) {
912
+ failedSinceGood = true;
672
913
  throw err;
914
+ }
673
915
  readFailure = describeTerminalReadFailure(err);
674
916
  return { kind: "terminal" };
675
917
  }
@@ -686,6 +928,12 @@ export async function runWaitRunCommand(argv, deps = {}) {
686
928
  : UNEXPECTED_FAILURE_MESSAGE;
687
929
  return { kind: "terminal" };
688
930
  }
931
+ const resolvedRunId = body.epic_run.epic_run_id;
932
+ if (typeof resolvedRunId === "string" && resolvedRunId.trim().length > 0)
933
+ probeRunId = resolvedRunId;
934
+ if (parsed.until === "attention") {
935
+ return observeAttention(snapshot);
936
+ }
689
937
  const token = buildWaitRunToken(snapshot);
690
938
  latestToken = token;
691
939
  latestRunStatus = snapshot.run.status;
@@ -728,6 +976,39 @@ export async function runWaitRunCommand(argv, deps = {}) {
728
976
  }
729
977
  return { kind: "observation", ready: false };
730
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
+ }
731
1012
  const outcome = await wait({
732
1013
  budgetMs: windowSeconds * 1000,
733
1014
  probe,
@@ -749,9 +1030,7 @@ export async function runWaitRunCommand(argv, deps = {}) {
749
1030
  else {
750
1031
  return fail(readFailure ?? UNEXPECTED_FAILURE_MESSAGE);
751
1032
  }
752
- if (await writeStdout(renderWaitRunResult(result, parsed.json)))
753
- return 0;
754
- return fail("wait-run: the result could not be written to stdout.");
1033
+ return await finish(result);
755
1034
  }
756
1035
  catch {
757
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,10 +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,
75
+ ciHarnessOwnerRole: options.env[workerDatabase.HARNESS_CI_OWNER_ENV],
45
76
  hostDigest: containment.hostIdentityDigest(os.hostname()),
46
77
  budgetMs: WORKER_DATABASE_DOCTOR_BUDGET_MS,
78
+ ...(options.scope !== undefined ? { scope: options.scope } : {}),
47
79
  }, workerDatabase.createDefaultWorkerDatabaseDeps({ stateDir, env: options.env }));
48
80
  };
49
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
+ }