@bridge_gpt/mcp-server 0.2.70 → 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 (134) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +29 -4
  3. package/build/agent-notes.js +171 -95
  4. package/build/agent-registry.js +5 -5
  5. package/build/agents.generated.js +12 -2
  6. package/build/bounded-wait.js +9 -1
  7. package/build/bridge-permissions.js +17 -5
  8. package/build/bridge-worktree-inspection.js +237 -0
  9. package/build/check-evidence.js +6 -0
  10. package/build/claude-review-workflow.js +1 -1
  11. package/build/cli-help.js +6 -0
  12. package/build/codex-auto-recovery.js +126 -0
  13. package/build/codex-skill-adapter.js +2 -0
  14. package/build/commands.generated.js +5 -5
  15. package/build/conductor/bridge-api-client.js +776 -23
  16. package/build/conductor/command-drift-production.js +7 -2
  17. package/build/conductor/doctor.js +93 -13
  18. package/build/conductor/epic-implementer-cli.js +55 -2
  19. package/build/conductor/gate-discovery.js +659 -19
  20. package/build/conductor/gate-settings-review.js +751 -0
  21. package/build/conductor/git-hooks-uninstall.js +112 -0
  22. package/build/conductor/git-hooks.js +81 -15
  23. package/build/conductor/guided-repair.js +10 -1
  24. package/build/conductor/install-doctor.js +2 -4
  25. package/build/conductor/launch-need-probes.js +16 -11
  26. package/build/conductor/launch-plan.js +185 -0
  27. package/build/conductor/local-merge.js +12 -1
  28. package/build/conductor/merge-execution-contract.js +1 -1
  29. package/build/conductor/merged-child-check.js +2 -1
  30. package/build/conductor/precheck-timings.js +14 -0
  31. package/build/conductor/prerequisite-inputs.js +379 -0
  32. package/build/conductor/preview-observations.js +10 -0
  33. package/build/conductor/readiness-assessment.js +78 -0
  34. package/build/conductor/readiness-cli.js +10 -0
  35. package/build/conductor/readiness-prerequisites.js +53 -0
  36. package/build/conductor/readiness-sections.js +25 -9
  37. package/build/conductor/readiness.js +20 -2
  38. package/build/conductor/recovery-cli.js +281 -14
  39. package/build/conductor/recovery-operations.js +78 -5
  40. package/build/conductor/repair-contract.js +33 -0
  41. package/build/conductor/tools.js +34 -3
  42. package/build/conductor/wait-run-attention.js +115 -0
  43. package/build/conductor/wait-run-cli.js +96 -3
  44. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  45. package/build/credential-store.js +25 -20
  46. package/build/dependency-install-declarations.js +157 -0
  47. package/build/docs.generated.js +4 -4
  48. package/build/doctor.js +37 -5
  49. package/build/drive-epic-help.js +2 -2
  50. package/build/drive-epic.js +240 -56
  51. package/build/epic-ci-workflow-drift.js +71 -23
  52. package/build/epic-ci-workflow-install.js +83 -26
  53. package/build/epic-ci-workflow-v1.js +132 -0
  54. package/build/epic-ci-workflow.js +174 -13
  55. package/build/epic-implementer-bin.js +119 -44
  56. package/build/epic-launch-profile.js +1 -1
  57. package/build/executor/ci-rerun-job.js +220 -14
  58. package/build/executor/cli.js +2 -0
  59. package/build/executor/completion-contract.js +16 -0
  60. package/build/executor/credentials.js +1 -1
  61. package/build/executor/delivery-observations.js +113 -0
  62. package/build/executor/delivery-outcome.js +30 -0
  63. package/build/executor/dependency-refresh-runner.js +132 -0
  64. package/build/executor/dependency-refresh.js +530 -0
  65. package/build/executor/deps.js +4 -0
  66. package/build/executor/env.js +274 -5
  67. package/build/executor/gate-qualification-job.js +20 -5
  68. package/build/executor/harness-coverage.js +19 -0
  69. package/build/executor/http-client.js +35 -1
  70. package/build/executor/index.js +2 -1
  71. package/build/executor/install-preflight.js +1 -1
  72. package/build/executor/job-runner.js +355 -36
  73. package/build/executor/likely-tests.js +100 -98
  74. package/build/executor/preflight.js +5 -0
  75. package/build/executor/process-containment.js +18 -0
  76. package/build/executor/prompt-spec.js +84 -15
  77. package/build/executor/reconcile-overlap-job.js +6 -1
  78. package/build/executor/required-verification.js +28 -0
  79. package/build/executor/required-work-diagnostics.js +30 -0
  80. package/build/executor/required-work-ledger.js +19 -1
  81. package/build/executor/results.js +42 -0
  82. package/build/executor/service-discovery.js +42 -0
  83. package/build/executor/service-lifecycle.js +109 -2
  84. package/build/executor/service-uninstall.js +205 -0
  85. package/build/executor/service-unit.js +5 -3
  86. package/build/executor/test-clock.js +3 -0
  87. package/build/executor/verification-hints.js +179 -0
  88. package/build/executor/worker-command.js +188 -1
  89. package/build/executor/worker-database.js +299 -40
  90. package/build/executor/worker-finalization.js +65 -10
  91. package/build/executor/worker-guard-hook.js +10 -2
  92. package/build/executor/worker-resources.js +12 -1
  93. package/build/executor/worker-verification-guidance.js +64 -0
  94. package/build/executor/worktree-inspection.js +42 -0
  95. package/build/github-sign-in.js +1 -1
  96. package/build/index.js +767 -310
  97. package/build/init.js +3 -3
  98. package/build/install-bridge-conductor-gate.js +416 -41
  99. package/build/install-bridge-conductor-setup.js +135 -32
  100. package/build/install-bridge-conductor.js +769 -353
  101. package/build/install-bridge.js +419 -124
  102. package/build/install-maintenance.js +104 -0
  103. package/build/install-reexec.js +1 -1
  104. package/build/local-cleanup.js +59 -0
  105. package/build/mcp-install-state.js +68 -2
  106. package/build/merge-workflow-install.js +22 -2
  107. package/build/package-script-semantics.js +10 -0
  108. package/build/pipeline-utils.js +1 -1
  109. package/build/pipelines.generated.js +6 -6
  110. package/build/plan-execution-ledger.js +171 -10
  111. package/build/plane/plane-freshness.js +12 -9
  112. package/build/plane/preflight.js +19 -0
  113. package/build/plane/terminal-run-cleanup.js +5 -1
  114. package/build/plane/terminal-run-status.js +4 -0
  115. package/build/printed-remedy-commands.js +31 -4
  116. package/build/readiness-check.js +1 -78
  117. package/build/readiness-prerequisites.generated.js +199 -0
  118. package/build/readme.generated.js +1 -1
  119. package/build/repository-toolchains.js +623 -0
  120. package/build/setup-change-policy.js +32 -0
  121. package/build/setup-epic.js +26 -9
  122. package/build/setup-question.js +62 -0
  123. package/build/start-tickets.js +4 -0
  124. package/build/test-command-detection.js +61 -80
  125. package/build/test-support/notes-fs.js +40 -0
  126. package/build/ticket-delivery-artifacts.js +7 -0
  127. package/build/ticket-delivery-enrollment.js +80 -4
  128. package/build/ticket-delivery-run-scope.js +128 -0
  129. package/build/version.generated.js +3 -3
  130. package/build/worker-guard-hook-bin.js +2 -2
  131. package/build/worktrees.js +105 -0
  132. package/docs/EPIC-IMPLEMENTER.md +43 -0
  133. package/docs/epic-implementer/getting-started.md +95 -14
  134. package/package.json +2 -2
@@ -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, } 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,14 +177,17 @@ 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,
184
+ ...(options.externalRepairOperationId !== undefined
185
+ ? { externalRepairOperationId: options.externalRepairOperationId }
186
+ : {}),
184
187
  });
185
188
  }
186
189
  catch (err) {
187
- const refusal = reviewHeadRefusal(err);
190
+ const refusal = reviewHeadRefusal(err) ?? externalRepairRefusal(err);
188
191
  if (refusal !== null) {
189
192
  return {
190
193
  ok: false,
@@ -193,8 +196,14 @@ async function ticketRecoveryWithRetry(access, options, mutate) {
193
196
  ticketKey: options.ticketKey,
194
197
  errorCode: refusal.errorCode,
195
198
  message: refusal.message,
199
+ ...(refusal.retryable !== undefined ? { retryable: refusal.retryable } : {}),
196
200
  };
197
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.
198
207
  return {
199
208
  ok: false,
200
209
  kind: "unavailable",
@@ -205,6 +214,7 @@ async function ticketRecoveryWithRetry(access, options, mutate) {
205
214
  }
206
215
  if (result.ok) {
207
216
  const recovery = result.ticket_status.review_head_recovery;
217
+ const external = result.ticket_status.external_repair;
208
218
  return {
209
219
  ok: true,
210
220
  kind: "unparked",
@@ -212,8 +222,11 @@ async function ticketRecoveryWithRetry(access, options, mutate) {
212
222
  ticketKey: options.ticketKey,
213
223
  status: result.ticket_status.status,
214
224
  ...(recovery ? { reviewHeadRecovery: recovery } : {}),
225
+ ...(external ? { externalRepair: external } : {}),
215
226
  };
216
227
  }
228
+ if (options.expectedRowVersion !== undefined)
229
+ break;
217
230
  // `result.kind === "cas-conflict"`: a concurrent write moved the ticket's
218
231
  // row_version between our read and our mutate. Loop back to a fresh read —
219
232
  // never reuse `result.current_row_version` here.
@@ -250,6 +263,43 @@ function reviewHeadRefusal(err) {
250
263
  return null;
251
264
  return { errorCode: code, message: REVIEW_HEAD_REFUSAL_MESSAGES[code] ?? "refused" };
252
265
  }
266
+ /**
267
+ * BAPI-1537: fixed operator sentences for the external-repair refusal codes,
268
+ * each naming the exit from the ticket's refusal table. Chosen by code so no
269
+ * server or provider text reaches the terminal.
270
+ */
271
+ const EXTERNAL_REPAIR_REFUSAL_MESSAGES = {
272
+ EXTERNAL_REPAIR_RUN_NOT_RECOVERABLE: "the run is paused, stopped, quarantined, or not active; resolve the run control " +
273
+ "(for example resume-run), then retry with the same operation id",
274
+ EXTERNAL_REPAIR_NOT_PARKED: "the ticket is not parked at exactly one gate, so the engine owns it; re-read explain-run",
275
+ EXTERNAL_REPAIR_LIVE_WORK: "an executor job for this ticket is queued or running; wait for it to end, re-read, " +
276
+ "and re-diagnose",
277
+ EXTERNAL_REPAIR_BRANCH_MISMATCH: "the repair is not on the ticket's own feature branch; push it to that branch",
278
+ EXTERNAL_REPAIR_ANCESTRY: "the branch head equals or does not descend from the ticket's recorded head; replay " +
279
+ "the commits fast-forward onto that head (never force), or end the intervention",
280
+ EXTERNAL_REPAIR_PR_MISMATCH: "the open pull request is cross-repository or has the wrong base or head; fix its " +
281
+ "base or head, or close the stray pull request, then retry",
282
+ EXTERNAL_REPAIR_PR_AMBIGUOUS: "more than one pull request is open from the ticket's branch; close the extras, then retry",
283
+ EXTERNAL_REPAIR_HEAD_CLAIMED: "another ticket or run already has this head bound; this is outside the sandbox, so " +
284
+ "apply the stop list",
285
+ EXTERNAL_REPAIR_OPERATION_CONFLICT: "this operation id already adopted a different head; use a new operation id",
286
+ EXTERNAL_REPAIR_UNAVAILABLE: "a provider or ancestry read was unreadable; retry with the same operation id",
287
+ EXTERNAL_REPAIR_ALREADY_INTEGRATED: "the repair head is already in the epic branch, so the parked-external-merge fold owns " +
288
+ "recovery; re-read explain-run",
289
+ };
290
+ /** Map a thrown client error to an external-repair refusal, or `null` for anything else. */
291
+ function externalRepairRefusal(err) {
292
+ if (!(err instanceof ConductorBridgeApiError) || err.status !== 409)
293
+ return null;
294
+ const code = err.errorCode;
295
+ if (typeof code !== "string" || !EXTERNAL_REPAIR_REFUSAL_CODES.includes(code))
296
+ return null;
297
+ return {
298
+ errorCode: code,
299
+ message: EXTERNAL_REPAIR_REFUSAL_MESSAGES[code] ?? "refused",
300
+ retryable: EXTERNAL_REPAIR_RETRYABLE_CODES.includes(code),
301
+ };
302
+ }
253
303
  /**
254
304
  * Unpark a parked `needs_human` ticket, with a bounded authoritative-reread
255
305
  * retry on a concurrent `row_version` bump.
@@ -283,6 +333,9 @@ function classifyRepairError(err, fallback) {
283
333
  code: err.errorCode,
284
334
  status: err.status,
285
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
+ : {}),
286
339
  };
287
340
  }
288
341
  return { ok: false, kind: "unavailable", message: safeDiagnosticMessage(err, fallback) };
@@ -310,6 +363,19 @@ export async function resolveHandoffRepair(access, options, deps = {}) {
310
363
  return classifyRepairError(err, "resolve-handoff request failed");
311
364
  }
312
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
+ }
313
379
  /**
314
380
  * Dispatch a remediation job with driver context. `context` must already be
315
381
  * validated against `DRIVER_CONTEXT_MAX_BYTES`; the server selects the job type.
@@ -379,7 +445,14 @@ export async function mergeChildRepair(access, options, deps = {}) {
379
445
  // which is discarded — never the server's action key, which the server
380
446
  // recomposes itself at completion.
381
447
  action_key: `merge-child:${options.epicRunId}:${options.prNumber}`,
382
- }, { 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
+ },
383
456
  // BAPI-1136: an explicitly configured local credential, never the ambient
384
457
  // login. `env` remains the source of the allowlisted operational base only.
385
458
  { env, credential });
@@ -917,7 +990,7 @@ export const RESUME_CI_POST_LIMIT = 3;
917
990
  const RESUME_CI_RETRY_DELAY_MS = 250;
918
991
  const FULL_SHA_PATTERN = /^[0-9a-f]{40}$/;
919
992
  const FINGERPRINT_PATTERN = /^[0-9a-f]{64}$/;
920
- 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"]);
921
994
  function isRecordValue(value) {
922
995
  return value !== null && typeof value === "object" && !Array.isArray(value);
923
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 }));