@bridge_gpt/mcp-server 0.2.71 → 0.2.72

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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -18,7 +18,7 @@
18
18
  * callers: `recovery-cli.ts` and `plane/shutdown.ts`.
19
19
  */
20
20
  import { randomUUID } from "crypto";
21
- import { adoptCurrentHeadAndUnparkTicket, completeMergeChild, ConductorBridgeApiError, dispatchRemediation, fetchEpicRunState, mergeChild, patchPolicy, RERUN_CI_ROUTE_UNAVAILABLE_CODE, RERUN_CI_ROUTE_UNAVAILABLE_MESSAGE, rerunCi, resolveHandoff, resumeRun, safeDiagnosticMessage, scopeCatchUp, scopeReparse, stopEpicRun, unparkEpicTicket, updateEpicRunStatus, fetchChildContinuationStatus, postContinueParkedChild, postGrantContinuation, resumeCiTicket, regeneratePlanTicket, REVIEW_HEAD_REFUSAL_CODES, EXTERNAL_REPAIR_REFUSAL_CODES, EXTERNAL_REPAIR_RETRYABLE_CODES, } from "./bridge-api-client.js";
21
+ import { acknowledgeGaps, adoptCurrentHeadAndUnparkTicket, completeMergeChild, ConductorBridgeApiError, dispatchRemediation, fetchEpicRunState, mergeChild, patchPolicy, RERUN_CI_ROUTE_UNAVAILABLE_CODE, RERUN_CI_ROUTE_UNAVAILABLE_MESSAGE, rerunCi, resolveHandoff, resumeRun, safeDiagnosticMessage, scopeCatchUp, scopeReparse, stopEpicRun, unparkEpicTicket, updateEpicRunStatus, fetchChildContinuationStatus, postContinueParkedChild, postGrantContinuation, resumeCiTicket, regeneratePlanTicket, REVIEW_HEAD_REFUSAL_CODES, EXTERNAL_REPAIR_REFUSAL_CODES, EXTERNAL_REPAIR_RETRYABLE_CODES, } from "./bridge-api-client.js";
22
22
  import { clearGuidedReference, guardForBinding, GUIDED_PAYLOAD_CONFLICT_MESSAGE, GUIDED_REFERENCE_STORE_FAILED_MESSAGE, guidedPayloadDigest, prepareGuidedRequest, } from "./guided-repair.js";
23
23
  import { DEFAULT_GATE_NAME } from "./git-ci-types.js";
24
24
  import { bindingsDriverContextSha256, CONTINUATION_CI_WAITING_REASONS, canonicalSha256, clearContinuationReference, clearRecoveryReferenceFile, computeContinuationFingerprint, driverContextSha256, readRecoveryReferenceFile, writeRecoveryReferenceFile, isFullSha, newContinuationRequestId, readContinuationReference, writeContinuationReference, } from "./epic-child-continuation.js";
@@ -177,7 +177,7 @@ async function ticketRecoveryWithRetry(access, options, mutate) {
177
177
  result = await mutate(access, {
178
178
  epicRunId: options.epicRunId,
179
179
  ticketKey: options.ticketKey,
180
- expectedRowVersion: ticket.row_version,
180
+ expectedRowVersion: options.expectedRowVersion ?? ticket.row_version,
181
181
  idempotencyKey,
182
182
  reason: options.reason,
183
183
  cleanupResolution: options.cleanupResolution,
@@ -199,6 +199,11 @@ async function ticketRecoveryWithRetry(access, options, mutate) {
199
199
  ...(refusal.retryable !== undefined ? { retryable: refusal.retryable } : {}),
200
200
  };
201
201
  }
202
+ // BAPI-1554: for an HTTP 400 `VALIDATION` refusal the client has already read
203
+ // the server's bounded `detail.error` into `bodyPreview` (stale-CAS handled
204
+ // first, inside the client), and `safeDiagnosticMessage` puts it after the
205
+ // `kind=/status=/code=` prefix. A missing, blank, or unusable explanation
206
+ // leaves only that prefix, so the generic diagnostic is the fallback.
202
207
  return {
203
208
  ok: false,
204
209
  kind: "unavailable",
@@ -220,6 +225,8 @@ async function ticketRecoveryWithRetry(access, options, mutate) {
220
225
  ...(external ? { externalRepair: external } : {}),
221
226
  };
222
227
  }
228
+ if (options.expectedRowVersion !== undefined)
229
+ break;
223
230
  // `result.kind === "cas-conflict"`: a concurrent write moved the ticket's
224
231
  // row_version between our read and our mutate. Loop back to a fresh read —
225
232
  // never reuse `result.current_row_version` here.
@@ -326,6 +333,9 @@ function classifyRepairError(err, fallback) {
326
333
  code: err.errorCode,
327
334
  status: err.status,
328
335
  message: err.bodyPreview ?? err.errorCode,
336
+ ...(typeof err.holderJobId === "number" && typeof err.holderJobType === "string"
337
+ ? { holder: { job_id: err.holderJobId, job_type: err.holderJobType } }
338
+ : {}),
329
339
  };
330
340
  }
331
341
  return { ok: false, kind: "unavailable", message: safeDiagnosticMessage(err, fallback) };
@@ -353,6 +363,19 @@ export async function resolveHandoffRepair(access, options, deps = {}) {
353
363
  return classifyRepairError(err, "resolve-handoff request failed");
354
364
  }
355
365
  }
366
+ /**
367
+ * BAPI-1562 — the owner's ONE acknowledgement of the run's carried-gap list. A
368
+ * thin wrapper so the CLI shares the closed refusal classification above.
369
+ */
370
+ export async function acknowledgeGapsRepair(access, options, deps = {}) {
371
+ try {
372
+ const call = deps.acknowledgeGaps ?? acknowledgeGaps;
373
+ return { ok: true, result: await call(access, options) };
374
+ }
375
+ catch (err) {
376
+ return classifyRepairError(err, "acknowledge-gaps request failed");
377
+ }
378
+ }
356
379
  /**
357
380
  * Dispatch a remediation job with driver context. `context` must already be
358
381
  * validated against `DRIVER_CONTEXT_MAX_BYTES`; the server selects the job type.
@@ -422,7 +445,14 @@ export async function mergeChildRepair(access, options, deps = {}) {
422
445
  // which is discarded — never the server's action key, which the server
423
446
  // recomposes itself at completion.
424
447
  action_key: `merge-child:${options.epicRunId}:${options.prNumber}`,
425
- }, { method: resolveLocalMergeMethod(local.merge_method) },
448
+ }, {
449
+ method: resolveLocalMergeMethod(local.merge_method),
450
+ // BAPI-1564 — a carry-gaps approval names its base; the local ref guard
451
+ // re-checks it before `gh pr merge`. A plain approval carries none.
452
+ ...(local.expected_base_branch !== undefined
453
+ ? { expectedBaseBranch: local.expected_base_branch }
454
+ : {}),
455
+ },
426
456
  // BAPI-1136: an explicitly configured local credential, never the ambient
427
457
  // login. `env` remains the source of the allowlisted operational base only.
428
458
  { env, credential });
@@ -960,7 +990,7 @@ export const RESUME_CI_POST_LIMIT = 3;
960
990
  const RESUME_CI_RETRY_DELAY_MS = 250;
961
991
  const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/;
962
992
  const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/;
963
- const CI_STOP_REASON_VALUES = new Set(["wait_expired", "verdict_unavailable", "repair_exhausted"]);
993
+ const CI_STOP_REASON_VALUES = new Set(["wait_expired", "verdict_unavailable", "repair_exhausted", "required_check_not_reporting"]);
964
994
  function isRecordValue(value) {
965
995
  return value !== null && typeof value === "object" && !Array.isArray(value);
966
996
  }
@@ -25,6 +25,12 @@ export const VERB_RESUME_RUN = "resume-run";
25
25
  export const VERB_RESUME_CI = "resume-ci";
26
26
  export const VERB_RERUN_CI = "rerun-ci";
27
27
  export const VERB_RESOLVE_HANDOFF = "resolve-handoff";
28
+ /**
29
+ * BAPI-1562 — the owner's ONE acknowledgement of the run's carried-gap list by
30
+ * its digest. An owner step: the driver never runs it and the worker guard
31
+ * denies it.
32
+ */
33
+ export const VERB_ACKNOWLEDGE_GAPS = "acknowledge-gaps";
28
34
  /** Every repair verb, in the order an operator meets them. */
29
35
  export const OPERATOR_REPAIR_VERBS = [
30
36
  VERB_SCOPE_REPARSE,
@@ -36,6 +42,7 @@ export const OPERATOR_REPAIR_VERBS = [
36
42
  VERB_RESUME_CI,
37
43
  VERB_RERUN_CI,
38
44
  VERB_RESOLVE_HANDOFF,
45
+ VERB_ACKNOWLEDGE_GAPS,
39
46
  ];
40
47
  /**
41
48
  * The ONE cap on driver context, in UTF-8 BYTES — the same number the server
@@ -124,6 +131,12 @@ export const OPERATOR_REPAIR_REFUSAL_CODES = [
124
131
  "HANDOFF_LEDGER_UNREADABLE",
125
132
  "HANDOFF_RESOLUTION_CAPACITY",
126
133
  "HANDOFF_SELECTION_CHANGED",
134
+ // BAPI-1555
135
+ "MERGE_ALREADY_ADMITTED",
136
+ // BAPI-1562
137
+ "GAP_LIST_UNREADABLE",
138
+ "GAP_LIST_EMPTY",
139
+ "GAP_DIGEST_STALE",
127
140
  ];
128
141
  /** True when `code` is one of the closed repair refusal codes. */
129
142
  export function isOperatorRepairRefusalCode(code) {
@@ -252,3 +265,23 @@ export const HANDOFF_RESOLUTION_KIND_LABELS = {
252
265
  export const HANDOFF_RESOLUTION_MAX_STEPS = 50;
253
266
  export const HANDOFF_RESOLUTION_EVIDENCE_REF_MAX_CHARS = 500;
254
267
  export const HANDOFF_RESOLUTION_REASON_MAX_CHARS = 2000;
268
+ // ---------------------------------------------------------------------------
269
+ // BAPI-1562 — `acknowledge-gaps`
270
+ // ---------------------------------------------------------------------------
271
+ /**
272
+ * The closed `acknowledge-gaps` refusal subset, in check order — mirrors
273
+ * `ACKNOWLEDGE_GAPS_REFUSAL_CODES` in `operator_repair_contract.py`.
274
+ */
275
+ export const ACKNOWLEDGE_GAPS_REFUSAL_CODES = [
276
+ "RESOLUTION_ACTOR_UNAVAILABLE",
277
+ "GAP_LIST_UNREADABLE",
278
+ "GAP_LIST_EMPTY",
279
+ "GAP_DIGEST_STALE",
280
+ ];
281
+ /** True when `code` is one of the closed `acknowledge-gaps` refusal codes. */
282
+ export function isAcknowledgeGapsRefusalCode(code) {
283
+ return (typeof code === "string" &&
284
+ ACKNOWLEDGE_GAPS_REFUSAL_CODES.includes(code));
285
+ }
286
+ /** The acknowledgement reason bound (`GAP_ACKNOWLEDGEMENT_REASON_MAX_CHARS`). */
287
+ export const GAP_ACKNOWLEDGEMENT_REASON_MAX_CHARS = 1000;
@@ -18,6 +18,15 @@ import { resolveConductorBridgeApiAccess, fetchEpicRunState, fetchExplainRun, Co
18
18
  function jsonResult(value) {
19
19
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
20
20
  }
21
+ /**
22
+ * BAPI-1557: compact (unindented) JSON, used only by `get_epic_snapshot`. Every
23
+ * other conductor tool keeps {@link jsonResult}'s pretty output.
24
+ */
25
+ function compactJsonResult(value) {
26
+ return { content: [{ type: "text", text: JSON.stringify(value) }] };
27
+ }
28
+ /** The snapshot tool's default executor-job row budget (soft; must-keep rows may exceed it). */
29
+ export const SNAPSHOT_DEFAULT_JOB_LIMIT = 50;
21
30
  /**
22
31
  * Wrap a tool handler so any thrown value becomes a sanitized structured JSON
23
32
  * error envelope (validation -> 400, store-busy -> 503, otherwise 500). Raw
@@ -51,16 +60,33 @@ function registerGetEpicSnapshotTool(registerTool) {
51
60
  "Read-only; never triggers a tick, transitions Jira, or mutates Epic state.",
52
61
  inputSchema: {
53
62
  epic_key: z.string().min(1).describe("The epic identifier to fetch the snapshot for (e.g. EPIC-123)."),
63
+ job_limit: z
64
+ .number()
65
+ .int()
66
+ .min(1)
67
+ .max(200)
68
+ .optional()
69
+ .describe("Soft job row budget, 1-200 (default 50)."),
70
+ ticket_key: z
71
+ .string()
72
+ .min(1)
73
+ .optional()
74
+ .describe("Scope to one ticket."),
54
75
  },
55
76
  }, withConductorToolErrorHandling(async (args) => {
56
77
  const epicKey = args.epic_key;
78
+ const jobLimit = args.job_limit ?? SNAPSHOT_DEFAULT_JOB_LIMIT;
79
+ const ticketKey = args.ticket_key;
57
80
  const accessResult = await resolveConductorBridgeApiAccess();
58
81
  if (!accessResult.ok) {
59
82
  throw new ConductorValidationError(accessResult.error);
60
83
  }
61
84
  try {
62
- const result = await fetchEpicRunState(accessResult.access, epicKey);
63
- return jsonResult(result);
85
+ const result = await fetchEpicRunState(accessResult.access, epicKey, undefined, {
86
+ job_limit: jobLimit,
87
+ ...(ticketKey !== undefined ? { ticket_key: ticketKey } : {}),
88
+ });
89
+ return compactJsonResult(result);
64
90
  }
65
91
  catch (error) {
66
92
  if (error instanceof ConductorBridgeApiError && error.status === 404) {
@@ -97,17 +123,22 @@ function registerExplainRunTool(registerTool) {
97
123
  .min(1)
98
124
  .optional()
99
125
  .describe("Narrow the answer to one ticket in the run."),
126
+ include_run: z
127
+ .boolean()
128
+ .optional()
129
+ .describe("With ticket_key: also return run.policy_action."),
100
130
  },
101
131
  }, withConductorToolErrorHandling(async (args) => {
102
132
  const epicRunId = args.epic_run_id;
103
133
  const ticketKey = args.ticket_key;
134
+ const includeRun = args.include_run;
104
135
  const scope = ticketKey === undefined ? "run" : "ticket";
105
136
  const accessResult = await resolveConductorBridgeApiAccess();
106
137
  if (!accessResult.ok) {
107
138
  throw new ConductorValidationError(accessResult.error);
108
139
  }
109
140
  try {
110
- return jsonResult(await fetchExplainRun(accessResult.access, epicRunId, ticketKey));
141
+ return jsonResult(await fetchExplainRun(accessResult.access, epicRunId, ticketKey, undefined, includeRun !== undefined ? { include_run: includeRun } : {}));
111
142
  }
112
143
  catch (error) {
113
144
  if (error instanceof ConductorBridgeApiError && error.status === 404) {
@@ -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 failed or 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(["failed", "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
+ }
@@ -42,6 +42,7 @@ import { boundedWait as defaultBoundedWait, } from "../bounded-wait.js";
42
42
  import { ConductorBridgeApiError, fetchEpicRunState, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
43
43
  import { ConductorValidationError } from "./errors.js";
44
44
  import { writeJsonDocument } from "./json-output.js";
45
+ import { WAIT_RUN_ATTENTION_TOKEN_PATTERN, WAIT_RUN_MAX_INCIDENTS, attentionIds, buildWaitRunAttention, buildWaitRunAttentionToken, executorJobEvidenceReadable, newIncidents, } from "./wait-run-attention.js";
45
46
  // ---------------------------------------------------------------------------
46
47
  // Constants
47
48
  // ---------------------------------------------------------------------------
@@ -73,6 +74,7 @@ const WAIT_RUN_VALUE_FLAGS = new Set([
73
74
  "--ticket-key",
74
75
  "--since",
75
76
  "--timeout",
77
+ "--until",
76
78
  ]);
77
79
  const WAIT_RUN_BOOL_FLAGS = new Set(["--json", "--help"]);
78
80
  /**
@@ -107,6 +109,7 @@ export function parseWaitRunArgs(argv) {
107
109
  epicRunId: "",
108
110
  timeoutSeconds: WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
109
111
  json: false,
112
+ until: "change",
110
113
  };
111
114
  }
112
115
  if (!token.startsWith("--")) {
@@ -147,7 +150,15 @@ export function parseWaitRunArgs(argv) {
147
150
  epicRunId: epicRunId.trim(),
148
151
  timeoutSeconds: WAIT_RUN_DEFAULT_TIMEOUT_SECONDS,
149
152
  json,
153
+ until: "change",
150
154
  };
155
+ const until = values.get("--until");
156
+ if (until !== undefined) {
157
+ if (until !== "change" && until !== "attention") {
158
+ throw new ConductorValidationError('Flag "--until" must be "change" or "attention".');
159
+ }
160
+ parsed.until = until;
161
+ }
151
162
  const ticketKey = values.get("--ticket-key");
152
163
  if (ticketKey !== undefined) {
153
164
  if (ticketKey.trim().length === 0) {
@@ -157,8 +168,12 @@ export function parseWaitRunArgs(argv) {
157
168
  }
158
169
  const since = values.get("--since");
159
170
  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).');
171
+ // Attention mode accepts a token from either mode: one from the other mode
172
+ // simply establishes a fresh baseline. Change mode is unchanged and takes v1 only.
173
+ const acceptable = WAIT_RUN_TOKEN_PATTERN.test(since) ||
174
+ (parsed.until === "attention" && WAIT_RUN_ATTENTION_TOKEN_PATTERN.test(since));
175
+ if (!acceptable) {
176
+ throw new ConductorValidationError('Flag "--since" must be a token from a previous wait-run result (v1: or a1: plus 16 hex characters).');
162
177
  }
163
178
  parsed.since = since;
164
179
  }
@@ -171,7 +186,7 @@ export function parseWaitRunArgs(argv) {
171
186
  /** Command-specific help. Printing it resolves no credentials and makes no request. */
172
187
  export function getWaitRunUsage() {
173
188
  return [
174
- "Usage: epic-implementer wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>] [--json]",
189
+ "Usage: epic-implementer wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>] [--until change|attention] [--json]",
175
190
  "",
176
191
  "Read-only. Wait until an epic run's observable state changes, the run finishes,",
177
192
  "or the window closes. Reads only the run's state route; changes nothing.",
@@ -183,6 +198,10 @@ export function getWaitRunUsage() {
183
198
  " run and the same --ticket-key; a mismatch reports changed with the",
184
199
  " bounded Current state (up to 20 tickets, parked first), not a diff",
185
200
  ` --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
+ " --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",
203
+ " dead-letter job, a paused or stopped run, a non-active run). Attention",
204
+ " tokens start with a1:; reuse one only with the same run, ticket and mode",
186
205
  " --json Print one JSON line",
187
206
  "",
188
207
  "Outcomes (all exit 0): changed, terminal (run done or abandoned), pending",
@@ -540,6 +559,18 @@ export function renderWaitRunResult(result, json) {
540
559
  if (result.outcome === "terminal") {
541
560
  return `wait-run: terminal (run ${runStatus}, ${window}, token ${token})`;
542
561
  }
562
+ if ("mode" in result) {
563
+ const lines = [
564
+ `wait-run: attention (run ${runStatus}, ${window}, token ${token}` +
565
+ `${result.truncated ? `, first ${result.incidents.length} of ${result.total_count} incidents shown` : ""})`,
566
+ ];
567
+ for (const incident of result.incidents) {
568
+ const subject = incident.ticket_key === null ? "run" : displayString(incident.ticket_key);
569
+ const detail = incident.detail === null ? "" : ` ${displayString(String(incident.detail))}`;
570
+ lines.push(` ${subject} ${incident.kind}${detail}`);
571
+ }
572
+ return lines.join("\n");
573
+ }
543
574
  if ("baseline" in result) {
544
575
  // BAPI-1532: a labeled snapshot, stacked per ticket so a narrow terminal stays
545
576
  // readable. It is the state NOW; what changed since the token is not reported.
@@ -660,6 +691,65 @@ export async function runWaitRunCommand(argv, deps = {}) {
660
691
  let latestRunStatus = null;
661
692
  let baseline = null;
662
693
  let readFailure = null;
694
+ // BAPI-1557: attention mode compares the incident set it OBSERVES against the
695
+ // baseline it observed first. It never infers an addition from a token mismatch.
696
+ let attentionBaseline = null;
697
+ const observeAttention = (snapshot) => {
698
+ const attention = buildWaitRunAttention(snapshot);
699
+ const token = buildWaitRunAttentionToken(attention);
700
+ latestRunStatus = snapshot.run.status;
701
+ // A finished run outranks everything, as in change mode.
702
+ if (TERMINAL_RUN_STATUSES.has(snapshot.run.status)) {
703
+ latestToken = token;
704
+ const value = {
705
+ outcome: "terminal",
706
+ token,
707
+ window_seconds: windowSeconds,
708
+ run_status: snapshot.run.status,
709
+ };
710
+ return { kind: "observation", ready: true, value };
711
+ }
712
+ // Missing job evidence is not an empty failure set. Report it to the
713
+ // primitive as a transient failure so the baseline is never cleared by it.
714
+ if (!executorJobEvidenceReadable(snapshot.executor_jobs_state)) {
715
+ throw new ConductorBridgeApiError("server", 503);
716
+ }
717
+ latestToken = token;
718
+ let added;
719
+ if (attentionBaseline === null) {
720
+ if (parsed.since !== undefined && parsed.since === token) {
721
+ // A matching token means the caller already saw this set: keep sleeping.
722
+ attentionBaseline = attentionIds(attention);
723
+ added = [];
724
+ }
725
+ else {
726
+ // No token, or one that no longer matches (the set changed since the
727
+ // caller looked, or it came from the other mode): report every
728
+ // incident present now, so none is lost between driver passes.
729
+ attentionBaseline = new Set();
730
+ added = newIncidents(attentionBaseline, attention);
731
+ }
732
+ }
733
+ else {
734
+ added = newIncidents(attentionBaseline, attention);
735
+ }
736
+ if (added.length > 0) {
737
+ const value = {
738
+ outcome: "changed",
739
+ token,
740
+ mode: "attention",
741
+ window_seconds: windowSeconds,
742
+ run_status: snapshot.run.status,
743
+ incidents: added.slice(0, WAIT_RUN_MAX_INCIDENTS),
744
+ total_count: added.length,
745
+ ...(added.length > WAIT_RUN_MAX_INCIDENTS ? { truncated: true } : {}),
746
+ };
747
+ return { kind: "observation", ready: true, value };
748
+ }
749
+ // Incidents that cleared leave the baseline silently: removals never wake.
750
+ attentionBaseline = attentionIds(attention);
751
+ return { kind: "observation", ready: false };
752
+ };
663
753
  const probe = async (signal) => {
664
754
  let body;
665
755
  try {
@@ -686,6 +776,9 @@ export async function runWaitRunCommand(argv, deps = {}) {
686
776
  : UNEXPECTED_FAILURE_MESSAGE;
687
777
  return { kind: "terminal" };
688
778
  }
779
+ if (parsed.until === "attention") {
780
+ return observeAttention(snapshot);
781
+ }
689
782
  const token = buildWaitRunToken(snapshot);
690
783
  latestToken = token;
691
784
  latestRunStatus = snapshot.run.status;
@@ -42,6 +42,7 @@ export function createWorkerDatabaseDoctorInspector(options) {
42
42
  });
43
43
  return workerDatabase.inspectWorkerDatabaseReadiness({
44
44
  operatorRepositoryRoot,
45
+ ciHarnessOwnerRole: options.env[workerDatabase.HARNESS_CI_OWNER_ENV],
45
46
  hostDigest: containment.hostIdentityDigest(os.hostname()),
46
47
  budgetMs: WORKER_DATABASE_DOCTOR_BUDGET_MS,
47
48
  }, workerDatabase.createDefaultWorkerDatabaseDeps({ stateDir, env: options.env }));
@@ -1054,8 +1054,12 @@ export async function promoteBootstrapPendingCredential(params, deps) {
1054
1054
  error: `No pending bootstrap-invite credential for ${getBootstrapPendingTarget(repoName)} in ${primaryPath}.`,
1055
1055
  };
1056
1056
  }
1057
+ if (Object.prototype.hasOwnProperty.call(params, "observedKey") &&
1058
+ (typeof base[target]?.BAPI_API_KEY === "string" ? base[target].BAPI_API_KEY : null) !== params.observedKey) {
1059
+ return { ok: false, path: primaryPath, target, kind: "credential-conflict", error: "Credential changed since the replacement decision; replay proof preserved." };
1060
+ }
1057
1061
  const hadKey = hasExistingBapiKey(base, repoName);
1058
- if (hadKey && !params.allowOverwriteExistingCredential) {
1062
+ if (hadKey && base[target]?.BAPI_API_KEY !== pending.keySecret && !params.allowOverwriteExistingCredential) {
1059
1063
  return {
1060
1064
  ok: false,
1061
1065
  path: primaryPath,
@@ -1068,6 +1072,8 @@ export async function promoteBootstrapPendingCredential(params, deps) {
1068
1072
  delete next[getBootstrapPendingTarget(repoName)];
1069
1073
  // Preserve sibling secret names under bapi:<repo>; replace ONLY BAPI_API_KEY.
1070
1074
  next[target] = { ...(base[target] ?? {}), BAPI_API_KEY: pending.keySecret };
1075
+ if (base[target]?.BAPI_API_KEY !== pending.keySecret)
1076
+ delete next[target].BAPI_EPIC_LAUNCH_BOUND_BASE_URL;
1071
1077
  const written = await durablyReplaceCredentialStoreJson(primaryPath, next, deps);
1072
1078
  if (!written.ok) {
1073
1079
  return { ok: false, path: primaryPath, target, kind: written.kind, error: written.error };
@@ -1308,22 +1314,10 @@ export async function discardBootstrapPendingCredential(params, deps) {
1308
1314
  return { ok: true, path: primaryPath, target };
1309
1315
  }, (error) => ({ ok: false, path: primaryPath, target, kind: "lock-error", error }));
1310
1316
  }
1311
- /**
1312
- * Upsert `BAPI_API_KEY` for `bapi:<repoName>` into the user-scoped PRIMARY
1313
- * credential store, atomically (temp file + rename) and secret-safely.
1314
- *
1315
- * - Always targets {@link getPrimaryCredentialStorePath}; never writes the
1316
- * fallback path and never touches project/worktree config.
1317
- * - Preserves every existing top-level entry and every sibling secret under
1318
- * `bapi:<repoName>`; replaces only `BAPI_API_KEY`.
1319
- * - On a first primary write, seeds from the legacy fallback store so its
1320
- * entries are not shadowed (`migratedFallback: true`).
1321
- * - POSIX: writes mode `0600` and `chmod`s the temp file before rename.
1322
- * `win32`: skips chmod and relies on user-profile ACLs.
1323
- * - Returns a structured, secret-free result. The `apiKey` value never appears
1324
- * in any returned error, even if an underlying I/O error message contains it.
1325
- */
1326
- export async function upsertBapiCredential(repoName, apiKey, deps) {
1317
+ function observationChanged(options, actual) {
1318
+ return Object.prototype.hasOwnProperty.call(options, "observedKey") && options.observedKey !== (actual ?? null);
1319
+ }
1320
+ export async function upsertBapiCredential(repoName, apiKey, deps, options = {}) {
1327
1321
  const primaryPath = getPrimaryCredentialStorePath(deps);
1328
1322
  const trimmedRepo = (repoName ?? "").trim();
1329
1323
  const trimmedKey = (apiKey ?? "").trim();
@@ -1369,6 +1363,12 @@ export async function upsertBapiCredential(repoName, apiKey, deps) {
1369
1363
  migratedFallback = seeded.migratedFallback;
1370
1364
  }
1371
1365
  const existingEntry = base[target];
1366
+ const actualKey = existingEntry?.BAPI_API_KEY?.trim() || undefined;
1367
+ if (observationChanged(options, actualKey))
1368
+ return { ok: false, path: primaryPath, target,
1369
+ kind: "changed-since-decision", error: "Saved credential changed since the decision. Re-evaluate before writing." };
1370
+ if (actualKey === trimmedKey)
1371
+ return { ok: true, path: primaryPath, target, action: "unchanged", migratedFallback: false };
1372
1372
  const hadKey = !!existingEntry &&
1373
1373
  typeof existingEntry.BAPI_API_KEY === "string" &&
1374
1374
  existingEntry.BAPI_API_KEY.length > 0;
@@ -1504,7 +1504,7 @@ export async function resolveEpicLaunchCredential(repoName, targetBaseUrl, deps,
1504
1504
  kind: "binding-unbound",
1505
1505
  error: `The stored credential "${diagnosticComponent(bundleKey)}" has not been approved for this Bridge API endpoint ` +
1506
1506
  `(${diagnosticComponent(primaryPath)}). Production needs no approval; any other endpoint does. Run guided setup ` +
1507
- `once to bind it: install conductor --launch-profile <name> --base-url ${diagnosticComponent(target)}.`,
1507
+ `once to bind it: install epic-implementer --launch-profile <name> --base-url ${diagnosticComponent(target)}.`,
1508
1508
  };
1509
1509
  }
1510
1510
  // An unreadable read-back is refused like a mismatch: the key was read a
@@ -1516,7 +1516,7 @@ export async function resolveEpicLaunchCredential(repoName, targetBaseUrl, deps,
1516
1516
  error: `The stored credential "${diagnosticComponent(bundleKey)}" is approved for a different Bridge API endpoint than the ` +
1517
1517
  "selected target. It was not sent. A key approved for a local server is never sent to " +
1518
1518
  "production: pass that server's --launch-profile <name> or --base-url <url>, or bind the key " +
1519
- "once with install conductor --launch-profile <name> --base-url <url>.",
1519
+ "once with install epic-implementer --launch-profile <name> --base-url <url>.",
1520
1520
  };
1521
1521
  }
1522
1522
  return { ok: true, apiKey: stored.values.BAPI_API_KEY, source: "file", binding: "store-bound" };
@@ -1573,7 +1573,7 @@ export async function readStoredBinding(bundleKey, deps) {
1573
1573
  * durable replacement; every other entry and sibling field is preserved. A store
1574
1574
  * with no key for the repository is refused rather than creating one.
1575
1575
  */
1576
- export async function bindEpicLaunchCredential(repoName, targetBaseUrl, deps) {
1576
+ export async function bindEpicLaunchCredential(repoName, targetBaseUrl, deps, options = {}) {
1577
1577
  const target = `bapi:${repoName.trim()}`;
1578
1578
  const baseUrl = normalizeBoundBaseUrl(targetBaseUrl);
1579
1579
  if (repoName.trim().length === 0 || baseUrl === null) {
@@ -1594,6 +1594,9 @@ export async function bindEpicLaunchCredential(repoName, targetBaseUrl, deps) {
1594
1594
  error: `No stored BAPI_API_KEY under "${target}" in ${primaryPath} to bind.`,
1595
1595
  };
1596
1596
  }
1597
+ if (observationChanged(options, entry.BAPI_API_KEY.trim()))
1598
+ return { ok: false, target,
1599
+ kind: "changed-since-decision", error: "Saved credential changed since endpoint authorization. Re-evaluate before binding." };
1597
1600
  const previous = normalizeBoundBaseUrl(entry[BAPI_EPIC_LAUNCH_BOUND_BASE_URL_FIELD]);
1598
1601
  if (previous === baseUrl)
1599
1602
  return { ok: true, target, action: "unchanged", path: primaryPath };
@@ -1913,6 +1916,8 @@ export async function promoteModernBootstrapCredential(scope, proof, deps, allow
1913
1916
  return { ok: true, path: getPrimaryCredentialStorePath(deps) };
1914
1917
  if (!record || record.keySecret !== proof.keySecret || record.canonical !== proof.canonical || record.fingerprint !== proof.fingerprint || record.folder !== scope.folder || record.baseUrl !== scope.baseUrl || reference?.LOCATOR !== scope.locator || reference.FOLDER !== scope.folder || reference.BASE_URL !== scope.baseUrl)
1915
1918
  throw new Error(modernRecoveryError);
1919
+ if (consentedKey !== undefined && (existingKey ?? null) !== consentedKey)
1920
+ return { ok: false, error: "Destination credential changed after the decision. Replay proof preserved." };
1916
1921
  if (existingKey && existingKey !== proof.keySecret) {
1917
1922
  if (!allowOverwrite)
1918
1923
  return { ok: false, error: "The canonical credential already exists; overwrite consent is required.", needsConsent: true, observedKey: existingKey };