@bridge_gpt/mcp-server 0.2.74 → 0.2.76

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 (102) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/prompt.js +9 -21
  3. package/build/agents.generated.js +6 -6
  4. package/build/authored-plan.js +542 -0
  5. package/build/bridge-permissions.js +8 -0
  6. package/build/codex-auto-recovery.js +25 -7
  7. package/build/commands.generated.js +7 -7
  8. package/build/conductor/bridge-api-client.js +807 -52
  9. package/build/conductor/declare-blocked.js +4 -0
  10. package/build/conductor/driver-pass.js +8 -0
  11. package/build/conductor/epic-implementer-cli.js +341 -96
  12. package/build/conductor/epic-server-journal.js +13 -0
  13. package/build/conductor/epic-server-recipe.js +15 -5
  14. package/build/conductor/epic-server-runtime.js +163 -45
  15. package/build/conductor/epic-server.js +13 -6
  16. package/build/conductor/gate-discovery.js +209 -9
  17. package/build/conductor/gate-settings-review.js +7 -11
  18. package/build/conductor/install-doctor.js +30 -2
  19. package/build/conductor/launch-plan.js +58 -12
  20. package/build/conductor/local-merge.js +54 -12
  21. package/build/conductor/open-decision-phrases.js +50 -0
  22. package/build/conductor/pr-ci-producer.js +12 -3
  23. package/build/conductor/prerequisite-inputs.js +181 -14
  24. package/build/conductor/readiness-sections.js +46 -13
  25. package/build/conductor/readiness.js +3 -40
  26. package/build/conductor/recovery-cli.js +12 -12
  27. package/build/conductor/repository-workflow-remedy.js +147 -7
  28. package/build/conductor/ui-readiness.js +224 -0
  29. package/build/conductor/wait-run-attention.js +9 -4
  30. package/build/conductor/wait-run-cli.js +9 -2
  31. package/build/connect-github-api.js +18 -0
  32. package/build/connect-github.js +35 -18
  33. package/build/docs.generated.js +3 -3
  34. package/build/drive-epic.js +787 -37
  35. package/build/epic-ci-workflow.js +3 -2
  36. package/build/epic-implementer-bin.js +200 -66
  37. package/build/epic-implementer-bundle-cli.js +61 -0
  38. package/build/epic-implementer-claude-hook-bin.js +1 -1
  39. package/build/epic-implementer-env.js +3 -4
  40. package/build/epic-integration-pr.js +5 -2
  41. package/build/epic-launch-context.js +8 -1
  42. package/build/epic-shared/cut-protocol.js +55 -3
  43. package/build/executor/completion-contract.js +24 -1
  44. package/build/executor/failure-reason-codes.js +2 -0
  45. package/build/executor/gate-qualification-job.js +193 -23
  46. package/build/executor/gate-qualification-tests-ran.js +232 -0
  47. package/build/executor/integration-job.js +56 -2
  48. package/build/executor/job-runner.js +13 -723
  49. package/build/executor/job-type-wrappers.js +734 -0
  50. package/build/executor/merge-job.js +45 -1
  51. package/build/executor/permissions.js +187 -2
  52. package/build/executor/preflight.js +6 -2
  53. package/build/executor/process-containment.js +8 -1
  54. package/build/executor/provider-checks.js +28 -5
  55. package/build/executor/reconcile-overlap-job.js +70 -17
  56. package/build/executor/required-verification.js +28 -2
  57. package/build/executor/required-work-ledger.js +7 -2
  58. package/build/executor/resume-pre-spawn.js +32 -8
  59. package/build/executor/runner.js +30 -5
  60. package/build/executor/types.js +9 -0
  61. package/build/executor/worker-database.js +6 -1
  62. package/build/executor/worker-guard-hook.js +24 -2
  63. package/build/executor/worktree.js +12 -1
  64. package/build/generated/ticket-status.js +20 -0
  65. package/build/index.js +627 -551
  66. package/build/init.js +16 -0
  67. package/build/install-bridge-conductor-answers.js +32 -1
  68. package/build/install-bridge-conductor-apply.js +21 -3
  69. package/build/install-bridge-conductor-assessment.js +185 -12
  70. package/build/install-bridge-conductor-compact.js +2 -0
  71. package/build/install-bridge-conductor-contracts.js +9 -1
  72. package/build/install-bridge-conductor-gate.js +257 -80
  73. package/build/install-bridge-conductor-setup.js +106 -6
  74. package/build/install-bridge-conductor-trial-report.js +170 -0
  75. package/build/install-bridge-conductor.js +740 -124
  76. package/build/mcp-host-config.js +54 -37
  77. package/build/phase-context-git-probe.js +16 -0
  78. package/build/pipelines.generated.js +15 -15
  79. package/build/plan-execution-ledger.js +27 -0
  80. package/build/plan-generation.js +17 -0
  81. package/build/plane/plane-freshness.js +43 -26
  82. package/build/printed-remedy-commands.js +62 -0
  83. package/build/readme.generated.js +1 -1
  84. package/build/repository-toolchains.js +11 -5
  85. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  86. package/build/secret-redaction.js +3 -0
  87. package/build/setup-epic.js +51 -9
  88. package/build/test-support/create-preview-world.js +232 -0
  89. package/build/test-support/executor-source-files.js +1 -1
  90. package/build/ticket-delivery.js +65 -0
  91. package/build/v2-readiness-requirements.js +13 -4
  92. package/build/version.generated.js +3 -3
  93. package/build/worker-guard-hook-bin.js +2 -2
  94. package/build/worktree-core.js +51 -7
  95. package/docs/EPIC-IMPLEMENTER.md +83 -4
  96. package/docs/epic-implementer/getting-started.md +1 -1
  97. package/docs/install/github-app.md +79 -92
  98. package/package.json +1 -1
  99. package/pipelines/implement-ticket.json +2 -2
  100. package/build/conductor/epic-reconcile.js +0 -603
  101. package/build/conductor/epic-runtime.js +0 -2020
  102. package/build/conductor/epic-state.js +0 -774
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridge_gpt/mcp-server",
3
- "version": "0.2.74",
3
+ "version": "0.2.76",
4
4
  "description": "Bridge API MCP server — exposes Jira endpoints as MCP tools for Claude Code agents",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "implement-ticket",
3
- "description": "Initial feature workflow: generate a plan, register the delivery binding and produce artifacts, checkpoint to origin, verify, commit, ask the server to publish (an ordinary or draft PR, or a held blocked checkpoint), close accepted post-PR gaps, and monitor CI. Finishing every recipe step is not delivery completion: the server readiness outcome decides that, and the final report states it. Re-entry of this initial workflow may reuse a fresh plan, but remaining-work corrections and continuations use versioned focused intent on the retained branch and never re-enter this recipe.",
3
+ "description": "Initial feature workflow: generate a plan, register the delivery binding and produce artifacts, checkpoint to origin, verify, commit, ask the server to publish (an ordinary or draft PR, or a held blocked checkpoint), close accepted post-PR gaps, and monitor CI. Finishing every recipe step is not delivery completion: the server readiness outcome decides that, and the final report states it. Re-entry of this initial workflow may reuse a fresh plan, but remaining-work corrections and continuations use versioned focused intent on the retained branch and never re-enter this recipe.\n\n<!-- BEGIN BRIDGE WORKER CONTINUATION RULE -->\n**Continue, reconsider, or record an honest gap**\n\n- **A hold that lists your own (`self_recorded`) blockers is not the end of the run.** Finish your own unfinished work, record it with `record_phase_result`, and call `create_pull_request` again.\n- **Before recording any step as escalated or cannot-do, reconsider once.** Try a corrected command, a disposable fixture or local service, an equivalent check, or a CI-covered deferral, using capabilities already provisioned for this repository. Never search for or obtain credentials.\n- **If a review or verification step truly can't be done, record an honest gap and continue other work.** Running out of budget never makes unfinished implementation, unwritten tests, or failing assertions gap-eligible.\n- **Never mark a step `executed` that you didn't run or write.**\n- **An incomplete run ends only on an observed outside blocker or a host-forced end.** Before a forced end, commit, push, and call `record_checkpoint`. A person running the session can always stop it. Normal completion and existing safety stops still apply. Open a PR only through `create_pull_request`'s readiness check.\n<!-- END BRIDGE WORKER CONTINUATION RULE -->",
4
4
  "variables": ["ticket_key", "docs_dir", "provider", "verification_scope"],
5
5
  "steps": [
6
6
  {
@@ -44,7 +44,7 @@
44
44
  {
45
45
  "type": "agent_task",
46
46
  "instruction_file": "create-pr.md",
47
- "description": "Check server delivery readiness, then create a pull request with a title derived from the commit subject. A delivery hold is a supported blocked-checkpoint exit: the branch and head are preserved and the run ends there."
47
+ "description": "Check server delivery readiness, then create a pull request with a title derived from the commit subject. A delivery hold is a saved checkpoint: it preserves the branch and head while you finish your own blockers and ask again."
48
48
  },
49
49
  {
50
50
  "type": "agent_task",
@@ -1,603 +0,0 @@
1
- /**
2
- * Deterministic observed→desired reconciliation for the Epic Supervisor
3
- * (BAPI-408, BAPI-436).
4
- *
5
- * Executes five steps in order:
6
- * 1. Fold terminal signals into Postgres via CAS
7
- * 2. Compute the ready-set (pure, no LLM — Goal 8)
8
- * 3. Dispatch ready tickets idempotently (key claim → spawn → correlate)
9
- * 4. Action approved merges via C6 delegation
10
- * 5. Schedule post-action wait hooks
11
- *
12
- * Dispatch is purely merge-gated (BAPI-436): dependents are dispatched only
13
- * after their predecessor reaches "done", which requires a merge.succeeded
14
- * signal. gate.met and run.stopped fold to the intermediate "ready_for_review"
15
- * state — dependents do NOT dispatch on these signals.
16
- *
17
- * All durable mutations go through injected seams so the logic is testable
18
- * without real network, ledger, or terminal access.
19
- */
20
- import { computeReadySet, decideRemediation, DEFAULT_MAX_SPEC_REVIEW_ATTEMPTS } from "./epic-state.js";
21
- import { extractMergeActionIdentityFromGateEvent } from "./merge-ledger.js";
22
- /**
23
- * The canonical park reason for a stale hold that ran out its deadline.
24
- *
25
- * Byte-identical to the Python reconciler's `SHADOW_STALE_DEADLINE_REASON`, and
26
- * that is the point: both conductors park for the same cause, so an operator
27
- * greps one string. This introduces no `epic_ticket_status` value — the ticket
28
- * moves to the EXISTING `needs_human`, whose vocabulary is closed (R14).
29
- */
30
- export const SHADOW_STALE_DEADLINE_REASON = "shadow_stale_deadline";
31
- /** Normalize either accepted seam shape into the richer one. */
32
- function normalizeShadowDecision(raw) {
33
- return typeof raw === "string" ? { verdict: raw } : raw;
34
- }
35
- /**
36
- * Sanitize a thrown value into a single-line, bounded diagnostic string for a
37
- * tick warning (BAPI-487 Requirement 2). Surfaces the real `err.message` (the
38
- * remediation messages — `remediate: no PR binding for <KEY>`, `remediate: no
39
- * head_sha for PR <N>` — are safe, secret-free text) instead of the opaque
40
- * constructor name that hid the true failure for an entire smoke test. Collapses
41
- * whitespace (defeating multiline log injection), caps length, and falls back to
42
- * the constructor name for an empty message or `fallback` for a non-Error throw.
43
- */
44
- export function safeDiagnosticMessage(err, fallback) {
45
- const raw = err instanceof Error
46
- ? (err.message.trim() || err.constructor.name)
47
- : fallback;
48
- return raw.replace(/\s+/g, " ").slice(0, 500);
49
- }
50
- // ---------------------------------------------------------------------------
51
- // reconcileEpic
52
- // ---------------------------------------------------------------------------
53
- /**
54
- * Surface an elapsed scope-freshness deadline without transitioning the ticket.
55
- *
56
- * Deliberately diagnostic. The `epic_ticket_status` vocabulary — `parsing`,
57
- * `needs_human` and the rest — is owned by the SERVER-side reconciler
58
- * (`api/library/epic_implementer/reconciler.py`), which is the single transition
59
- * authority for it and already parks this exact condition through its ordinary
60
- * `_park_needs_human` commit point under the same `shadow_stale_deadline` reason.
61
- * This pass runs the legacy supervisor's own, narrower status vocabulary, and
62
- * minting a park from here would give one ticket two transition authorities —
63
- * the failure mode R14 exists to prevent.
64
- *
65
- * So what this does is the honest half: it stops the dispatch (the caller
66
- * `continue`s), and it makes the expiry and its cause visible in the tick's
67
- * warnings so an operator watching this side is not left wondering why a ticket
68
- * sat still. The durable park is observed, not raced for.
69
- */
70
- function reportShadowDeadlineExpired(deps, result, ticketKey, verdict, blockedAdvanceReason) {
71
- const reason = blockedAdvanceReason
72
- ? `${SHADOW_STALE_DEADLINE_REASON}:${blockedAdvanceReason}`
73
- : SHADOW_STALE_DEADLINE_REASON;
74
- result.warnings.push(`shadow-freshness deadline elapsed for ${ticketKey}: ${reason}`);
75
- deps.log(`[epic-reconcile] ${ticketKey} shadow watermark ${verdict} past deadline (${reason}); ` +
76
- `holding dispatch — the server reconciler owns the needs_human park`);
77
- }
78
- /**
79
- * Execute the deterministic observed→desired reconciliation pass. All I/O is
80
- * behind injected seams; the ready-set is computed by pure code (no LLM).
81
- */
82
- export async function reconcileEpic(access, observed, plan, deps, supervisorConfig) {
83
- const result = {
84
- signals_folded: 0,
85
- dispatched: 0,
86
- merges_actioned: 0,
87
- warnings: [],
88
- };
89
- const escalate = deps.escalateOnce ?? (async () => undefined);
90
- // Step 1: Fold terminal signals → CAS into Postgres
91
- for (const signal of observed.unfolded_terminal_signals) {
92
- let casResult;
93
- try {
94
- casResult = await deps.casTicketStatus(observed.epic_key, signal.ticket_key, signal.postgres_row_version, signal.next_status, observed.plan_version);
95
- }
96
- catch (err) {
97
- const safeMsg = err instanceof Error ? err.constructor.name : "cas error";
98
- result.warnings.push(`cas-error folding ${signal.signal_type} for ${signal.ticket_key}: ${safeMsg}`);
99
- // BAPI-500: the fold CAS did not durably run, so any PREDICTED post-fold
100
- // row version for this ticket is unconfirmed. Clear it so the same-pass
101
- // remediation CAS falls back to the tick-start snapshot instead of trusting
102
- // a snapshot+1 that was never written.
103
- observed.ticket_post_fold_row_versions?.delete(signal.ticket_key);
104
- continue;
105
- }
106
- if (casResult.ok) {
107
- result.signals_folded += 1;
108
- // BAPI-500: confirm the post-fold row version from the ACTUAL CAS response
109
- // (never the tick-start snapshot or a re-derived `+ 1`), so a follow-on
110
- // remediation CAS in this same pass CASes against the durable snapshot+1.
111
- // Keyed per ticket — one status CAS per ticket per tick. Do NOT touch
112
- // `observed.ticket_row_versions`; it stays the tick-start snapshot so
113
- // callers can distinguish fallback values from same-pass post-fold values.
114
- observed.ticket_post_fold_row_versions ??= new Map();
115
- observed.ticket_post_fold_row_versions.set(signal.ticket_key, casResult.ticket_status.row_version);
116
- deps.log(`[epic-reconcile] folded ${signal.signal_type} for ${signal.ticket_key} → ${signal.next_status}`);
117
- // BAPI-442: fire teardown + Jira transition strictly after merge.succeeded
118
- // CAS → done. Both are fail-open: errors are logged and never abort the pass.
119
- // BAPI-527: additionally require next_status === "done". Post-merge parse
120
- // (parse-after-merge) folds a merge.succeeded signal to `parse_pending` while
121
- // the repository re-index runs, and to `blocked` on permanent parse failure —
122
- // teardown/Jira transition must NOT fire in either of those non-done folds, or
123
- // the merged branch/worktree would be torn down (and Jira transitioned) before
124
- // the ticket is truly done. They fire only once the ticket actually reaches
125
- // `done` (either an immediate merge.succeeded fold when parse-after-merge is
126
- // off, or the later parse-success fold that re-tags next_status back to "done").
127
- if (signal.signal_type === "merge.succeeded" && signal.next_status === "done") {
128
- if (supervisorConfig?.teardown_enabled && deps.teardownSeam) {
129
- await deps.teardownSeam(observed.epic_key, signal.ticket_key).catch((e) => {
130
- const safeMsg = e instanceof Error ? e.constructor.name : "teardown error";
131
- deps.log(`[epic-reconcile] teardown error for ${signal.ticket_key}: ${safeMsg}`);
132
- });
133
- }
134
- if (deps.jiraTransitionSeam) {
135
- await deps.jiraTransitionSeam(observed.epic_key, signal.ticket_key).catch((e) => {
136
- const safeMsg = e instanceof Error ? e.constructor.name : "jira error";
137
- deps.log(`[epic-reconcile] jira-transition error for ${signal.ticket_key}: ${safeMsg}`);
138
- });
139
- }
140
- }
141
- }
142
- else {
143
- // CAS conflict: another tick already advanced this ticket — non-fatal.
144
- // BAPI-500: the predicted post-fold version is unconfirmed (the real row
145
- // version is whatever the other writer left), so clear it and let the
146
- // same-pass remediation CAS fall back to the tick-start snapshot.
147
- observed.ticket_post_fold_row_versions?.delete(signal.ticket_key);
148
- result.warnings.push(`cas-conflict folding ${signal.signal_type} for ${signal.ticket_key}`);
149
- }
150
- }
151
- // Step 1.5: LEGACY/unreachable safety seed — not the authority that makes an
152
- // approved run runnable. Live Conductor v2 initial seeding happens server-side
153
- // in the Python approve-plan DAL workflow (`approve_epic_plan()` seeds every
154
- // plan node before activating the run, BAPI-633). This loop belongs to the
155
- // frozen v1 tick path and is retained only as defensive behavior.
156
- //
157
- // Seed planned status rows for every plan node. Idempotent: the
158
- // backend read-back no-ops a re-seed of an existing row (A6/BAPI-507), so a
159
- // normal multi-tick run no longer produces per-node seed warnings. When a seed
160
- // DOES fail, the warning carries safe backend diagnostics (status/code/message
161
- // preview) rather than the opaque `ConductorBridgeApiError` constructor name.
162
- for (const ticket of plan.tickets) {
163
- try {
164
- await deps.seedTicketStatus(observed.epic_key, ticket.ticket_key, plan.plan_version);
165
- }
166
- catch (err) {
167
- result.warnings.push(`seed-error for ${ticket.ticket_key}: ${safeDiagnosticMessage(err, "seed error")}`);
168
- }
169
- }
170
- // Step 2: Compute the ready-set (pure — never calls LLM)
171
- const readySet = computeReadySet(plan, observed.ticket_statuses);
172
- // Step 3: Dispatch each ready ticket idempotently.
173
- //
174
- // BAPI-445 — pre-implementation spec re-review sequencing gate (Phase 1). When
175
- // `auto_rereview_enabled` is on and the review seam is wired, a `planned` ready
176
- // ticket must first pass a spec re-review: this loop advances it
177
- // planned → reviewing, spawns the review run under a `:review` dispatch role,
178
- // correlates its run_id, and STOPS — implementation does NOT dispatch in the
179
- // same tick (honouring the product directive: "wait for review to complete
180
- // before implementation begins"). The reviewing → ready (or → blocked) fold
181
- // happens on a later tick once the review completes/votes; only THEN does this
182
- // loop dispatch implementation. Gating only on `planned` (not `ready`) is
183
- // deliberate: a `ready` ticket already passed review (reviewing → ready) or the
184
- // flag is off, so re-gating it would loop forever.
185
- for (const ticketKey of readySet) {
186
- const currentStatus = observed.ticket_statuses.get(ticketKey) ?? "planned";
187
- if (supervisorConfig?.auto_rereview_enabled &&
188
- deps.dispatchReviewSeam &&
189
- currentStatus === "planned") {
190
- await enterSpecReview(observed, deps, result, escalate, ticketKey);
191
- // Either the review was dispatched, or a benign race/failure was logged;
192
- // in every case implementation must NOT dispatch this tick.
193
- continue;
194
- }
195
- // BAPI-654 (T2): commit-watermark dispatch gate. A DAG-DEPENDENT ticket must
196
- // not claim a dispatch key until the backend proves the run's shadow index
197
- // covers every declared predecessor's merge watermark. Dependency-free nodes
198
- // bypass the gate entirely so independent tickets keep their parallel behavior.
199
- // BAPI-845: the EXPLICIT non-epic bypass. A ticket that declares no
200
- // predecessors is not a member of an active epic/scope workflow, so it is
201
- // exempted here — before any scope-status lookup and before any ticket-status
202
- // mutation. Stating it rather than letting it fall out of a compound
203
- // condition is what makes "a scope problem never blocks a non-epic ticket" a
204
- // property this file asserts instead of one it happens to have: a stale,
205
- // blocked, or failed scope cannot reach an independent ticket's dispatch at
206
- // all, because the scope is never consulted for one.
207
- const declaredDeps = plan.tickets.find((t) => t.ticket_key === ticketKey)?.depends_on ?? [];
208
- const participatesInScopeWorkflow = declaredDeps.length > 0;
209
- if (participatesInScopeWorkflow && deps.checkShadowFreshness) {
210
- let decision;
211
- try {
212
- decision = normalizeShadowDecision(await deps.checkShadowFreshness(ticketKey));
213
- }
214
- catch (err) {
215
- // Fail closed: a freshness API error / malformed response never opens the
216
- // gate, and never parks either — an unread deadline is not an elapsed one.
217
- // Hold this tick without claiming a key or consuming any counter.
218
- decision = { verdict: "stale" };
219
- deps.log(`[epic-reconcile] shadow-freshness error for ${ticketKey}: ${safeDiagnosticMessage(err, "freshness error")}; holding`);
220
- }
221
- const { verdict } = decision;
222
- if (verdict === "stale" || verdict === "failed") {
223
- // BAPI-678: `stale` covers ordinary unproven freshness AND the backend's
224
- // warn-only downgrade of a `failed` shadow lifecycle; `failed` is the
225
- // terminal one the backend has already blocked the run for. Both hold.
226
- //
227
- // BAPI-845 bounds that hold. While the backend reports the typed
228
- // `shadow.stale_deadline_seconds` as unexpired the ticket simply waits —
229
- // it is never dispatched and never routed to the canonical index, so a
230
- // held ticket cannot quietly research against an index that does not
231
- // contain its predecessors' merges. A ticket already in `parsing` is left
232
- // exactly where it is; nothing on this path advances it.
233
- const blocked = decision.blockedAdvanceReason ?? null;
234
- const because = blocked ? ` (${blocked})` : "";
235
- if (decision.deadlineExpired !== true) {
236
- deps.log(`[epic-reconcile] holding ${ticketKey}: shadow watermark ${verdict}${because}`);
237
- continue;
238
- }
239
- reportShadowDeadlineExpired(deps, result, ticketKey, verdict, blocked);
240
- continue;
241
- }
242
- // "covered" | "not_applicable" fall through to the normal claim/dispatch.
243
- }
244
- let claimResult;
245
- try {
246
- claimResult = await deps.claimDispatchKey(observed.epic_key, ticketKey, observed.plan_version);
247
- }
248
- catch (err) {
249
- const safeMsg = err instanceof Error ? err.constructor.name : "claim error";
250
- result.warnings.push(`claim-error for ${ticketKey}: ${safeMsg}`);
251
- continue;
252
- }
253
- if (!claimResult.ok) {
254
- // lease-held: another tick is dispatching this ticket concurrently
255
- result.warnings.push(`dispatch-key lease-held for ${ticketKey}`);
256
- continue;
257
- }
258
- if (claimResult.kind === "terminal") {
259
- // Already dispatched and terminal — nothing to do
260
- continue;
261
- }
262
- if (claimResult.kind === "already-spawned") {
263
- // Spawn already occurred; ensure post-action wait is scheduled
264
- await deps.postActionWaitSeam(observed.epic_key, ticketKey);
265
- continue;
266
- }
267
- if (claimResult.kind === "already-exists") {
268
- if (claimResult.dispatch.run_id === null) {
269
- // Spawn happened on a prior tick but correlateRunId failed — the live run's
270
- // terminal signals can never be correlated back to this ticket. Escalate so
271
- // an operator can manually recover (set run_id or abandon the dispatch key).
272
- result.warnings.push(`dispatch-orphan: ${ticketKey} has pending dispatch key with no run_id`);
273
- await escalate(observed.epic_key, `dispatch-orphan:${ticketKey}`);
274
- }
275
- continue;
276
- }
277
- // kind === "claimed": proceed with spawn
278
- const dispatchKey = claimResult.dispatch.dispatch_key;
279
- let runId;
280
- try {
281
- runId = await deps.dispatchSeam(observed.epic_key, ticketKey);
282
- }
283
- catch (err) {
284
- const safeMsg = err instanceof Error ? err.constructor.name : "dispatch error";
285
- result.warnings.push(`dispatch-failed for ${ticketKey}: ${safeMsg}`);
286
- continue;
287
- }
288
- try {
289
- await deps.correlateRunId(dispatchKey, runId);
290
- result.dispatched += 1;
291
- deps.log(`[epic-reconcile] dispatched ${ticketKey} run_id=${runId}`);
292
- await deps.postActionWaitSeam(observed.epic_key, ticketKey);
293
- }
294
- catch (err) {
295
- const safeMsg = err instanceof Error ? err.constructor.name : "correlate error";
296
- result.warnings.push(`correlate-failed for ${ticketKey}: ${safeMsg}`);
297
- }
298
- }
299
- // Step 3.2: Reviewing recovery (BAPI-445 Phase 1 re-entry). computeReadySet
300
- // never surfaces a `reviewing` ticket (it is mid-flight, not ready), so a
301
- // ticket whose spec-review run died before completing would be stranded
302
- // forever without this pass. Iterate `reviewing` tickets explicitly (mirroring
303
- // how the remediation pass iterates `blocked` tickets): if the review run is
304
- // dead and the dedicated review-attempt cap is not yet exhausted, reclaim an
305
- // attempt-scoped `:review` dispatch key and re-dispatch the review; once the
306
- // cap is exhausted, escalate. This uses its OWN attempt counter — it never
307
- // touches the BAPI-441 remediation budget.
308
- if (supervisorConfig?.auto_rereview_enabled &&
309
- deps.dispatchReviewSeam &&
310
- deps.readReviewWorkerLiveness) {
311
- const dispatchReviewSeam = deps.dispatchReviewSeam;
312
- const readReviewWorkerLiveness = deps.readReviewWorkerLiveness;
313
- const maxReviewAttempts = supervisorConfig.max_spec_review_attempts ?? DEFAULT_MAX_SPEC_REVIEW_ATTEMPTS;
314
- for (const [ticketKey, status] of observed.ticket_statuses) {
315
- if (status !== "reviewing")
316
- continue;
317
- try {
318
- const liveness = await readReviewWorkerLiveness(observed.epic_key, ticketKey);
319
- if (liveness.alive)
320
- continue; // review still running — wait across ticks
321
- const priorAttempts = deps.countReviewAttempts
322
- ? deps.countReviewAttempts(ticketKey)
323
- : 0;
324
- if (priorAttempts >= maxReviewAttempts) {
325
- await escalate(observed.epic_key, `spec-review-liveness-exhausted:${ticketKey}`);
326
- deps.log(`[epic-reconcile] spec-review liveness exhausted for ${ticketKey} ` +
327
- `(attempts=${priorAttempts} max=${maxReviewAttempts}) → escalate`);
328
- continue;
329
- }
330
- // Reclaim a fresh attempt-scoped review dispatch key. `priorAttempts`
331
- // (>= 1 once the initial review dispatched) doubles as the next attempt
332
- // index, so the key differs from every prior review run's key.
333
- const attempt = priorAttempts;
334
- let claim;
335
- try {
336
- claim = await deps.claimDispatchKey(observed.epic_key, ticketKey, observed.plan_version, "review", attempt);
337
- }
338
- catch (err) {
339
- const safeMsg = err instanceof Error ? err.constructor.name : "claim error";
340
- result.warnings.push(`review-reclaim-error for ${ticketKey}: ${safeMsg}`);
341
- continue;
342
- }
343
- if (!claim.ok) {
344
- result.warnings.push(`review-dispatch-key lease-held for ${ticketKey}`);
345
- continue;
346
- }
347
- if (claim.kind !== "claimed") {
348
- if (claim.kind === "already-exists" && claim.dispatch.run_id === null) {
349
- result.warnings.push(`review-dispatch-orphan: ${ticketKey} has pending review dispatch key with no run_id`);
350
- await escalate(observed.epic_key, `dispatch-orphan:${ticketKey}`);
351
- }
352
- continue;
353
- }
354
- const dispatchKey = claim.dispatch.dispatch_key;
355
- let runId;
356
- try {
357
- runId = await dispatchReviewSeam(observed.epic_key, ticketKey, attempt);
358
- }
359
- catch (err) {
360
- const safeMsg = err instanceof Error ? err.constructor.name : "dispatch error";
361
- result.warnings.push(`review-redispatch-failed for ${ticketKey}: ${safeMsg}`);
362
- continue;
363
- }
364
- try {
365
- await deps.correlateRunId(dispatchKey, runId);
366
- deps.log(`[epic-reconcile] re-dispatched spec re-review for ${ticketKey} ` +
367
- `run_id=${runId} attempt=${attempt}`);
368
- }
369
- catch (err) {
370
- const safeMsg = err instanceof Error ? err.constructor.name : "correlate error";
371
- result.warnings.push(`review-correlate-failed for ${ticketKey}: ${safeMsg}`);
372
- }
373
- }
374
- catch (err) {
375
- const safeMsg = err instanceof Error ? err.constructor.name : "reviewing recovery error";
376
- result.warnings.push(`reviewing-recovery-error for ${ticketKey}: ${safeMsg}`);
377
- }
378
- }
379
- }
380
- // Step 3.4: Spec-review verdict gate (BAPI-445 Phase 2). A ticket blocked by a
381
- // changes-requested SPEC review is a spec problem, not a code bug: escalate it
382
- //
383
- // NOTE: this block is reachable only once the verdict EMISSION primitive
384
- // (`emitSpecReviewVerdict` in spec-review-producer.ts) is wired into the
385
- // review-ticket completion flow so a `spec_review.changes_requested` event is
386
- // folded to `blocked` with this reason. Until that Phase 2 integration lands,
387
- // no ticket carries the `spec_review.changes_requested` blocked reason and this
388
- // pass is a no-op. That is FAIL-SAFE: a completed review with no verdict does
389
- // NOT advance `reviewing → ready` (epic-state filters review-run incidental
390
- // terminals), so implementation never proceeds without an explicit pass —
391
- // a stranded `reviewing` ticket is escalated by the recovery branch above.
392
- // once for operator attention and EXCLUDE it from the BAPI-441 remediation pass
393
- // below so it never spends the implementation remediation budget (no nudge, no
394
- // redispatch, no budget counter increment). Runs independently of the
395
- // remediation seams so a spec rejection is always surfaced.
396
- const specRejectedTickets = new Set();
397
- for (const [ticketKey, status] of observed.ticket_statuses) {
398
- if (status !== "blocked")
399
- continue;
400
- if (observed.ticket_blocked_reasons?.get(ticketKey) !== "spec_review.changes_requested") {
401
- continue;
402
- }
403
- specRejectedTickets.add(ticketKey);
404
- await escalate(observed.epic_key, `spec-review-rejected:${ticketKey}`);
405
- deps.log(`[epic-reconcile] spec-review changes-requested for ${ticketKey} → escalate ` +
406
- `(remediation budget bypassed)`);
407
- }
408
- // Step 3.5: Remediation pass (BAPI-441) — re-act on blocked tickets under
409
- // budget. Keyed off the folded "blocked" status + per-ticket counters, NOT a
410
- // computeReadySet change (the ready-set still returns only planned tickets).
411
- // Skipped entirely unless the remediation seams + supervisorConfig are wired.
412
- const remediationWired = supervisorConfig !== undefined &&
413
- deps.readWorkerLiveness !== undefined &&
414
- deps.remediateCas !== undefined &&
415
- deps.sendNudge !== undefined &&
416
- deps.resumeDispatch !== undefined;
417
- if (remediationWired) {
418
- const cfg = supervisorConfig;
419
- const readWorkerLiveness = deps.readWorkerLiveness;
420
- const sendNudge = deps.sendNudge;
421
- const resumeDispatch = deps.resumeDispatch;
422
- const remediateCas = deps.remediateCas;
423
- for (const [ticketKey, status] of observed.ticket_statuses) {
424
- if (status !== "blocked")
425
- continue;
426
- // BAPI-445: a spec-review rejection was already escalated in Step 3.4 and
427
- // must never enter the implementation remediation budget. Skip it here.
428
- if (specRejectedTickets.has(ticketKey))
429
- continue;
430
- // Per-ticket try/catch so a single ticket's failure never aborts the pass.
431
- try {
432
- const counters = observed.ticket_remediation_counters?.get(ticketKey) ?? {
433
- attempts: 0,
434
- no_progress: 0,
435
- };
436
- const liveness = await readWorkerLiveness(observed.epic_key, ticketKey);
437
- const decision = decideRemediation(counters.attempts, counters.no_progress, liveness.alive, cfg);
438
- if (decision === "escalate") {
439
- await escalate(observed.epic_key, `remediation-budget-exhausted:${ticketKey}`);
440
- deps.log(`[epic-reconcile] remediation escalate ${ticketKey} ` +
441
- `(attempts=${counters.attempts} no_progress=${counters.no_progress})`);
442
- continue;
443
- }
444
- // The attempt being recorded is the next one (1-based).
445
- const attempt = counters.attempts + 1;
446
- // The folding reason frames the nudge (message type + digest). Default to
447
- // the review path when the ledger no longer carries the blocking event.
448
- // spec_review.changes_requested is impossible here (skipped above) but
449
- // narrow explicitly so the remediation seams keep their tight reason type.
450
- // BAPI-494: `merge.conflict` is normalized as a first-class reason.
451
- const blockedReason = observed.ticket_blocked_reasons?.get(ticketKey);
452
- const normalizedReason = blockedReason === "ci.failed"
453
- ? "ci.failed"
454
- : blockedReason === "merge.conflict"
455
- ? "merge.conflict"
456
- : "review.changes_requested";
457
- // BAPI-494: a conflict ALWAYS redispatches a resume-mode worker (it needs a
458
- // working tree to rebase + resolve, not a message), regardless of whether the
459
- // original worker is still alive — so the alive-worker nudge is forced to a
460
- // redispatch here. Budget-exhaustion escalation already fired above, so at this
461
- // point the budget is not exhausted. CI/review keep their liveness-driven
462
- // nudge-vs-redispatch decision unchanged.
463
- const attemptKind = normalizedReason === "merge.conflict" ? "redispatch" : decision;
464
- // A nudge needs a worker to address it to. The liveness scan already
465
- // resolved the worker id from the same heartbeat that proved the worker
466
- // alive; if it is missing we cannot relay, so skip BEFORE recording an
467
- // attempt — otherwise the CAS would burn a budget unit with nothing sent.
468
- // A redispatch (including every conflict) needs no worker id, so it is exempt.
469
- if (attemptKind === "nudge" && !liveness.workerId) {
470
- result.warnings.push(`remediation nudge skipped for ${ticketKey}: alive worker has no worker_id`);
471
- continue;
472
- }
473
- // Record the attempt durably FIRST. The remediate endpoint builds the
474
- // (backend-redacted) review digest for a nudge and returns it, and is
475
- // idempotent (a 409 replay returns conflict, not throw). An unexpected
476
- // remediate failure is absorbed as a per-ticket warning so the rest of
477
- // the pass still runs (crash-replay safe).
478
- let casOutcome;
479
- try {
480
- casOutcome = await remediateCas(observed.epic_key, ticketKey, attemptKind, normalizedReason);
481
- }
482
- catch (err) {
483
- const safeMsg = safeDiagnosticMessage(err, "remediate error");
484
- result.warnings.push(`remediate-cas-failed for ${ticketKey} (${attemptKind}): ${safeMsg}`);
485
- continue;
486
- }
487
- if (casOutcome.conflict) {
488
- // Idempotency replay: the attempt was already recorded (and acted on)
489
- // on a prior tick. Do not re-act — the crash-replay self-heals here.
490
- result.warnings.push(`remediation replay swallowed for ${ticketKey} (${attemptKind})`);
491
- continue;
492
- }
493
- if (attemptKind === "nudge") {
494
- // Nudge is CI/review only (conflict never nudges), so narrow the reason.
495
- const nudgeReason = normalizedReason === "ci.failed" ? "ci.failed" : "review.changes_requested";
496
- await sendNudge(observed.epic_key, ticketKey, attempt, casOutcome.reviewDigest, casOutcome.truncated, nudgeReason, liveness.workerId);
497
- }
498
- else {
499
- await resumeDispatch(observed.epic_key, ticketKey, attempt);
500
- }
501
- deps.log(`[epic-reconcile] remediation ${attemptKind} ${ticketKey} attempt=${attempt} reason=${normalizedReason}`);
502
- }
503
- catch (err) {
504
- const safeMsg = safeDiagnosticMessage(err, "remediation error");
505
- result.warnings.push(`remediation-error for ${ticketKey}: ${safeMsg}`);
506
- }
507
- }
508
- }
509
- // Step 4: Action approved merges via C6 delegation
510
- for (const event of observed.pending_merge_events) {
511
- const identity = extractMergeActionIdentityFromGateEvent(event);
512
- if (!identity)
513
- continue;
514
- try {
515
- const mergeResult = await deps.processMerge(access, event);
516
- if (mergeResult.processed) {
517
- result.merges_actioned += 1;
518
- }
519
- }
520
- catch (err) {
521
- const safeMsg = err instanceof Error ? err.constructor.name : "merge error";
522
- result.warnings.push(`merge-failed ${identity.action_key}: ${safeMsg}`);
523
- }
524
- }
525
- // Step 5: Post-action waits are scheduled inline above per-dispatch
526
- return result;
527
- }
528
- // ---------------------------------------------------------------------------
529
- // enterSpecReview (BAPI-445 Phase 1 — planned → reviewing + spawn review run)
530
- // ---------------------------------------------------------------------------
531
- /**
532
- * Advance a `planned` ready ticket into the pre-implementation spec re-review:
533
- * CAS planned → reviewing, claim the `:review` dispatch key, spawn the review
534
- * run, and correlate its run_id. Every failure is absorbed as a per-ticket
535
- * warning so the rest of the reconcile pass still runs.
536
- *
537
- * Deliberately does NOT mutate the local `observed.ticket_statuses` map: the CAS
538
- * is durable in Postgres (the NEXT tick's snapshot shows `reviewing`), and
539
- * leaving the local status as `planned` keeps the same-tick reviewing-recovery
540
- * pass from mistaking this freshly-spawned review for a stranded one and
541
- * double-dispatching it.
542
- */
543
- async function enterSpecReview(observed, deps, result, escalate, ticketKey) {
544
- const dispatchReviewSeam = deps.dispatchReviewSeam;
545
- if (!dispatchReviewSeam)
546
- return; // caller-guarded; defensive
547
- // CAS planned → reviewing (durable). Idempotency: if another tick already
548
- // advanced the ticket, the CAS conflicts and we bail benignly.
549
- const rowVersion = observed.ticket_row_versions.get(ticketKey) ?? 0;
550
- let cas;
551
- try {
552
- cas = await deps.casTicketStatus(observed.epic_key, ticketKey, rowVersion, "reviewing", observed.plan_version);
553
- }
554
- catch (err) {
555
- const safeMsg = err instanceof Error ? err.constructor.name : "cas error";
556
- result.warnings.push(`review-cas-error for ${ticketKey}: ${safeMsg}`);
557
- return;
558
- }
559
- if (!cas.ok) {
560
- result.warnings.push(`review-cas-conflict advancing ${ticketKey} → reviewing`);
561
- return;
562
- }
563
- // Claim the :review dispatch key (attempt 0), then spawn + correlate.
564
- let claim;
565
- try {
566
- claim = await deps.claimDispatchKey(observed.epic_key, ticketKey, observed.plan_version, "review", 0);
567
- }
568
- catch (err) {
569
- const safeMsg = err instanceof Error ? err.constructor.name : "claim error";
570
- result.warnings.push(`review-claim-error for ${ticketKey}: ${safeMsg}`);
571
- return;
572
- }
573
- if (!claim.ok) {
574
- result.warnings.push(`review-dispatch-key lease-held for ${ticketKey}`);
575
- return;
576
- }
577
- if (claim.kind !== "claimed") {
578
- if (claim.kind === "already-exists" && claim.dispatch.run_id === null) {
579
- result.warnings.push(`review-dispatch-orphan: ${ticketKey} has pending review dispatch key with no run_id`);
580
- await escalate(observed.epic_key, `dispatch-orphan:${ticketKey}`);
581
- }
582
- return;
583
- }
584
- const dispatchKey = claim.dispatch.dispatch_key;
585
- let runId;
586
- try {
587
- runId = await dispatchReviewSeam(observed.epic_key, ticketKey, 0);
588
- }
589
- catch (err) {
590
- const safeMsg = err instanceof Error ? err.constructor.name : "dispatch error";
591
- result.warnings.push(`review-dispatch-failed for ${ticketKey}: ${safeMsg}`);
592
- return;
593
- }
594
- try {
595
- await deps.correlateRunId(dispatchKey, runId);
596
- deps.log(`[epic-reconcile] dispatched spec re-review for ${ticketKey} ` +
597
- `run_id=${runId} (planned → reviewing; implementation deferred)`);
598
- }
599
- catch (err) {
600
- const safeMsg = err instanceof Error ? err.constructor.name : "correlate error";
601
- result.warnings.push(`review-correlate-failed for ${ticketKey}: ${safeMsg}`);
602
- }
603
- }