@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.
- package/README.md +14 -7
- package/build/agent-launchers/prompt.js +9 -21
- package/build/agents.generated.js +6 -6
- package/build/authored-plan.js +542 -0
- package/build/bridge-permissions.js +8 -0
- package/build/codex-auto-recovery.js +25 -7
- package/build/commands.generated.js +7 -7
- package/build/conductor/bridge-api-client.js +807 -52
- package/build/conductor/declare-blocked.js +4 -0
- package/build/conductor/driver-pass.js +8 -0
- package/build/conductor/epic-implementer-cli.js +341 -96
- package/build/conductor/epic-server-journal.js +13 -0
- package/build/conductor/epic-server-recipe.js +15 -5
- package/build/conductor/epic-server-runtime.js +163 -45
- package/build/conductor/epic-server.js +13 -6
- package/build/conductor/gate-discovery.js +209 -9
- package/build/conductor/gate-settings-review.js +7 -11
- package/build/conductor/install-doctor.js +30 -2
- package/build/conductor/launch-plan.js +58 -12
- package/build/conductor/local-merge.js +54 -12
- package/build/conductor/open-decision-phrases.js +50 -0
- package/build/conductor/pr-ci-producer.js +12 -3
- package/build/conductor/prerequisite-inputs.js +181 -14
- package/build/conductor/readiness-sections.js +46 -13
- package/build/conductor/readiness.js +3 -40
- package/build/conductor/recovery-cli.js +12 -12
- package/build/conductor/repository-workflow-remedy.js +147 -7
- package/build/conductor/ui-readiness.js +224 -0
- package/build/conductor/wait-run-attention.js +9 -4
- package/build/conductor/wait-run-cli.js +9 -2
- package/build/connect-github-api.js +18 -0
- package/build/connect-github.js +35 -18
- package/build/docs.generated.js +3 -3
- package/build/drive-epic.js +787 -37
- package/build/epic-ci-workflow.js +3 -2
- package/build/epic-implementer-bin.js +200 -66
- package/build/epic-implementer-bundle-cli.js +61 -0
- package/build/epic-implementer-claude-hook-bin.js +1 -1
- package/build/epic-implementer-env.js +3 -4
- package/build/epic-integration-pr.js +5 -2
- package/build/epic-launch-context.js +8 -1
- package/build/epic-shared/cut-protocol.js +55 -3
- package/build/executor/completion-contract.js +24 -1
- package/build/executor/failure-reason-codes.js +2 -0
- package/build/executor/gate-qualification-job.js +193 -23
- package/build/executor/gate-qualification-tests-ran.js +232 -0
- package/build/executor/integration-job.js +56 -2
- package/build/executor/job-runner.js +13 -723
- package/build/executor/job-type-wrappers.js +734 -0
- package/build/executor/merge-job.js +45 -1
- package/build/executor/permissions.js +187 -2
- package/build/executor/preflight.js +6 -2
- package/build/executor/process-containment.js +8 -1
- package/build/executor/provider-checks.js +28 -5
- package/build/executor/reconcile-overlap-job.js +70 -17
- package/build/executor/required-verification.js +28 -2
- package/build/executor/required-work-ledger.js +7 -2
- package/build/executor/resume-pre-spawn.js +32 -8
- package/build/executor/runner.js +30 -5
- package/build/executor/types.js +9 -0
- package/build/executor/worker-database.js +6 -1
- package/build/executor/worker-guard-hook.js +24 -2
- package/build/executor/worktree.js +12 -1
- package/build/generated/ticket-status.js +20 -0
- package/build/index.js +627 -551
- package/build/init.js +16 -0
- package/build/install-bridge-conductor-answers.js +32 -1
- package/build/install-bridge-conductor-apply.js +21 -3
- package/build/install-bridge-conductor-assessment.js +185 -12
- package/build/install-bridge-conductor-compact.js +2 -0
- package/build/install-bridge-conductor-contracts.js +9 -1
- package/build/install-bridge-conductor-gate.js +257 -80
- package/build/install-bridge-conductor-setup.js +106 -6
- package/build/install-bridge-conductor-trial-report.js +170 -0
- package/build/install-bridge-conductor.js +740 -124
- package/build/mcp-host-config.js +54 -37
- package/build/phase-context-git-probe.js +16 -0
- package/build/pipelines.generated.js +15 -15
- package/build/plan-execution-ledger.js +27 -0
- package/build/plan-generation.js +17 -0
- package/build/plane/plane-freshness.js +43 -26
- package/build/printed-remedy-commands.js +62 -0
- package/build/readme.generated.js +1 -1
- package/build/repository-toolchains.js +11 -5
- package/build/scripts/saved-commands-config-field-driver.js +65 -0
- package/build/secret-redaction.js +3 -0
- package/build/setup-epic.js +51 -9
- package/build/test-support/create-preview-world.js +232 -0
- package/build/test-support/executor-source-files.js +1 -1
- package/build/ticket-delivery.js +65 -0
- package/build/v2-readiness-requirements.js +13 -4
- package/build/version.generated.js +3 -3
- package/build/worker-guard-hook-bin.js +2 -2
- package/build/worktree-core.js +51 -7
- package/docs/EPIC-IMPLEMENTER.md +83 -4
- package/docs/epic-implementer/getting-started.md +1 -1
- package/docs/install/github-app.md +79 -92
- package/package.json +1 -1
- package/pipelines/implement-ticket.json +2 -2
- package/build/conductor/epic-reconcile.js +0 -603
- package/build/conductor/epic-runtime.js +0 -2020
- package/build/conductor/epic-state.js +0 -774
|
@@ -1,2020 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Epic Supervisor stateless reconciliation tick (BAPI-408).
|
|
3
|
-
*
|
|
4
|
-
* `epic-implementer epic-tick --epic-key <key>` runs one stateless pass:
|
|
5
|
-
* 1. Claim the epic supervision lease (single-writer guard)
|
|
6
|
-
* 2. Drift check (log if fired materially late)
|
|
7
|
-
* 3. Rebuild observed state from Postgres + local ledger
|
|
8
|
-
* 4. Assert plan integrity (fail-closed on hash mismatch)
|
|
9
|
-
* 5. Reconcile observed→desired (deterministic, no LLM on ordering)
|
|
10
|
-
* 6. Budget / dead-state check
|
|
11
|
-
* 7. Persist, release lease, exit
|
|
12
|
-
*
|
|
13
|
-
* Crash/sleep is the expected path: every mutation is an idempotent CAS/lease
|
|
14
|
-
* op so the next wakeup re-derives and continues.
|
|
15
|
-
*
|
|
16
|
-
* This module opens NO Postgres connection and holds NO VCS write credentials.
|
|
17
|
-
* All durable mutations go through the injectable seams that call the sibling
|
|
18
|
-
* Epic Run TS client (already available in bridge-api-client.ts as of BAPI-407).
|
|
19
|
-
*/
|
|
20
|
-
import { spawnSync } from "child_process";
|
|
21
|
-
import { resolveConductorBridgeApiAccess, claimEpicSupervisionLease, fetchEpicRunState, advanceEpicTicketStatus, createEpicTicketStatus, updateEpicRunStatus, recordEpicDispatch, transitionEpicDispatch, fetchParseStatus, triggerRepositoryParse, getEpicPlan, buildEpicDispatchKey, fetchEffectiveSupervisorConfig, fetchEffectiveSupervisorSetup, remediateEpicTicket, deletePullRequestBranch, transitionJiraStatus, reconcileShadowMerge, fetchShadowDispatchFreshness, safeDiagnosticMessage, } from "./bridge-api-client.js";
|
|
22
|
-
import { processGateMetMerge } from "./supervisor-merge.js";
|
|
23
|
-
import { observePrCiOnce } from "./pr-ci-producer.js";
|
|
24
|
-
import { runGhCommand } from "./pr-discovery.js";
|
|
25
|
-
import { isPrMergeConflict, parseGhPrMergeabilityFields, } from "./github-mergeability.js";
|
|
26
|
-
import { makeLocalMergeExecutor, resolveLocalMergeCredential, resolveLocalMergeMethod, } from "./local-merge.js";
|
|
27
|
-
import { getHeadSha, getPrNumber } from "./event-accessors.js";
|
|
28
|
-
import { emitConductorEventIfNew } from "./producer-ledger.js";
|
|
29
|
-
import { rebuildObservedState, extractWorkerLiveness, } from "./epic-state.js";
|
|
30
|
-
import { reconcileEpic, } from "./epic-reconcile.js";
|
|
31
|
-
import { normalizeDeclaredTouchedFiles } from "./file-scope-guard.js";
|
|
32
|
-
import { buildSupervisorRemediationWorkerMessage } from "./supervisor-message-relay.js";
|
|
33
|
-
import { sendWorkerMessage } from "./store.js";
|
|
34
|
-
import { hashPlan } from "./plan.js";
|
|
35
|
-
import { pollConductorEvents, POLL_LIMIT_MAX } from "./store.js";
|
|
36
|
-
import { dispatchSupervisorNotification } from "./supervisor-notification.js";
|
|
37
|
-
import { makeSupervisorIdempotencyKey } from "./supervisor-ledger.js";
|
|
38
|
-
import { createDefaultStartTicketsDeps, orchestrateStartTickets } from "../start-tickets.js";
|
|
39
|
-
import { orchestrateReviewTickets } from "../review-tickets.js";
|
|
40
|
-
import { createStartTicketsConductorContext, provisionConductorHooksForRows, emitStartTicketsRunStarted, } from "../start-tickets-conductor.js";
|
|
41
|
-
import { validateBranchName } from "../base-ref.js";
|
|
42
|
-
import { resolveDeclaredRunBaseBranch } from "./run-branch.js";
|
|
43
|
-
// ---------------------------------------------------------------------------
|
|
44
|
-
// Constants
|
|
45
|
-
// ---------------------------------------------------------------------------
|
|
46
|
-
const DEFAULT_LEASE_TTL_SECONDS = 120;
|
|
47
|
-
const DEFAULT_MAX_DRIFT_MS = 30_000;
|
|
48
|
-
const DEFAULT_DISPATCH_KEY_TTL_SECONDS = 300; // independent of supervision lease TTL
|
|
49
|
-
const ACTIVE_WORKER_STATUSES = new Set(["dispatched", "running"]);
|
|
50
|
-
// ---------------------------------------------------------------------------
|
|
51
|
-
// Module-private helpers
|
|
52
|
-
// ---------------------------------------------------------------------------
|
|
53
|
-
/**
|
|
54
|
-
* Source + producer tags for the durable `parse.triggered` marker that the
|
|
55
|
-
* parse-after-merge wait emits from the epic-tick process.
|
|
56
|
-
*/
|
|
57
|
-
const PARSE_WAIT_EVENT_SOURCE = "epic-implementer-supervisor";
|
|
58
|
-
const PARSE_WAIT_EVENT_PRODUCER = "epic-parse-wait";
|
|
59
|
-
/**
|
|
60
|
-
* BAPI-494: source + producer tags for the durable `merge.conflict` marker the
|
|
61
|
-
* done-gate pass emits when a `ready_for_review` ticket's PR is un-mergeable.
|
|
62
|
-
*/
|
|
63
|
-
const MERGE_CONFLICT_EVENT_SOURCE = "epic-implementer-supervisor";
|
|
64
|
-
const MERGE_CONFLICT_EVENT_PRODUCER = "epic-mergeability";
|
|
65
|
-
function defaultLeaseOwner() {
|
|
66
|
-
return `epic-tick-${process.pid}`;
|
|
67
|
-
}
|
|
68
|
-
async function defaultEscalateOnce(epicKey, reason) {
|
|
69
|
-
process.stderr.write(`[epic-tick] ESCALATION epic=${epicKey} reason=${reason}\n`);
|
|
70
|
-
}
|
|
71
|
-
async function defaultDispatchSeam(_epicKey, ticketKey, _attempt = 0) {
|
|
72
|
-
throw new Error(`dispatch seam not wired for ticket ${ticketKey}`);
|
|
73
|
-
}
|
|
74
|
-
async function defaultPostActionWaitSeam(_epicKey, _ticketKey) {
|
|
75
|
-
// no-op: parse-after-merge wait is a sibling ticket's concern
|
|
76
|
-
}
|
|
77
|
-
export function parsePrBindingFromGhJson(stdout) {
|
|
78
|
-
let pr;
|
|
79
|
-
try {
|
|
80
|
-
pr = JSON.parse(stdout);
|
|
81
|
-
}
|
|
82
|
-
catch {
|
|
83
|
-
return null;
|
|
84
|
-
}
|
|
85
|
-
const num = pr.number;
|
|
86
|
-
const sha = pr.headRefOid;
|
|
87
|
-
const state = typeof pr.state === "string" ? pr.state : "";
|
|
88
|
-
if (typeof num === "number" &&
|
|
89
|
-
Number.isInteger(num) &&
|
|
90
|
-
num >= 1 &&
|
|
91
|
-
typeof sha === "string" &&
|
|
92
|
-
/^[0-9a-f]{7,40}$/i.test(sha) &&
|
|
93
|
-
state.toUpperCase() === "OPEN") {
|
|
94
|
-
// BAPI-494: parse mergeability defensively from the same JSON object — unknown
|
|
95
|
-
// values become null and never reject an otherwise valid open PR binding.
|
|
96
|
-
const mergeability = parseGhPrMergeabilityFields(pr);
|
|
97
|
-
const rawBase = pr.baseRefName;
|
|
98
|
-
const baseRef = typeof rawBase === "string" && rawBase.trim().length > 0 ? rawBase.trim() : undefined;
|
|
99
|
-
return {
|
|
100
|
-
prNumber: num,
|
|
101
|
-
headSha: sha,
|
|
102
|
-
mergeable: mergeability.mergeable,
|
|
103
|
-
mergeStateStatus: mergeability.mergeStateStatus,
|
|
104
|
-
...(baseRef !== undefined ? { baseRef } : {}),
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
return null;
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Shared gh-discovery PR-binding resolver: resolve BOTH the PR number and the
|
|
111
|
-
* CURRENT head SHA for a ticket from its `feature/<KEY>` branch via
|
|
112
|
-
* `gh pr view ... --json number,headRefOid,state`. This is the single
|
|
113
|
-
* gh-discovery path used by BOTH the Conductor done-gate pass and the
|
|
114
|
-
* remediation CAS dispatch (BAPI-487 Requirement 1). It intentionally does NOT
|
|
115
|
-
* consult `epic_supervisor_setup.pr_bindings` — nothing auto-populates that map,
|
|
116
|
-
* so the legacy `pr_bindings` seam always returned null and stranded remediation.
|
|
117
|
-
*
|
|
118
|
-
* Fail-closed: returns null for any failed `gh` invocation, empty stdout, or a
|
|
119
|
-
* closed/merged PR / malformed number / non-hex head SHA (all enforced by
|
|
120
|
-
* {@link parsePrBindingFromGhJson}). `options.runGh` is injectable for pure unit
|
|
121
|
-
* tests; `options.cwd` defaults to the Conductor's current working directory.
|
|
122
|
-
*/
|
|
123
|
-
export function resolveTicketPrBindingFromGh(ticketKey, options = {}) {
|
|
124
|
-
const runGh = options.runGh ?? runGhCommand;
|
|
125
|
-
const ghRes = runGh(
|
|
126
|
-
// BAPI-494: mergeability fields added to the SAME per-ticket binding call — the
|
|
127
|
-
// done-gate reads mergeability inside this existing call, spawning no new gh process.
|
|
128
|
-
// BAPI-586: baseRefName added to the SAME call so the done-gate can detect a wrong-base PR.
|
|
129
|
-
["pr", "view", `feature/${ticketKey}`, "--json", "number,headRefOid,state,mergeable,mergeStateStatus,baseRefName"], { cwd: options.cwd ?? process.cwd() });
|
|
130
|
-
if (ghRes.ok && ghRes.stdout.trim()) {
|
|
131
|
-
const parsed = parsePrBindingFromGhJson(ghRes.stdout);
|
|
132
|
-
// Normalize the head SHA to lowercase so downstream head-scoped comparisons
|
|
133
|
-
// (blocked-head vs. current-head, gate.met dedupe) are case-stable.
|
|
134
|
-
return parsed
|
|
135
|
-
? { ...parsed, headSha: parsed.headSha.toLowerCase() }
|
|
136
|
-
: null;
|
|
137
|
-
}
|
|
138
|
-
return null;
|
|
139
|
-
}
|
|
140
|
-
// ---------------------------------------------------------------------------
|
|
141
|
-
// Dispatched/running done-gate backstop (BAPI-525 Change B)
|
|
142
|
-
// ---------------------------------------------------------------------------
|
|
143
|
-
/** Conservative default quiescence window (ticks) for the dispatched backstop. */
|
|
144
|
-
const DEFAULT_DISPATCHED_BACKSTOP_QUIESCENCE_TICKS = 3;
|
|
145
|
-
/** The conservative default (disabled) dispatched-backstop policy. */
|
|
146
|
-
export const DEFAULT_DISPATCHED_BACKSTOP_POLICY = {
|
|
147
|
-
enabled: false,
|
|
148
|
-
quiescence_ticks: DEFAULT_DISPATCHED_BACKSTOP_QUIESCENCE_TICKS,
|
|
149
|
-
quiescence_ms: null,
|
|
150
|
-
};
|
|
151
|
-
/** Accept only a positive integer; every other shape (0, negative, float, string, NaN) → null. */
|
|
152
|
-
function parsePositiveInt(value) {
|
|
153
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* Resolve the dispatched-backstop policy from an epic run's `policy_json`.
|
|
157
|
-
* Fail-closed to {@link DEFAULT_DISPATCHED_BACKSTOP_POLICY} on any missing/malformed
|
|
158
|
-
* shape. Only a literal boolean `true` enables the path; `quiescence_ticks` /
|
|
159
|
-
* `quiescence_ms` accept only positive integers and otherwise fall back to the
|
|
160
|
-
* conservative default (ticks) / `null` (ms). Mirrors the defensive style used for
|
|
161
|
-
* `policy_json.post_action_waits.parse_after_merge`.
|
|
162
|
-
*/
|
|
163
|
-
export function resolveDispatchedBackstopPolicy(policyJson) {
|
|
164
|
-
const doneGate = policyJson && typeof policyJson === "object" && !Array.isArray(policyJson)
|
|
165
|
-
? policyJson.done_gate
|
|
166
|
-
: undefined;
|
|
167
|
-
const cfg = doneGate && typeof doneGate === "object" && !Array.isArray(doneGate)
|
|
168
|
-
? doneGate.dispatched_backstop
|
|
169
|
-
: undefined;
|
|
170
|
-
if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) {
|
|
171
|
-
return { ...DEFAULT_DISPATCHED_BACKSTOP_POLICY };
|
|
172
|
-
}
|
|
173
|
-
const record = cfg;
|
|
174
|
-
return {
|
|
175
|
-
enabled: record.enabled === true,
|
|
176
|
-
quiescence_ticks: parsePositiveInt(record.quiescence_ticks) ?? DEFAULT_DISPATCHED_BACKSTOP_QUIESCENCE_TICKS,
|
|
177
|
-
quiescence_ms: parsePositiveInt(record.quiescence_ms),
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
/** Reuse the single active-worker status set as the backstop admission set. */
|
|
181
|
-
export function isActiveWorkerStatus(status) {
|
|
182
|
-
return ACTIVE_WORKER_STATUSES.has(status);
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* The base done-gate statuses (`ready_for_review`/`blocked`) whose behavior is
|
|
186
|
-
* unchanged by BAPI-525 — no quiescence gate is applied to them.
|
|
187
|
-
*/
|
|
188
|
-
export function isBaseDoneGateStatus(status) {
|
|
189
|
-
return status === "ready_for_review" || status === "blocked";
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Head-changing event families used to compute stable-head quiescence. `getHeadSha`
|
|
193
|
-
* reads the canonical `data.details.head_sha` regardless of the typed details
|
|
194
|
-
* family, so `git.commit_created` (details-less in the accessor map) still yields a
|
|
195
|
-
* head when the raw envelope carries one.
|
|
196
|
-
*/
|
|
197
|
-
const HEAD_CHANGING_EVENT_TYPES = new Set([
|
|
198
|
-
"git.pr_opened",
|
|
199
|
-
"git.commit_created",
|
|
200
|
-
"ci.passed",
|
|
201
|
-
"review.passed",
|
|
202
|
-
"gate.met",
|
|
203
|
-
]);
|
|
204
|
-
/**
|
|
205
|
-
* Build a local-first PR binding resolver for the dispatched backstop (BAPI-525
|
|
206
|
-
* Change B, Requirement 5). Resolution order per ticket:
|
|
207
|
-
* 1. dispatch/run-state PR binding — SKIPPED: `EpicDispatch`/`EpicTicketStatus`
|
|
208
|
-
* carry no PR number/head SHA and `pr_bindings` is a legacy always-null seam,
|
|
209
|
-
* so there is no durable PR binding on run state to consult (documented here so
|
|
210
|
-
* a future state-model addition knows to wire it in first).
|
|
211
|
-
* 2. the newest local ledger event (by `seq`) carrying BOTH a valid `pr_number`
|
|
212
|
-
* and `head_sha` (e.g. a `gate.met`), read through the typed `getPrNumber` /
|
|
213
|
-
* `getHeadSha` accessors and normalized fail-closed.
|
|
214
|
-
* 3. a `gh pr view feature/<KEY>` lookup, with NEGATIVE results cached per tick so
|
|
215
|
-
* a ticket with no open PR is never polled twice in the same tick.
|
|
216
|
-
* A local binding carries `mergeable`/`mergeStateStatus: null` (unknown without the
|
|
217
|
-
* gh call); a conflict check treats `null` as non-conflicting.
|
|
218
|
-
*/
|
|
219
|
-
export function buildTicketPrBindingResolver(deps) {
|
|
220
|
-
// Precompute ticket_key -> newest local (pr_number, head_sha) binding.
|
|
221
|
-
const localByTicket = new Map();
|
|
222
|
-
for (const ev of deps.events) {
|
|
223
|
-
const prNumber = getPrNumber(ev);
|
|
224
|
-
const headSha = getHeadSha(ev);
|
|
225
|
-
if (prNumber === null || headSha === null)
|
|
226
|
-
continue;
|
|
227
|
-
let ticketKey = null;
|
|
228
|
-
if (typeof ev.run_id === "string" && deps.resolveTicketForRunId) {
|
|
229
|
-
ticketKey = deps.resolveTicketForRunId(ev.run_id);
|
|
230
|
-
}
|
|
231
|
-
if (!ticketKey && typeof ev.subject === "string" && ev.subject.trim().length > 0) {
|
|
232
|
-
ticketKey = ev.subject;
|
|
233
|
-
}
|
|
234
|
-
if (!ticketKey)
|
|
235
|
-
continue;
|
|
236
|
-
const prev = localByTicket.get(ticketKey);
|
|
237
|
-
if (!prev || ev.seq >= prev.seq) {
|
|
238
|
-
localByTicket.set(ticketKey, {
|
|
239
|
-
seq: ev.seq,
|
|
240
|
-
binding: {
|
|
241
|
-
prNumber,
|
|
242
|
-
headSha: headSha.toLowerCase(),
|
|
243
|
-
mergeable: null,
|
|
244
|
-
mergeStateStatus: null,
|
|
245
|
-
},
|
|
246
|
-
});
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
// Per-tick gh cache: memoize BOTH hits and misses so a missing PR is looked up at
|
|
250
|
-
// most once per ticket per tick (Requirement 5 — no gh/CI thrash on dispatched).
|
|
251
|
-
const ghCache = new Map();
|
|
252
|
-
return (ticketKey) => {
|
|
253
|
-
const local = localByTicket.get(ticketKey);
|
|
254
|
-
if (local)
|
|
255
|
-
return local.binding;
|
|
256
|
-
if (ghCache.has(ticketKey))
|
|
257
|
-
return ghCache.get(ticketKey) ?? null;
|
|
258
|
-
const gh = deps.resolveFromGh(ticketKey);
|
|
259
|
-
ghCache.set(ticketKey, gh);
|
|
260
|
-
return gh;
|
|
261
|
-
};
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* Build the active-ticket quiescence resolver (BAPI-525 Change B, Requirement 6).
|
|
265
|
-
* A `dispatched`/`running` ticket is folded toward `ready_for_review` ONLY when its
|
|
266
|
-
* PR-bound completion evidence (resolved by the caller) is accompanied by a
|
|
267
|
-
* quiescence signal — NEVER on green-PR evidence alone, because workers are
|
|
268
|
-
* interactive and may still be pushing follow-up commits:
|
|
269
|
-
*
|
|
270
|
-
* - an explicit implementation `run.stopped` for the ticket's impl run, OR
|
|
271
|
-
* - a head SHA that MATCHES the candidate PR head AND has been stable for at least
|
|
272
|
-
* `policy.quiescence_ms` since the latest head-changing ledger event.
|
|
273
|
-
*
|
|
274
|
-
* `quiescence_ticks` is parsed and carried on the policy but is NOT used here: the
|
|
275
|
-
* conductor has no durable per-tick marker to count "N consecutive ticks" against,
|
|
276
|
-
* and tick stability MUST NOT be faked from process memory (it would not survive a
|
|
277
|
-
* restart). When only `quiescence_ticks` is configured (no `quiescence_ms`), the
|
|
278
|
-
* stable-head path cannot prove quiescence and only `run.stopped` folds the ticket.
|
|
279
|
-
* Worker MCP heartbeats (`message.delivered`/`message.acked`) are deliberately NOT
|
|
280
|
-
* used as the reliable primitive — that channel is exactly what fails in Issue 1.
|
|
281
|
-
*/
|
|
282
|
-
export function buildActiveTicketQuiescenceResolver(deps) {
|
|
283
|
-
return (ticketKey, prBinding) => {
|
|
284
|
-
if (!deps.policy.enabled)
|
|
285
|
-
return { quiescent: false, reason: "policy_disabled" };
|
|
286
|
-
const implRunId = deps.resolveImplRunId(ticketKey);
|
|
287
|
-
// Select the ticket's implementation-run events. Prefer the impl run_id (which
|
|
288
|
-
// excludes any `:review` run); fall back to subject match when no run is known.
|
|
289
|
-
const matchesTicket = (ev) => implRunId !== null
|
|
290
|
-
? ev.run_id === implRunId
|
|
291
|
-
: ev.subject === ticketKey;
|
|
292
|
-
// Explicit completion evidence: an implementation `run.stopped`.
|
|
293
|
-
for (const ev of deps.events) {
|
|
294
|
-
if (ev.type === "run.stopped" && matchesTicket(ev)) {
|
|
295
|
-
return { quiescent: true, reason: "run.stopped" };
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
// Stable-head evidence: latest head-changing event for the impl run.
|
|
299
|
-
let latest = null;
|
|
300
|
-
for (const ev of deps.events) {
|
|
301
|
-
if (!HEAD_CHANGING_EVENT_TYPES.has(ev.type) || !matchesTicket(ev))
|
|
302
|
-
continue;
|
|
303
|
-
const headSha = getHeadSha(ev);
|
|
304
|
-
if (headSha === null)
|
|
305
|
-
continue;
|
|
306
|
-
const timeMs = typeof ev.time === "string" ? Date.parse(ev.time) : NaN;
|
|
307
|
-
if (Number.isNaN(timeMs))
|
|
308
|
-
continue;
|
|
309
|
-
if (!latest || ev.seq >= latest.seq) {
|
|
310
|
-
latest = { headSha: headSha.toLowerCase(), timeMs, seq: ev.seq };
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
if (!latest)
|
|
314
|
-
return { quiescent: false, reason: "no_signal" };
|
|
315
|
-
if (latest.headSha !== prBinding.headSha.toLowerCase()) {
|
|
316
|
-
return { quiescent: false, reason: "unstable_head", last_head_event_time: latest.timeMs };
|
|
317
|
-
}
|
|
318
|
-
// Head matches the candidate PR head. Prove stability via the ms window only.
|
|
319
|
-
if (deps.policy.quiescence_ms === null) {
|
|
320
|
-
return { quiescent: false, reason: "no_signal", last_head_event_time: latest.timeMs };
|
|
321
|
-
}
|
|
322
|
-
const stableMs = deps.nowMs - latest.timeMs;
|
|
323
|
-
if (stableMs >= deps.policy.quiescence_ms) {
|
|
324
|
-
return {
|
|
325
|
-
quiescent: true,
|
|
326
|
-
reason: "stable_head",
|
|
327
|
-
stable_ms: stableMs,
|
|
328
|
-
last_head_event_time: latest.timeMs,
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
return { quiescent: false, reason: "unstable_head", last_head_event_time: latest.timeMs };
|
|
332
|
-
};
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* For each `ready_for_review` ticket — and (BAPI-487) each `blocked` ticket whose
|
|
336
|
-
* live PR head has advanced past the head that blocked it — ask the conductor to
|
|
337
|
-
* evaluate the composite done-gate itself via {@link observePrCiOnce}, the
|
|
338
|
-
* correctness backstop for FINDING 6 where a worker never self-emits `gate.met`.
|
|
339
|
-
* `observePrCiOnce` binds to the CURRENT head SHA, fails closed on any
|
|
340
|
-
* unavailable/ambiguous/stale-head signal, and idempotently emits `gate.met`
|
|
341
|
-
* (deduped by ticket+PR+head_sha) so the fold + merge-enqueue happens exactly once
|
|
342
|
-
* regardless of whether the worker also emitted it.
|
|
343
|
-
*
|
|
344
|
-
* A `blocked` ticket is re-evaluated ONLY when its PR binding resolves AND either
|
|
345
|
-
* the recorded blocked head is unknown (fail-closed recovery) or the current head
|
|
346
|
-
* differs from it — a ticket still blocked on its current head is left blocked so
|
|
347
|
-
* a same-head failure is never bypassed.
|
|
348
|
-
*
|
|
349
|
-
* Fully fail-closed and non-blocking: a per-ticket observation error is caught and
|
|
350
|
-
* logged so it can never crash or stall the reconcile loop; tickets that are
|
|
351
|
-
* neither `ready_for_review` nor advanced-head `blocked`, and tickets without a
|
|
352
|
-
* PR binding, are skipped.
|
|
353
|
-
*/
|
|
354
|
-
export async function runConductorDoneGatePass(ticketStatuses, deps) {
|
|
355
|
-
const backstopEnabled = deps.dispatchedBackstopPolicy?.enabled === true;
|
|
356
|
-
for (const [ticketKey, status] of ticketStatuses) {
|
|
357
|
-
// BAPI-525 Change B: admit the base statuses (ready_for_review/blocked) always;
|
|
358
|
-
// admit the active statuses (dispatched/running) ONLY when the dispatched
|
|
359
|
-
// backstop is enabled. Every other status (terminal, planned, reviewing, …) is
|
|
360
|
-
// skipped before any PR binding / CI observation, exactly as before.
|
|
361
|
-
const isActive = isActiveWorkerStatus(status);
|
|
362
|
-
if (!isBaseDoneGateStatus(status) && !(isActive && backstopEnabled))
|
|
363
|
-
continue;
|
|
364
|
-
// Base statuses always resolve the CURRENT head via gh-discovery (unchanged).
|
|
365
|
-
// Active statuses use the local-first resolver (BAPI-525 Change B) so a
|
|
366
|
-
// dispatched ticket with no local PR binding is not re-polled every tick.
|
|
367
|
-
const prBinding = isActive
|
|
368
|
-
? (deps.resolveActivePrBinding ?? deps.resolvePrBinding)(ticketKey)
|
|
369
|
-
: deps.resolvePrBinding(ticketKey);
|
|
370
|
-
if (prBinding === null) {
|
|
371
|
-
deps.log(`[epic-tick] done-gate poll for ${ticketKey}: skipped (no PR binding)`);
|
|
372
|
-
continue;
|
|
373
|
-
}
|
|
374
|
-
// BAPI-525 Change B: an admitted active ticket is folded ONLY when quiescent
|
|
375
|
-
// (explicit run.stopped or a stable head) — never on green-PR evidence alone, so
|
|
376
|
-
// an interactive worker still pushing commits is not yanked out from under.
|
|
377
|
-
if (isActive) {
|
|
378
|
-
const quiescence = deps.resolveActiveTicketQuiescence?.(ticketKey, prBinding) ?? {
|
|
379
|
-
quiescent: false,
|
|
380
|
-
reason: "no_signal",
|
|
381
|
-
};
|
|
382
|
-
if (!quiescence.quiescent) {
|
|
383
|
-
deps.log(`[epic-tick] done-gate poll for ${ticketKey}: skipped (${status} not quiescent: ${quiescence.reason})`);
|
|
384
|
-
continue;
|
|
385
|
-
}
|
|
386
|
-
deps.log(`[epic-tick] done-gate backstop for ${ticketKey}: ${status} quiescent (${quiescence.reason}); evaluating done-gate at head ${prBinding.headSha}`);
|
|
387
|
-
}
|
|
388
|
-
// BAPI-487: gate a `blocked` ticket's re-evaluation on its head advancing.
|
|
389
|
-
if (status === "blocked") {
|
|
390
|
-
const blockedHead = deps.resolveBlockedHeadSha?.(ticketKey) ?? null;
|
|
391
|
-
if (blockedHead === null) {
|
|
392
|
-
deps.log(`[epic-tick] done-gate re-eval for ${ticketKey}: blocked with no recorded head; ` +
|
|
393
|
-
`polling current head ${prBinding.headSha} fail-closed as recovery`);
|
|
394
|
-
}
|
|
395
|
-
else if (blockedHead.toLowerCase() === prBinding.headSha.toLowerCase()) {
|
|
396
|
-
deps.log(`[epic-tick] done-gate poll for ${ticketKey}: skipped (still blocked on current head ${prBinding.headSha})`);
|
|
397
|
-
continue;
|
|
398
|
-
}
|
|
399
|
-
else {
|
|
400
|
-
deps.log(`[epic-tick] done-gate re-eval for ${ticketKey}: blocked head ${blockedHead} ` +
|
|
401
|
-
`superseded by current head ${prBinding.headSha}; re-evaluating`);
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
// Stamp the ticket's run_id and (when available) worker_id onto the emitted
|
|
405
|
-
// gate.met via a per-ticket env override (observePrCiOnce reads
|
|
406
|
-
// BAPI_EPIC_IMPLEMENTER_RUN_ID/_WORKER_ID from env, env taking precedence). run_id
|
|
407
|
-
// correlates the fold to the ticket. worker_id is attribution ONLY: BAPI-525
|
|
408
|
-
// Change A removed the worker_id requirement from merge-identity extraction, so
|
|
409
|
-
// a missing worker_id no longer blocks the merge — the backstop stamps real
|
|
410
|
-
// attribution when it can resolve it and merges regardless when it cannot.
|
|
411
|
-
const runId = deps.resolveRunId?.(ticketKey) ?? null;
|
|
412
|
-
const workerId = deps.resolveWorkerId?.(ticketKey) ?? null;
|
|
413
|
-
// BAPI-494: a `ready_for_review` PR that is already un-mergeable
|
|
414
|
-
// (CONFLICTING/DIRTY) can never be re-reviewed (claude-review won't verdict an
|
|
415
|
-
// unmergeable branch) or merged — so it would sit at ready_for_review forever.
|
|
416
|
-
// Route it into the head-scoped `merge.conflict` blocking path (folded next
|
|
417
|
-
// tick, remediated as a resume-mode redispatch) BEFORE re-polling CI, and skip
|
|
418
|
-
// CI observation for this ticket. Only `ready_for_review` conflicts are emitted
|
|
419
|
-
// here; a `blocked` ticket already has routing + stale-head re-evaluation.
|
|
420
|
-
if (status === "ready_for_review" && isPrMergeConflict(prBinding)) {
|
|
421
|
-
try {
|
|
422
|
-
await deps.emitConflictSignal?.({
|
|
423
|
-
ticketKey,
|
|
424
|
-
repoName: deps.access.repoName,
|
|
425
|
-
prNumber: prBinding.prNumber,
|
|
426
|
-
headSha: prBinding.headSha,
|
|
427
|
-
mergeable: prBinding.mergeable,
|
|
428
|
-
mergeStateStatus: prBinding.mergeStateStatus,
|
|
429
|
-
runId,
|
|
430
|
-
workerId,
|
|
431
|
-
});
|
|
432
|
-
deps.log(`[epic-tick] done-gate conflict for ${ticketKey}: PR #${prBinding.prNumber} ` +
|
|
433
|
-
`not mergeable at head ${prBinding.headSha}; emitted merge.conflict`);
|
|
434
|
-
}
|
|
435
|
-
catch (err) {
|
|
436
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "conflict emit error";
|
|
437
|
-
deps.errorLog(`[epic-tick] done-gate conflict-signal failed (${safeMsg}) for ${ticketKey}; continuing`);
|
|
438
|
-
}
|
|
439
|
-
continue;
|
|
440
|
-
}
|
|
441
|
-
// BAPI-586: block a wrong-base PR at reconciliation BEFORE any CI/review
|
|
442
|
-
// evaluation. The comparison uses the ACTUAL observed base (`prBinding.baseRef`,
|
|
443
|
-
// from the SAME gh binding call) rather than delegating to observePrCiOnce —
|
|
444
|
-
// that call receives EXPLICIT pr_number/head_sha and so takes the no-discovery
|
|
445
|
-
// binding path, where `base_ref` is never populated. Fail-open when the base is
|
|
446
|
-
// unknown (`baseRef` absent) so a correctly-based PR is NEVER falsely blocked;
|
|
447
|
-
// only a CONFIRMED mismatch skips the ticket. The executor finalization guard
|
|
448
|
-
// remains the primary layer; this is the reconciliation backstop.
|
|
449
|
-
if (deps.expectedBaseBranch &&
|
|
450
|
-
typeof prBinding.baseRef === "string" &&
|
|
451
|
-
prBinding.baseRef !== deps.expectedBaseBranch) {
|
|
452
|
-
deps.log(`[epic-tick] done-gate poll for ${ticketKey}: pr-base-mismatch — PR #${prBinding.prNumber} ` +
|
|
453
|
-
`targets base '${prBinding.baseRef}' but the run base is '${deps.expectedBaseBranch}'; ` +
|
|
454
|
-
`not emitting gate.met (rebuild from origin/${deps.expectedBaseBranch}, do not retarget the PR in the UI)`);
|
|
455
|
-
continue;
|
|
456
|
-
}
|
|
457
|
-
const perTicketEnv = {
|
|
458
|
-
...deps.env,
|
|
459
|
-
...(runId ? { BAPI_EPIC_IMPLEMENTER_RUN_ID: runId } : {}),
|
|
460
|
-
...(workerId ? { BAPI_EPIC_IMPLEMENTER_WORKER_ID: workerId } : {}),
|
|
461
|
-
};
|
|
462
|
-
try {
|
|
463
|
-
const observeResult = await deps.observePrCi({
|
|
464
|
-
repoName: deps.access.repoName,
|
|
465
|
-
prNumber: prBinding.prNumber,
|
|
466
|
-
headSha: prBinding.headSha,
|
|
467
|
-
}, {
|
|
468
|
-
env: perTicketEnv,
|
|
469
|
-
resolveAccess: async () => ({ ok: true, access: deps.access }),
|
|
470
|
-
});
|
|
471
|
-
deps.log(`[epic-tick] done-gate poll for ${ticketKey}: ${observeResult.reason}`);
|
|
472
|
-
}
|
|
473
|
-
catch (err) {
|
|
474
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "observe error";
|
|
475
|
-
deps.errorLog(`[epic-tick] done-gate poll failed (${safeMsg}) for ${ticketKey}; continuing`);
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
// ---------------------------------------------------------------------------
|
|
480
|
-
// N-3 run self-completion (BAPI-507)
|
|
481
|
-
// ---------------------------------------------------------------------------
|
|
482
|
-
/**
|
|
483
|
-
* BAPI-507 (N-3): should the epic run self-complete this tick? True ONLY when the
|
|
484
|
-
* approved plan has at least one ticket AND every plan ticket's effective status
|
|
485
|
-
* is exactly `"done"` in `observed.ticket_statuses`. Any node that is
|
|
486
|
-
* `abandoned` / `blocked` / `ready_for_review` / `running` / `reviewing` /
|
|
487
|
-
* `ready` / `dispatched` / `planned`, missing from the status map, or any other
|
|
488
|
-
* non-`done` value makes this return `false`. Conservative done-only policy: a
|
|
489
|
-
* plan ending in a `done` + `abandoned` mix does NOT auto-complete — an operator
|
|
490
|
-
* decides how to close a run with abandoned nodes. Pure: no I/O, no clock.
|
|
491
|
-
*/
|
|
492
|
-
function shouldSelfCompleteEpicRun(plan, observed) {
|
|
493
|
-
if (plan.tickets.length === 0)
|
|
494
|
-
return false;
|
|
495
|
-
for (const ticket of plan.tickets) {
|
|
496
|
-
if (observed.ticket_statuses.get(ticket.ticket_key) !== "done") {
|
|
497
|
-
return false;
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
return true;
|
|
501
|
-
}
|
|
502
|
-
// ---------------------------------------------------------------------------
|
|
503
|
-
// runEpicTick
|
|
504
|
-
// ---------------------------------------------------------------------------
|
|
505
|
-
/**
|
|
506
|
-
* Execute one stateless reconciliation pass for an Epic. Claims the lease,
|
|
507
|
-
* rebuilds observed state, asserts plan integrity, reconciles, and exits.
|
|
508
|
-
* Returns a structured result with a process exit code.
|
|
509
|
-
*
|
|
510
|
-
* Offline / fail-closed: if Bridge API credentials or the backend are
|
|
511
|
-
* unreachable, the tick takes NO privileged action, logs a sanitized
|
|
512
|
-
* diagnostic, and returns exit code 0 (observer mode).
|
|
513
|
-
*/
|
|
514
|
-
export async function runEpicTick(options, deps = {}) {
|
|
515
|
-
const { epic_key, scheduled_at, lease_owner = defaultLeaseOwner(), lease_ttl_seconds = DEFAULT_LEASE_TTL_SECONDS, max_drift_ms = DEFAULT_MAX_DRIFT_MS, } = options;
|
|
516
|
-
const nowFn = deps.now ?? (() => Date.now());
|
|
517
|
-
const log = deps.log ?? ((msg) => console.log(msg));
|
|
518
|
-
const errorLog = deps.errorLog ?? ((msg) => process.stderr.write(`${msg}\n`));
|
|
519
|
-
const escalateOnce = deps.escalateOnce ?? defaultEscalateOnce;
|
|
520
|
-
const dispatchSeam = deps.dispatchSeam ?? defaultDispatchSeam;
|
|
521
|
-
// BAPI-445: optional review dispatch seam. When absent the spec re-review
|
|
522
|
-
// sequencing gate stays off (a ready ticket dispatches implementation directly).
|
|
523
|
-
const dispatchReviewSeamFn = deps.dispatchReviewSeam;
|
|
524
|
-
const processMergeFn = deps.processMerge ?? processGateMetMerge;
|
|
525
|
-
const postActionWaitSeam = deps.postActionWaitSeam ?? defaultPostActionWaitSeam;
|
|
526
|
-
const fetchLocalEvents = deps.fetchLocalEvents ??
|
|
527
|
-
((_key, _runIds) => []);
|
|
528
|
-
const resolveBridgeAccess = deps.resolveBridgeAccess ?? resolveConductorBridgeApiAccess;
|
|
529
|
-
const claimLeaseFn = deps.claimLease ?? claimEpicSupervisionLease;
|
|
530
|
-
const fetchEpicStateFn = deps.fetchEpicState ?? fetchEpicRunState;
|
|
531
|
-
const releaseLease = deps.releaseLease;
|
|
532
|
-
const env = deps.env ?? process.env;
|
|
533
|
-
const observePrCiSeamFn = deps.observePrCiSeam ?? observePrCiOnce;
|
|
534
|
-
// BAPI-507 (N-3): default self-completion seam CASes the run active → done via
|
|
535
|
-
// the existing PATCH /runs/{id} path, addressing the run by its concrete UUID.
|
|
536
|
-
const completeEpicRunFn = deps.completeEpicRun ??
|
|
537
|
-
(async (acc, epicRunId) => {
|
|
538
|
-
await updateEpicRunStatus(acc, {
|
|
539
|
-
epicKey: epicRunId,
|
|
540
|
-
status: "done",
|
|
541
|
-
expectedStatus: "active",
|
|
542
|
-
});
|
|
543
|
-
});
|
|
544
|
-
// BAPI-494: a single durable event emitter reused by BOTH the parse-after-merge
|
|
545
|
-
// marker block and the done-gate `merge.conflict` wiring, so there is one
|
|
546
|
-
// injectable ledger path (not a second hardcoded emitter).
|
|
547
|
-
const emitConductorEventFn = deps.emitConductorEvent ?? emitConductorEventIfNew;
|
|
548
|
-
// FINDING 1 (BAPI-463): a dry-run tick must exercise the full dispatch-resolution
|
|
549
|
-
// path (ready-set → resolved command + model routing) yet persist NO authoritative
|
|
550
|
-
// dispatch state. Without this guard, `correlateRunId` writes a `run_spawned` row
|
|
551
|
-
// under the REAL dispatch_key, and the next real tick's `claimDispatchKey` returns
|
|
552
|
-
// `already-spawned`, silently skipping the real worker spawn.
|
|
553
|
-
const isDryRun = env.BAPI_EPIC_IMPLEMENTER_DISPATCH_DRY_RUN === "1";
|
|
554
|
-
const startMs = nowFn();
|
|
555
|
-
// ---------------------------------------------------------------------------
|
|
556
|
-
// Step 0: Resolve Bridge API access (offline / fail-closed guard)
|
|
557
|
-
// ---------------------------------------------------------------------------
|
|
558
|
-
let access;
|
|
559
|
-
try {
|
|
560
|
-
const accessResult = await resolveBridgeAccess();
|
|
561
|
-
if (!accessResult.ok) {
|
|
562
|
-
errorLog(`[epic-tick] observe-only: bridge access unavailable for epic=${epic_key}: ${accessResult.kind}`);
|
|
563
|
-
return {
|
|
564
|
-
run_id: epic_key,
|
|
565
|
-
status: "complete",
|
|
566
|
-
exit_code: 0,
|
|
567
|
-
reason: "offline: bridge access unavailable",
|
|
568
|
-
last_seq: -1,
|
|
569
|
-
worker_count: 0,
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
access = accessResult.access;
|
|
573
|
-
}
|
|
574
|
-
catch (err) {
|
|
575
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "init error";
|
|
576
|
-
errorLog(`[epic-tick] observe-only: bridge access resolution failed (${safeMsg}) for epic=${epic_key}`);
|
|
577
|
-
return {
|
|
578
|
-
run_id: epic_key,
|
|
579
|
-
status: "complete",
|
|
580
|
-
exit_code: 0,
|
|
581
|
-
reason: "offline: bridge access resolution failed",
|
|
582
|
-
last_seq: -1,
|
|
583
|
-
worker_count: 0,
|
|
584
|
-
};
|
|
585
|
-
}
|
|
586
|
-
// ---------------------------------------------------------------------------
|
|
587
|
-
// Step 1: Claim the epic supervision lease (single-writer guard)
|
|
588
|
-
// ---------------------------------------------------------------------------
|
|
589
|
-
let leaseAcquired = false;
|
|
590
|
-
try {
|
|
591
|
-
const leaseResult = await claimLeaseFn(access, {
|
|
592
|
-
epicKey: epic_key,
|
|
593
|
-
leaseOwner: lease_owner,
|
|
594
|
-
ttlSeconds: lease_ttl_seconds,
|
|
595
|
-
});
|
|
596
|
-
if (!leaseResult.ok) {
|
|
597
|
-
if (leaseResult.kind === "terminal") {
|
|
598
|
-
log(`[epic-tick] epic=${epic_key} is terminal (${leaseResult.row.status}); nothing to do`);
|
|
599
|
-
return {
|
|
600
|
-
run_id: epic_key,
|
|
601
|
-
status: "complete",
|
|
602
|
-
exit_code: 0,
|
|
603
|
-
reason: `observer: epic is terminal (${leaseResult.row.status})`,
|
|
604
|
-
last_seq: -1,
|
|
605
|
-
worker_count: 0,
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
// held-by-other
|
|
609
|
-
log(`[epic-tick] lease held by another worker for epic=${epic_key}; exiting as observer`);
|
|
610
|
-
return {
|
|
611
|
-
run_id: epic_key,
|
|
612
|
-
status: "complete",
|
|
613
|
-
exit_code: 0,
|
|
614
|
-
reason: "observer: lease held by another worker",
|
|
615
|
-
last_seq: -1,
|
|
616
|
-
worker_count: 0,
|
|
617
|
-
};
|
|
618
|
-
}
|
|
619
|
-
leaseAcquired = true;
|
|
620
|
-
}
|
|
621
|
-
catch (err) {
|
|
622
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "lease error";
|
|
623
|
-
errorLog(`[epic-tick] observe-only: lease claim failed (${safeMsg}) for epic=${epic_key}`);
|
|
624
|
-
return {
|
|
625
|
-
run_id: epic_key,
|
|
626
|
-
status: "complete",
|
|
627
|
-
exit_code: 0,
|
|
628
|
-
reason: "offline: lease claim failed",
|
|
629
|
-
last_seq: -1,
|
|
630
|
-
worker_count: 0,
|
|
631
|
-
};
|
|
632
|
-
}
|
|
633
|
-
// ---------------------------------------------------------------------------
|
|
634
|
-
// Steps 2-6: Main reconcile body (lease is held)
|
|
635
|
-
// ---------------------------------------------------------------------------
|
|
636
|
-
let exitCode = 0;
|
|
637
|
-
let reason = "reconcile complete";
|
|
638
|
-
let workerCount = 0;
|
|
639
|
-
try {
|
|
640
|
-
// Step 2: Drift check
|
|
641
|
-
if (scheduled_at !== undefined) {
|
|
642
|
-
const driftMs = startMs - scheduled_at;
|
|
643
|
-
if (driftMs > max_drift_ms) {
|
|
644
|
-
log(`[epic-tick] drift warning: epic=${epic_key} fired ${driftMs}ms late (threshold=${max_drift_ms}ms)`);
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
// Step 3: Rebuild observed state
|
|
648
|
-
let epicRunState;
|
|
649
|
-
try {
|
|
650
|
-
epicRunState = await fetchEpicStateFn(access, epic_key);
|
|
651
|
-
}
|
|
652
|
-
catch (err) {
|
|
653
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "fetch error";
|
|
654
|
-
errorLog(`[epic-tick] state fetch failed (${safeMsg}) for epic=${epic_key}`);
|
|
655
|
-
exitCode = 1;
|
|
656
|
-
reason = "state fetch failed";
|
|
657
|
-
return {
|
|
658
|
-
run_id: epic_key,
|
|
659
|
-
status: "failed",
|
|
660
|
-
exit_code: exitCode,
|
|
661
|
-
reason,
|
|
662
|
-
last_seq: -1,
|
|
663
|
-
worker_count: 0,
|
|
664
|
-
};
|
|
665
|
-
}
|
|
666
|
-
// Scope the local-ledger read to this epic's dispatched run_ids. The shared
|
|
667
|
-
// ~/.config/bridge/events.db ledger accumulates events for every epic/worker
|
|
668
|
-
// on the machine; rebuildObservedState only folds signals whose run_id maps
|
|
669
|
-
// to one of these dispatches, so scoping the read here avoids loading the
|
|
670
|
-
// entire (up to 50K-row) ledger on every tick.
|
|
671
|
-
const dispatchedRunIds = (epicRunState.dispatches ?? [])
|
|
672
|
-
.map((d) => d.run_id)
|
|
673
|
-
.filter((rid) => typeof rid === "string" && rid.length > 0);
|
|
674
|
-
const localEvents = await fetchLocalEvents(epic_key, dispatchedRunIds);
|
|
675
|
-
const observed = rebuildObservedState(epicRunState, localEvents, nowFn());
|
|
676
|
-
workerCount = [...observed.ticket_statuses.values()].filter((s) => ACTIVE_WORKER_STATUSES.has(s)).length;
|
|
677
|
-
// Step 3.5: Run post-action waits (parse-after-merge)
|
|
678
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
679
|
-
const pamConfig = epicRunState.epic_run.policy_json
|
|
680
|
-
?.post_action_waits
|
|
681
|
-
?.parse_after_merge;
|
|
682
|
-
const isParseWaitEnabled = pamConfig?.enabled === true;
|
|
683
|
-
if (isParseWaitEnabled) {
|
|
684
|
-
const maxWaitMs = typeof pamConfig?.max_wait_ms === "number" ? pamConfig.max_wait_ms : 10 * 60 * 1000;
|
|
685
|
-
const fetchParseStatusFn = deps.fetchParseStatus ?? fetchParseStatus;
|
|
686
|
-
const triggerParseFn = deps.triggerParse ?? triggerRepositoryParse;
|
|
687
|
-
for (let i = 0; i < observed.unfolded_terminal_signals.length; i++) {
|
|
688
|
-
const signal = observed.unfolded_terminal_signals[i];
|
|
689
|
-
if (signal.signal_type !== "merge.succeeded")
|
|
690
|
-
continue;
|
|
691
|
-
const ticketKey = signal.ticket_key;
|
|
692
|
-
const mergeEvent = signal.event;
|
|
693
|
-
const mergeTimeMs = new Date(mergeEvent.time).getTime();
|
|
694
|
-
// rebuildObservedState only surfaces a merge.succeeded whose run_id maps to
|
|
695
|
-
// a tracked dispatch, so mergeRunId is non-null and in the run-scoped
|
|
696
|
-
// localEvents read — binding the parse.triggered marker to it guarantees a
|
|
697
|
-
// later tick re-reads it. The merged PR head SHA (pre-merge) lives under
|
|
698
|
-
// the merge.* event's data.details; used only as an extra dedupe dimension.
|
|
699
|
-
const mergeRunId = mergeEvent.run_id ?? null;
|
|
700
|
-
const mergeDetails = mergeEvent.data?.details;
|
|
701
|
-
const mergeHeadSha = typeof mergeDetails?.head_sha === "string" ? mergeDetails.head_sha : undefined;
|
|
702
|
-
const revertSignal = () => {
|
|
703
|
-
const origStatus = epicRunState.ticket_statuses.find((ts) => ts.ticket_key === ticketKey)?.status ??
|
|
704
|
-
"running";
|
|
705
|
-
observed.ticket_statuses.set(ticketKey, origStatus);
|
|
706
|
-
observed.unfolded_terminal_signals.splice(i, 1);
|
|
707
|
-
i -= 1;
|
|
708
|
-
};
|
|
709
|
-
const currentPgStatus = epicRunState.ticket_statuses.find((ts) => ts.ticket_key === ticketKey)?.status ?? null;
|
|
710
|
-
// DURABLE wait state (replaces the former in-memory parseWaitStateMap, which
|
|
711
|
-
// was lost between stateless epic-tick processes → re-triggered the parse on
|
|
712
|
-
// every idle tick and never folded to `done`). The marker is a
|
|
713
|
-
// `parse.triggered` ledger event correlated to this ticket's dispatch run_id
|
|
714
|
-
// and emitted strictly after the merge — so its presence is the skew-free
|
|
715
|
-
// signal that the post-merge parse was already kicked off.
|
|
716
|
-
const parseTriggeredEvent = localEvents.find((e) => e.type === "parse.triggered" &&
|
|
717
|
-
e.subject === ticketKey &&
|
|
718
|
-
e.run_id === mergeRunId &&
|
|
719
|
-
new Date(e.time).getTime() >= mergeTimeMs);
|
|
720
|
-
const elapsedMs = nowFn() - mergeTimeMs;
|
|
721
|
-
// BAPI-527: enter (or hold at) the explicit parse_pending state. This
|
|
722
|
-
// replaces the old "revert to ready_for_review and hold" behavior — a
|
|
723
|
-
// merged ticket whose post-merge parse is queued/running is now DURABLY
|
|
724
|
-
// parse_pending, so the state is observable between stateless epic-tick
|
|
725
|
-
// processes. When the ticket is ALREADY durably parse_pending we hold
|
|
726
|
-
// WITHOUT a churny re-CAS (revert drops the signal, leaving the Postgres row
|
|
727
|
-
// untouched); otherwise we retag the merge.succeeded fold to parse_pending so
|
|
728
|
-
// reconcile CASes it there.
|
|
729
|
-
const holdOrEnterParsePending = () => {
|
|
730
|
-
if (currentPgStatus === "parse_pending") {
|
|
731
|
-
revertSignal();
|
|
732
|
-
return;
|
|
733
|
-
}
|
|
734
|
-
signal.next_status = "parse_pending";
|
|
735
|
-
observed.ticket_statuses.set(ticketKey, "parse_pending");
|
|
736
|
-
};
|
|
737
|
-
// BAPI-527: fold to `blocked` for a terminal parse failure or an exhausted
|
|
738
|
-
// wait budget. Escalates exactly once, gated on the durable Postgres status
|
|
739
|
-
// (not an in-memory flag): a later tick that finds the ticket already
|
|
740
|
-
// `blocked` drops the signal without re-escalating or re-CASing. EVERY
|
|
741
|
-
// terminal failure/timeout path routes through here, so a permanent parse
|
|
742
|
-
// failure can never silently wedge the epic at parse_pending. `reason` is a
|
|
743
|
-
// bounded, secret-free summary — never subprocess stderr/traceback.
|
|
744
|
-
const foldToBlocked = async (reason) => {
|
|
745
|
-
if (currentPgStatus === "blocked") {
|
|
746
|
-
observed.ticket_statuses.set(ticketKey, "blocked");
|
|
747
|
-
observed.unfolded_terminal_signals.splice(i, 1);
|
|
748
|
-
i -= 1;
|
|
749
|
-
return;
|
|
750
|
-
}
|
|
751
|
-
await escalateOnce(epic_key, reason);
|
|
752
|
-
signal.next_status = "blocked";
|
|
753
|
-
observed.ticket_statuses.set(ticketKey, "blocked");
|
|
754
|
-
// Let the signal remain so the reconcile pass CASes once to blocked.
|
|
755
|
-
};
|
|
756
|
-
// Budget exhaustion (measured from the durable merge.succeeded time):
|
|
757
|
-
// escalate once then block with a parse-timeout reason.
|
|
758
|
-
if (elapsedMs > maxWaitMs) {
|
|
759
|
-
await foldToBlocked(`parse-after-merge timed out (budget exhausted) for ${ticketKey}`);
|
|
760
|
-
continue;
|
|
761
|
-
}
|
|
762
|
-
if (!parseTriggeredEvent) {
|
|
763
|
-
// No durable trigger for this merge yet — fire the parse, record the
|
|
764
|
-
// marker, and set the ticket to parse_pending. DO NOT poll parse status
|
|
765
|
-
// in the SAME tick as the trigger, so parse_pending is always observable
|
|
766
|
-
// after merge before any success/failure fold.
|
|
767
|
-
try {
|
|
768
|
-
// BAPI-654 (T2): additively reconcile the run's shadow index for this
|
|
769
|
-
// observed feature-branch merge. The backend records the current
|
|
770
|
-
// feature-branch head and schedules a shadow re-parse; when no shadow
|
|
771
|
-
// applies it is a benign no-op and the canonical parse-after-merge path
|
|
772
|
-
// below runs unchanged (Step 9.10). Fail-open: a reconcile error never
|
|
773
|
-
// blocks the canonical trigger.
|
|
774
|
-
if (deps.reconcileShadowMerge) {
|
|
775
|
-
try {
|
|
776
|
-
const shadowResult = await deps.reconcileShadowMerge(access, epic_key, ticketKey);
|
|
777
|
-
if (shadowResult.applies) {
|
|
778
|
-
log(`[epic-runtime] shadow merge-reconcile for ${ticketKey}: scheduled=${shadowResult.scheduled} reason=${shadowResult.reasonCode}`);
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
catch (err) {
|
|
782
|
-
errorLog(`[epic-runtime] shadow merge-reconcile failed for ${ticketKey}: ${safeDiagnosticMessage(err, "reconcile error")}`);
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
await triggerParseFn(access);
|
|
786
|
-
emitConductorEventFn({
|
|
787
|
-
source: PARSE_WAIT_EVENT_SOURCE,
|
|
788
|
-
type: "parse.triggered",
|
|
789
|
-
subject: ticketKey,
|
|
790
|
-
run_id: mergeRunId,
|
|
791
|
-
worker_id: mergeEvent.worker_id ?? null,
|
|
792
|
-
producer: PARSE_WAIT_EVENT_PRODUCER,
|
|
793
|
-
observed_via: "supervisor",
|
|
794
|
-
time: new Date(nowFn()).toISOString(),
|
|
795
|
-
data: {
|
|
796
|
-
summary: `parse-after-merge triggered for ${ticketKey}`,
|
|
797
|
-
details: {
|
|
798
|
-
epic_key,
|
|
799
|
-
ticket_key: ticketKey,
|
|
800
|
-
...(mergeHeadSha ? { head_sha: mergeHeadSha } : {}),
|
|
801
|
-
},
|
|
802
|
-
},
|
|
803
|
-
}, {
|
|
804
|
-
event_type: "parse.triggered",
|
|
805
|
-
run_id: mergeRunId ?? undefined,
|
|
806
|
-
commit_sha: mergeHeadSha,
|
|
807
|
-
});
|
|
808
|
-
log(`[epic-tick] triggered parse-after-merge for ${ticketKey} in epic=${epic_key}; holding at parse_pending`);
|
|
809
|
-
holdOrEnterParsePending();
|
|
810
|
-
}
|
|
811
|
-
catch (err) {
|
|
812
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "trigger error";
|
|
813
|
-
errorLog(`[epic-tick] parse trigger failed (${safeMsg}) for ${ticketKey}; will retry next tick`);
|
|
814
|
-
// Transient trigger failure: hold the merge.succeeded signal for the
|
|
815
|
-
// next tick rather than folding to done/blocked.
|
|
816
|
-
revertSignal();
|
|
817
|
-
}
|
|
818
|
-
continue;
|
|
819
|
-
}
|
|
820
|
-
// A durable parse.triggered exists for this merge — poll the durable parse
|
|
821
|
-
// status surface (BAPI-527: idle | queued | in_progress | succeeded | failed).
|
|
822
|
-
let parseStatusResult;
|
|
823
|
-
try {
|
|
824
|
-
parseStatusResult = await fetchParseStatusFn(access);
|
|
825
|
-
}
|
|
826
|
-
catch (err) {
|
|
827
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "fetch error";
|
|
828
|
-
errorLog(`[epic-tick] parse-status check failed (${safeMsg}) for ${ticketKey}; will retry next tick`);
|
|
829
|
-
// Transient status-fetch failure: hold in parse_pending for the next tick.
|
|
830
|
-
holdOrEnterParsePending();
|
|
831
|
-
continue;
|
|
832
|
-
}
|
|
833
|
-
if (parseStatusResult.status === "failed") {
|
|
834
|
-
// Terminal parse failure — emit a compact parse.failed marker, then fold
|
|
835
|
-
// to blocked (escalate-once). `last_error` is already a bounded, sanitized
|
|
836
|
-
// backend summary; the marker carries no stdout/stderr/stack/command.
|
|
837
|
-
emitConductorEventFn({
|
|
838
|
-
source: PARSE_WAIT_EVENT_SOURCE,
|
|
839
|
-
type: "parse.failed",
|
|
840
|
-
subject: ticketKey,
|
|
841
|
-
run_id: mergeRunId,
|
|
842
|
-
worker_id: mergeEvent.worker_id ?? null,
|
|
843
|
-
producer: PARSE_WAIT_EVENT_PRODUCER,
|
|
844
|
-
observed_via: "supervisor",
|
|
845
|
-
time: new Date(nowFn()).toISOString(),
|
|
846
|
-
data: {
|
|
847
|
-
summary: `parse-after-merge failed for ${ticketKey}`,
|
|
848
|
-
status: "failed",
|
|
849
|
-
reason: "parse_failed",
|
|
850
|
-
details: {
|
|
851
|
-
epic_key,
|
|
852
|
-
ticket_key: ticketKey,
|
|
853
|
-
...(mergeHeadSha ? { head_sha: mergeHeadSha } : {}),
|
|
854
|
-
...(typeof parseStatusResult.last_error === "string"
|
|
855
|
-
? { last_error: parseStatusResult.last_error }
|
|
856
|
-
: {}),
|
|
857
|
-
...(typeof parseStatusResult.attempt_count === "number"
|
|
858
|
-
? { attempt_count: parseStatusResult.attempt_count }
|
|
859
|
-
: {}),
|
|
860
|
-
},
|
|
861
|
-
},
|
|
862
|
-
}, {
|
|
863
|
-
event_type: "parse.failed",
|
|
864
|
-
run_id: mergeRunId ?? undefined,
|
|
865
|
-
commit_sha: mergeHeadSha,
|
|
866
|
-
});
|
|
867
|
-
await foldToBlocked(`parse-after-merge failed for ${ticketKey}`);
|
|
868
|
-
continue;
|
|
869
|
-
}
|
|
870
|
-
if (parseStatusResult.status === "succeeded") {
|
|
871
|
-
// Terminal parse success — emit a compact parse.succeeded marker and let
|
|
872
|
-
// the original merge.succeeded signal proceed with next_status="done".
|
|
873
|
-
emitConductorEventFn({
|
|
874
|
-
source: PARSE_WAIT_EVENT_SOURCE,
|
|
875
|
-
type: "parse.succeeded",
|
|
876
|
-
subject: ticketKey,
|
|
877
|
-
run_id: mergeRunId,
|
|
878
|
-
worker_id: mergeEvent.worker_id ?? null,
|
|
879
|
-
producer: PARSE_WAIT_EVENT_PRODUCER,
|
|
880
|
-
observed_via: "supervisor",
|
|
881
|
-
time: new Date(nowFn()).toISOString(),
|
|
882
|
-
data: {
|
|
883
|
-
summary: `parse-after-merge succeeded for ${ticketKey}`,
|
|
884
|
-
status: "succeeded",
|
|
885
|
-
reason: "parse_succeeded",
|
|
886
|
-
details: {
|
|
887
|
-
epic_key,
|
|
888
|
-
ticket_key: ticketKey,
|
|
889
|
-
...(mergeHeadSha ? { head_sha: mergeHeadSha } : {}),
|
|
890
|
-
},
|
|
891
|
-
},
|
|
892
|
-
}, {
|
|
893
|
-
event_type: "parse.succeeded",
|
|
894
|
-
run_id: mergeRunId ?? undefined,
|
|
895
|
-
commit_sha: mergeHeadSha,
|
|
896
|
-
});
|
|
897
|
-
log(`[epic-tick] parse-after-merge succeeded for ${ticketKey}; folding merge.succeeded → done`);
|
|
898
|
-
// Do NOT revert: signal.next_status stays "done" (from the merge.succeeded
|
|
899
|
-
// fold) so reconcile CASes the ticket to done.
|
|
900
|
-
continue;
|
|
901
|
-
}
|
|
902
|
-
// status is queued | in_progress | idle. All are NON-terminal for a
|
|
903
|
-
// triggered parse: queued/in_progress are self-evidently still running, and
|
|
904
|
-
// BAPI-527 treats `idle` as unknown/not-yet-terminal — NEVER fold to done
|
|
905
|
-
// from idle (only an explicit `succeeded` does that). Hold at parse_pending.
|
|
906
|
-
holdOrEnterParsePending();
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
// Step 4: Fetch + assert plan integrity (only if fetchPlan injected)
|
|
910
|
-
const fetchPlanFn = deps.fetchPlan;
|
|
911
|
-
let plan = null;
|
|
912
|
-
if (fetchPlanFn !== undefined) {
|
|
913
|
-
try {
|
|
914
|
-
plan = await fetchPlanFn(epic_key, access);
|
|
915
|
-
}
|
|
916
|
-
catch (err) {
|
|
917
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "plan fetch error";
|
|
918
|
-
errorLog(`[epic-tick] plan fetch failed (${safeMsg}) for epic=${epic_key}; fail-closed`);
|
|
919
|
-
await escalateOnce(epic_key, "plan-unavailable");
|
|
920
|
-
exitCode = 1;
|
|
921
|
-
reason = "plan unavailable";
|
|
922
|
-
return {
|
|
923
|
-
run_id: epic_key,
|
|
924
|
-
status: "failed",
|
|
925
|
-
exit_code: exitCode,
|
|
926
|
-
reason,
|
|
927
|
-
last_seq: -1,
|
|
928
|
-
worker_count: workerCount,
|
|
929
|
-
};
|
|
930
|
-
}
|
|
931
|
-
if (plan !== null) {
|
|
932
|
-
const approvedHash = epicRunState.epic_run.approved_plan_hash;
|
|
933
|
-
if (approvedHash !== null && approvedHash !== plan.plan_hash) {
|
|
934
|
-
errorLog(`[epic-tick] plan hash mismatch for epic=${epic_key}; fail-closed (no dispatch, no merge)`);
|
|
935
|
-
await escalateOnce(epic_key, "plan-hash-mismatch");
|
|
936
|
-
exitCode = 1;
|
|
937
|
-
reason = "plan hash mismatch";
|
|
938
|
-
return {
|
|
939
|
-
run_id: epic_key,
|
|
940
|
-
status: "failed",
|
|
941
|
-
exit_code: exitCode,
|
|
942
|
-
reason,
|
|
943
|
-
last_seq: -1,
|
|
944
|
-
worker_count: workerCount,
|
|
945
|
-
};
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
// Step 5: Reconcile observed→desired
|
|
950
|
-
if (plan !== null) {
|
|
951
|
-
// BAPI-441: fetch the effective supervisor config (budget ceilings +
|
|
952
|
-
// liveness window) and setup (pr_bindings) once. Fail-open: if the config
|
|
953
|
-
// read fails, remediationConfig stays undefined and reconcile skips the
|
|
954
|
-
// remediation pass entirely (dispatch/merge steps unaffected).
|
|
955
|
-
//
|
|
956
|
-
// BAPI-487: `prBindings` is retained ONLY for the legacy teardown seam
|
|
957
|
-
// (which needs just the PR number). Both the done-gate observation and the
|
|
958
|
-
// remediation CAS resolve their PR binding via gh-discovery
|
|
959
|
-
// (resolveTicketPrBindingFromGh), never from this map — nothing
|
|
960
|
-
// auto-populates `pr_bindings`, so relying on it stranded remediation.
|
|
961
|
-
let remediationConfig;
|
|
962
|
-
let livenessWindowSeconds = 120;
|
|
963
|
-
let prBindings = {};
|
|
964
|
-
try {
|
|
965
|
-
const cfg = await fetchEffectiveSupervisorConfig(access, epic_key);
|
|
966
|
-
remediationConfig = {
|
|
967
|
-
max_remediation_attempts: cfg.max_remediation_attempts,
|
|
968
|
-
max_remediation_no_progress_attempts: cfg.max_remediation_no_progress_attempts,
|
|
969
|
-
auto_rereview_enabled: cfg.auto_rereview_enabled ?? false,
|
|
970
|
-
teardown_enabled: cfg.teardown_enabled ?? false,
|
|
971
|
-
};
|
|
972
|
-
livenessWindowSeconds = cfg.worker_liveness_window_seconds;
|
|
973
|
-
}
|
|
974
|
-
catch (err) {
|
|
975
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "config error";
|
|
976
|
-
errorLog(`[epic-tick] supervisor-config fetch failed (${safeMsg}); skipping remediation for epic=${epic_key}`);
|
|
977
|
-
}
|
|
978
|
-
if (remediationConfig) {
|
|
979
|
-
try {
|
|
980
|
-
const setup = await fetchEffectiveSupervisorSetup(access, epic_key);
|
|
981
|
-
if (setup.pr_bindings && typeof setup.pr_bindings === "object") {
|
|
982
|
-
prBindings = setup.pr_bindings;
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
catch (err) {
|
|
986
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "setup error";
|
|
987
|
-
errorLog(`[epic-tick] supervisor-setup fetch failed (${safeMsg}); remediation PR resolution degraded for epic=${epic_key}`);
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
// ticket_key → dispatched run_id (the run whose heartbeat liveness reads).
|
|
991
|
-
// Seed from ticket_status.dispatch_run_id, then prefer the most-recent
|
|
992
|
-
// dispatch-ledger run_id per ticket so that after a remediation re-dispatch
|
|
993
|
-
// (a new attempt-scoped epic_dispatch row correlated with the fresh run_id)
|
|
994
|
-
// liveness tracks the NEW worker rather than the stale original.
|
|
995
|
-
const ticketRunIdMap = new Map();
|
|
996
|
-
for (const ts of epicRunState.ticket_statuses) {
|
|
997
|
-
if (ts.dispatch_run_id)
|
|
998
|
-
ticketRunIdMap.set(ts.ticket_key, ts.dispatch_run_id);
|
|
999
|
-
}
|
|
1000
|
-
// BAPI-445: split dispatch records by role. `:review`-suffixed dispatch keys
|
|
1001
|
-
// are the pre-implementation spec re-review runs; they must be EXCLUDED from
|
|
1002
|
-
// the implementation liveness map (so BAPI-441 remediation liveness only ever
|
|
1003
|
-
// targets the implementation run) and tracked in a separate review map +
|
|
1004
|
-
// per-ticket attempt counter consumed by the reviewing recovery branch.
|
|
1005
|
-
const latestDispatchByTicket = new Map();
|
|
1006
|
-
const reviewLatestDispatchByTicket = new Map();
|
|
1007
|
-
const reviewAttemptCounts = new Map();
|
|
1008
|
-
for (const d of epicRunState.dispatches ?? []) {
|
|
1009
|
-
const isReview = d.dispatch_key.endsWith(":review");
|
|
1010
|
-
if (isReview) {
|
|
1011
|
-
reviewAttemptCounts.set(d.ticket_key, (reviewAttemptCounts.get(d.ticket_key) ?? 0) + 1);
|
|
1012
|
-
}
|
|
1013
|
-
if (!d.run_id)
|
|
1014
|
-
continue;
|
|
1015
|
-
const updatedAt = new Date(d.updated_at).getTime();
|
|
1016
|
-
const target = isReview ? reviewLatestDispatchByTicket : latestDispatchByTicket;
|
|
1017
|
-
const prev = target.get(d.ticket_key);
|
|
1018
|
-
if (!prev || updatedAt >= prev.updatedAt) {
|
|
1019
|
-
target.set(d.ticket_key, { runId: d.run_id, updatedAt });
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
for (const [tk, info] of latestDispatchByTicket) {
|
|
1023
|
-
ticketRunIdMap.set(tk, info.runId);
|
|
1024
|
-
}
|
|
1025
|
-
const reviewTicketRunIdMap = new Map();
|
|
1026
|
-
for (const [tk, info] of reviewLatestDispatchByTicket) {
|
|
1027
|
-
reviewTicketRunIdMap.set(tk, info.runId);
|
|
1028
|
-
}
|
|
1029
|
-
// Legacy PR-number-only resolver from `pr_bindings`. BAPI-487: this is now
|
|
1030
|
-
// consumed ONLY by the teardownSeam, which needs just the number and is
|
|
1031
|
-
// outside this ticket's remediation critical path. Both the done-gate
|
|
1032
|
-
// observation and the remediation CAS resolve their PR binding via
|
|
1033
|
-
// gh-discovery (resolveTicketPrBindingFromGh / resolvePrBinding) instead,
|
|
1034
|
-
// because nothing auto-populates `pr_bindings` (confirmed NULL for repo
|
|
1035
|
-
// `bapi`), so this legacy path always returns null. Teardown is left on it
|
|
1036
|
-
// deliberately rather than silently migrated.
|
|
1037
|
-
const resolvePrNumber = (ticketKey) => {
|
|
1038
|
-
const raw = prBindings[ticketKey];
|
|
1039
|
-
if (typeof raw === "number" && Number.isInteger(raw) && raw >= 1)
|
|
1040
|
-
return raw;
|
|
1041
|
-
if (raw && typeof raw === "object") {
|
|
1042
|
-
const obj = raw;
|
|
1043
|
-
const pr = obj.pr_number ?? obj.pr;
|
|
1044
|
-
if (typeof pr === "number" && Number.isInteger(pr) && pr >= 1)
|
|
1045
|
-
return pr;
|
|
1046
|
-
}
|
|
1047
|
-
return null;
|
|
1048
|
-
};
|
|
1049
|
-
// gh-discovery PR binding used by BOTH the done-gate pass and the
|
|
1050
|
-
// remediation CAS (BAPI-487 Requirement 1). Delegates to the shared
|
|
1051
|
-
// `resolveTicketPrBindingFromGh` helper so the two seams cannot diverge; it
|
|
1052
|
-
// resolves the number AND the current head SHA from `feature/<KEY>` and
|
|
1053
|
-
// fail-closes unless the PR is OPEN with a well-formed number + head SHA.
|
|
1054
|
-
const resolvePrBinding = (ticketKey) => resolveTicketPrBindingFromGh(ticketKey, { cwd: process.cwd() });
|
|
1055
|
-
// ---------------------------------------------------------------------
|
|
1056
|
-
// Step 4.5: Conductor-driven done-gate for ready_for_review tickets
|
|
1057
|
-
// (FINDING 6, BAPI-463) — the correctness backstop for the hands-off run.
|
|
1058
|
-
//
|
|
1059
|
-
// Workers do not reliably self-emit `gate.met` (a ticket can reach
|
|
1060
|
-
// ready_for_review via `run.stopped` alone), so the merge enqueue — gated on
|
|
1061
|
-
// `gate.met` only — would stall forever awaiting a worker signal. Here the
|
|
1062
|
-
// CONDUCTOR evaluates the composite done-gate itself via the existing
|
|
1063
|
-
// `observePrCiOnce`, which binds to the resolved CURRENT head SHA, evaluates
|
|
1064
|
-
// the pure fail-closed done-gate (required-CI green + current-head review
|
|
1065
|
-
// verdict), and idempotently emits `gate.met` (deduped by ticket+PR+head_sha)
|
|
1066
|
-
// so this tick or the next one folds it and enqueues the merge exactly once.
|
|
1067
|
-
// Worker-emitted `gate.met` stays a valid fast-path; this pass never removes it.
|
|
1068
|
-
// The pass is best-effort and fully fail-closed: an observation error is
|
|
1069
|
-
// caught per-ticket so it can never crash or block the reconcile loop, and
|
|
1070
|
-
// `observePrCiOnce` emits nothing on an unavailable/ambiguous/stale-head signal.
|
|
1071
|
-
// run_id → worker_id from the ledger (first worker_id seen per run) so the
|
|
1072
|
-
// conductor-emitted gate.met carries the real worker's id for ATTRIBUTION.
|
|
1073
|
-
// BAPI-525 Change A: merge eligibility no longer depends on worker_id, so an
|
|
1074
|
-
// unresolved worker maps to `null` (real attribution or nothing) — the old
|
|
1075
|
-
// synthetic `conductor:${tk}` fallback existed only to satisfy the now-removed
|
|
1076
|
-
// merge-identity presence check and is no longer needed.
|
|
1077
|
-
const runIdToWorkerId = new Map();
|
|
1078
|
-
for (const ev of localEvents) {
|
|
1079
|
-
if (ev.run_id && ev.worker_id && !runIdToWorkerId.has(ev.run_id)) {
|
|
1080
|
-
runIdToWorkerId.set(ev.run_id, ev.worker_id);
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
const resolveTicketRunId = (tk) => ticketRunIdMap.get(tk) ?? latestDispatchByTicket.get(tk)?.runId ?? null;
|
|
1084
|
-
const resolveDoneGateWorkerId = (tk) => {
|
|
1085
|
-
const rid = resolveTicketRunId(tk);
|
|
1086
|
-
if (rid && runIdToWorkerId.has(rid))
|
|
1087
|
-
return runIdToWorkerId.get(rid);
|
|
1088
|
-
return null;
|
|
1089
|
-
};
|
|
1090
|
-
// BAPI-525 Change A: durable worker attribution for a `gate.met` that carries
|
|
1091
|
-
// no worker_id (e.g. the autonomous git-hook chain). Used ONLY to stamp the
|
|
1092
|
-
// emitted `merge.*` ledger events for audit — NEVER a merge gate. Resolves via
|
|
1093
|
-
// the event's run_id, else the event subject's implementation dispatch run,
|
|
1094
|
-
// else null (a null attribution is tolerated end-to-end).
|
|
1095
|
-
const resolveWorkerIdForGateEvent = (event, _identity) => {
|
|
1096
|
-
const directRid = typeof event.run_id === "string" && event.run_id.trim().length > 0
|
|
1097
|
-
? event.run_id
|
|
1098
|
-
: null;
|
|
1099
|
-
const rid = directRid ??
|
|
1100
|
-
(typeof event.subject === "string" && event.subject.trim().length > 0
|
|
1101
|
-
? resolveTicketRunId(event.subject)
|
|
1102
|
-
: null);
|
|
1103
|
-
if (rid && runIdToWorkerId.has(rid))
|
|
1104
|
-
return runIdToWorkerId.get(rid);
|
|
1105
|
-
return null;
|
|
1106
|
-
};
|
|
1107
|
-
// BAPI-525 Change B: resolve the per-run dispatched-backstop policy (default
|
|
1108
|
-
// OFF). When enabled, the done-gate pass ALSO admits dispatched/running
|
|
1109
|
-
// tickets, gated by quiescence. Invert the impl-dispatch maps so ledger
|
|
1110
|
-
// events can be attributed back to a ticket for local-first PR binding.
|
|
1111
|
-
const dispatchedBackstopPolicy = resolveDispatchedBackstopPolicy(epicRunState.epic_run.policy_json);
|
|
1112
|
-
// BAPI-586/BAPI-1127: resolve the run's EFFECTIVE base branch so the
|
|
1113
|
-
// done-gate pass can catch a wrong-base PR (one not targeting the run
|
|
1114
|
-
// base) at reconciliation time — the backstop to the executor's own
|
|
1115
|
-
// finalization guard.
|
|
1116
|
-
//
|
|
1117
|
-
// BAPI-1127 moved branch-name validation out of the shared declaration
|
|
1118
|
-
// resolver and into this operational wrapper, so this call site now owns
|
|
1119
|
-
// the fail-closed disposition it used to inherit. It fails CLOSED: when
|
|
1120
|
-
// the declared base is not a usable ref the pass is SKIPPED entirely
|
|
1121
|
-
// rather than run with the base comparison silently disabled. A pass that
|
|
1122
|
-
// cannot verify a PR's base cannot honestly admit one as done, and the
|
|
1123
|
-
// wrong-base PR this check exists to catch is exactly what would slip
|
|
1124
|
-
// through. The skip happens BEFORE any PR binding resolution, CI
|
|
1125
|
-
// observation, or provider call, and reports only the failed rule.
|
|
1126
|
-
const runBaseResolution = resolveEffectiveRunBaseBranch(epicRunState.epic_run.policy_json);
|
|
1127
|
-
if (!runBaseResolution.ok) {
|
|
1128
|
-
errorLog(`[epic-tick] done-gate pass skipped for ${epic_key}: ${runBaseResolution.error}`);
|
|
1129
|
-
}
|
|
1130
|
-
const doneGateExpectedBaseBranch = runBaseResolution.ok
|
|
1131
|
-
? runBaseResolution.effectiveBaseBranch
|
|
1132
|
-
: undefined;
|
|
1133
|
-
const ticketForRunId = new Map();
|
|
1134
|
-
for (const [tk, rid] of ticketRunIdMap)
|
|
1135
|
-
ticketForRunId.set(rid, tk);
|
|
1136
|
-
for (const [tk, info] of latestDispatchByTicket)
|
|
1137
|
-
ticketForRunId.set(info.runId, tk);
|
|
1138
|
-
const resolveActivePrBinding = buildTicketPrBindingResolver({
|
|
1139
|
-
events: localEvents,
|
|
1140
|
-
resolveTicketForRunId: (rid) => ticketForRunId.get(rid) ?? null,
|
|
1141
|
-
resolveFromGh: resolvePrBinding,
|
|
1142
|
-
});
|
|
1143
|
-
const resolveActiveTicketQuiescence = buildActiveTicketQuiescenceResolver({
|
|
1144
|
-
events: localEvents,
|
|
1145
|
-
nowMs: nowFn(),
|
|
1146
|
-
policy: dispatchedBackstopPolicy,
|
|
1147
|
-
resolveImplRunId: resolveTicketRunId,
|
|
1148
|
-
});
|
|
1149
|
-
if (runBaseResolution.ok) {
|
|
1150
|
-
await runConductorDoneGatePass(observed.ticket_statuses, {
|
|
1151
|
-
observePrCi: observePrCiSeamFn,
|
|
1152
|
-
// BAPI-586: the run base so the done-gate pass fails a wrong-base PR
|
|
1153
|
-
// before CI/review evaluation (reconciliation backstop to executor
|
|
1154
|
-
// finalization).
|
|
1155
|
-
expectedBaseBranch: doneGateExpectedBaseBranch,
|
|
1156
|
-
resolvePrBinding,
|
|
1157
|
-
// BAPI-525 Change B: local-first binding + quiescence gate for the new
|
|
1158
|
-
// dispatched/running admission (policy default OFF ⇒ no behavior change).
|
|
1159
|
-
resolveActivePrBinding,
|
|
1160
|
-
dispatchedBackstopPolicy,
|
|
1161
|
-
resolveActiveTicketQuiescence,
|
|
1162
|
-
// BAPI-487: re-evaluate a blocked ticket only when its PR head advanced
|
|
1163
|
-
// past the head recorded on its latest blocking signal.
|
|
1164
|
-
resolveBlockedHeadSha: (tk) => observed.ticket_blocked_heads?.get(tk) ?? null,
|
|
1165
|
-
resolveRunId: resolveTicketRunId,
|
|
1166
|
-
resolveWorkerId: resolveDoneGateWorkerId,
|
|
1167
|
-
// BAPI-494: convert a detected conflict into a durable, head-scoped
|
|
1168
|
-
// `merge.conflict` ledger event stamped with the ticket's dispatch run/worker
|
|
1169
|
-
// so the fold correlates it and the remediation pass redispatches. Emitted via
|
|
1170
|
-
// the shared injectable emitter, idempotent per conflict head. Folded next tick
|
|
1171
|
-
// (this pass runs after rebuildObservedState), matching the gate.met latency.
|
|
1172
|
-
emitConflictSignal: (input) => {
|
|
1173
|
-
emitConductorEventFn({
|
|
1174
|
-
source: MERGE_CONFLICT_EVENT_SOURCE,
|
|
1175
|
-
type: "merge.conflict",
|
|
1176
|
-
subject: input.ticketKey,
|
|
1177
|
-
run_id: input.runId,
|
|
1178
|
-
worker_id: input.workerId,
|
|
1179
|
-
producer: MERGE_CONFLICT_EVENT_PRODUCER,
|
|
1180
|
-
observed_via: "supervisor",
|
|
1181
|
-
time: new Date(nowFn()).toISOString(),
|
|
1182
|
-
data: {
|
|
1183
|
-
summary: `PR #${input.prNumber} for ${input.ticketKey} is not mergeable`,
|
|
1184
|
-
status: "blocked",
|
|
1185
|
-
reason: "merge.conflict",
|
|
1186
|
-
details: {
|
|
1187
|
-
epic_key,
|
|
1188
|
-
ticket_key: input.ticketKey,
|
|
1189
|
-
repo: input.repoName,
|
|
1190
|
-
pr_number: input.prNumber,
|
|
1191
|
-
head_sha: input.headSha,
|
|
1192
|
-
mergeable: input.mergeable,
|
|
1193
|
-
mergeStateStatus: input.mergeStateStatus,
|
|
1194
|
-
},
|
|
1195
|
-
},
|
|
1196
|
-
}, {
|
|
1197
|
-
event_type: "merge.conflict",
|
|
1198
|
-
run_id: input.runId ?? undefined,
|
|
1199
|
-
commit_sha: input.headSha,
|
|
1200
|
-
});
|
|
1201
|
-
},
|
|
1202
|
-
access,
|
|
1203
|
-
env,
|
|
1204
|
-
log,
|
|
1205
|
-
errorLog,
|
|
1206
|
-
});
|
|
1207
|
-
}
|
|
1208
|
-
const maxSeqForRun = (runId) => {
|
|
1209
|
-
let maxSeq = 0;
|
|
1210
|
-
for (const ev of localEvents) {
|
|
1211
|
-
if (ev.run_id === runId && ev.seq > maxSeq)
|
|
1212
|
-
maxSeq = ev.seq;
|
|
1213
|
-
}
|
|
1214
|
-
return maxSeq;
|
|
1215
|
-
};
|
|
1216
|
-
const reconcileDeps = {
|
|
1217
|
-
casTicketStatus: async (ek, tk, rowVersion, nextStatus, planVersion) => advanceEpicTicketStatus(access, {
|
|
1218
|
-
epicKey: ek,
|
|
1219
|
-
ticketKey: tk,
|
|
1220
|
-
expectedRowVersion: rowVersion,
|
|
1221
|
-
nextStatus,
|
|
1222
|
-
planVersion,
|
|
1223
|
-
}),
|
|
1224
|
-
seedTicketStatus: async (_ek, tk, planVersion) => {
|
|
1225
|
-
// Legacy seam: live Conductor v2 initial seeding now occurs in the
|
|
1226
|
-
// Python approve-plan DAL workflow (`approve_epic_plan()`, BAPI-633),
|
|
1227
|
-
// which seeds every plan node before the run is activated. This seam
|
|
1228
|
-
// is retained unchanged as frozen-v1 safety behavior.
|
|
1229
|
-
//
|
|
1230
|
-
// A6/BAPI-507: address the run by its concrete epic_run_id — the
|
|
1231
|
-
// endpoint path is /runs/{epic_run_id}/tickets. Passing the UUID (not
|
|
1232
|
-
// the Jira epic key `_ek`) skips the epic-key→active-run resolution and
|
|
1233
|
-
// its multi-active-run CONFLICT edge. The backend read-back makes a
|
|
1234
|
-
// re-seed of an existing row a clean 2xx no-op.
|
|
1235
|
-
await createEpicTicketStatus(access, {
|
|
1236
|
-
epicKey: epicRunState.epic_run.epic_run_id,
|
|
1237
|
-
ticketKey: tk,
|
|
1238
|
-
status: "planned",
|
|
1239
|
-
planVersion,
|
|
1240
|
-
});
|
|
1241
|
-
},
|
|
1242
|
-
claimDispatchKey: async (ek, tk, planVersion, role, attempt = 0) => {
|
|
1243
|
-
// FINDING 1 (BAPI-463): in dry-run mode, DO NOT persist a real dispatch
|
|
1244
|
-
// claim. Return a synthetic "claimed" result (run_id null) so the reconcile
|
|
1245
|
-
// pass proceeds to resolve the command + model routing (still exercised) but
|
|
1246
|
-
// no authoritative `run_spawned` row is written under the real dispatch_key.
|
|
1247
|
-
if (isDryRun) {
|
|
1248
|
-
const suffix = `${role === "review" ? ":review" : ""}${attempt > 0 ? `:r${attempt}` : ""}`;
|
|
1249
|
-
const nowIso = new Date(nowFn()).toISOString();
|
|
1250
|
-
log(`[DRY RUN] claiming dispatch key skipped for ${tk} (epic=${ek}, role=${role ?? "implementation"}, attempt=${attempt}); no run_spawned row persisted`);
|
|
1251
|
-
return {
|
|
1252
|
-
ok: true,
|
|
1253
|
-
kind: "claimed",
|
|
1254
|
-
dispatch: {
|
|
1255
|
-
dispatch_key: `dry-run:${ek}:${tk}:v${planVersion}${suffix}`,
|
|
1256
|
-
epic_run_id: ek,
|
|
1257
|
-
ticket_key: tk,
|
|
1258
|
-
plan_version: planVersion,
|
|
1259
|
-
status: "pending",
|
|
1260
|
-
run_id: null,
|
|
1261
|
-
lease_owner: lease_owner,
|
|
1262
|
-
lease_expires_at: null,
|
|
1263
|
-
created_at: nowIso,
|
|
1264
|
-
updated_at: nowIso,
|
|
1265
|
-
},
|
|
1266
|
-
};
|
|
1267
|
-
}
|
|
1268
|
-
return recordEpicDispatch(access, {
|
|
1269
|
-
epicKey: ek,
|
|
1270
|
-
ticketKey: tk,
|
|
1271
|
-
planVersion,
|
|
1272
|
-
leaseOwner: lease_owner,
|
|
1273
|
-
ttlSeconds: DEFAULT_DISPATCH_KEY_TTL_SECONDS,
|
|
1274
|
-
attempt,
|
|
1275
|
-
// BAPI-445: a review-role claim appends ":review" to the dispatch key
|
|
1276
|
-
// so the run-id maps above can separate review runs from impl runs.
|
|
1277
|
-
reviewRole: role === "review",
|
|
1278
|
-
});
|
|
1279
|
-
},
|
|
1280
|
-
// BAPI-445 spec re-review seams. dispatchReviewSeam is wired only when the
|
|
1281
|
-
// factory provides it (gate stays off otherwise); the liveness + attempt
|
|
1282
|
-
// accessors read the review-scoped maps built above.
|
|
1283
|
-
dispatchReviewSeam: dispatchReviewSeamFn
|
|
1284
|
-
? async (ek, tk, attempt = 0) => dispatchReviewSeamFn(ek, tk, attempt)
|
|
1285
|
-
: undefined,
|
|
1286
|
-
readReviewWorkerLiveness: async (_ek, tk) => {
|
|
1287
|
-
const runId = reviewTicketRunIdMap.get(tk);
|
|
1288
|
-
if (!runId)
|
|
1289
|
-
return { alive: false, workerId: null };
|
|
1290
|
-
return extractWorkerLiveness(localEvents, runId, nowFn(), livenessWindowSeconds);
|
|
1291
|
-
},
|
|
1292
|
-
countReviewAttempts: (tk) => reviewAttemptCounts.get(tk) ?? 0,
|
|
1293
|
-
correlateRunId: async (dispatchKey, runId) => {
|
|
1294
|
-
// FINDING 1 (BAPI-463): dry-run must not transition the dispatch row to
|
|
1295
|
-
// `run_spawned`. Skipping this keeps the real dispatch_key un-claimed so a
|
|
1296
|
-
// subsequent real tick spawns the worker instead of hitting `already-spawned`.
|
|
1297
|
-
if (isDryRun) {
|
|
1298
|
-
log(`[DRY RUN] correlate run_id skipped for dispatch_key=${dispatchKey} (run_id=${runId}); no run_spawned transition persisted`);
|
|
1299
|
-
return;
|
|
1300
|
-
}
|
|
1301
|
-
await transitionEpicDispatch(access, {
|
|
1302
|
-
dispatchKey,
|
|
1303
|
-
nextStatus: "run_spawned",
|
|
1304
|
-
runId,
|
|
1305
|
-
});
|
|
1306
|
-
},
|
|
1307
|
-
dispatchSeam: async (ek, tk, attempt = 0) => dispatchSeam(ek, tk, attempt),
|
|
1308
|
-
processMerge: async (acc, event) => {
|
|
1309
|
-
// F4: when policy_json.local_merge.enabled is set (opt-in, default OFF)
|
|
1310
|
-
// and the caller did not inject a processMerge stub, run the real merge
|
|
1311
|
-
// pipeline with a LOCAL executor swapped in for the backend route — the
|
|
1312
|
-
// merge happens here using the agent's own `gh` credentials, so the
|
|
1313
|
-
// hosted backend never needs global GitHub write scope. Otherwise the
|
|
1314
|
-
// default backend-route path is unchanged for all existing users.
|
|
1315
|
-
if (deps.processMerge === undefined) {
|
|
1316
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1317
|
-
const localCfg = epicRunState.epic_run.policy_json?.local_merge;
|
|
1318
|
-
if (localCfg?.enabled === true) {
|
|
1319
|
-
return processGateMetMerge(acc, event, {
|
|
1320
|
-
merge: makeLocalMergeExecutor({
|
|
1321
|
-
method: resolveLocalMergeMethod(localCfg.method),
|
|
1322
|
-
approvalRequired: localCfg.approval_required === true,
|
|
1323
|
-
},
|
|
1324
|
-
// BAPI-1136: `env` now supplies only the allowlisted
|
|
1325
|
-
// operational base; the identity is the explicitly configured
|
|
1326
|
-
// local credential, and an unconfigured one fails closed with
|
|
1327
|
-
// `local_merge_credential_missing` rather than borrowing the
|
|
1328
|
-
// ambient `gh` login this path used to rely on.
|
|
1329
|
-
{
|
|
1330
|
-
env: process.env,
|
|
1331
|
-
credential: resolveLocalMergeCredential(process.env, "local"),
|
|
1332
|
-
}),
|
|
1333
|
-
// BAPI-525 Change A: durable attribution for a worker_id-less gate.met.
|
|
1334
|
-
resolveWorkerIdForGateEvent,
|
|
1335
|
-
});
|
|
1336
|
-
}
|
|
1337
|
-
// Default (backend-route) path, with durable merge attribution wired in.
|
|
1338
|
-
return processGateMetMerge(acc, event, { resolveWorkerIdForGateEvent });
|
|
1339
|
-
}
|
|
1340
|
-
return processMergeFn(acc, event);
|
|
1341
|
-
},
|
|
1342
|
-
postActionWaitSeam: async (ek, tk) => postActionWaitSeam(ek, tk),
|
|
1343
|
-
escalateOnce: async (ek, reason) => escalateOnce(ek, reason),
|
|
1344
|
-
log,
|
|
1345
|
-
// BAPI-442: teardown and Jira-transition seams (fail-open, optional).
|
|
1346
|
-
teardownSeam: async (_ek, tk) => {
|
|
1347
|
-
// Resolve the PR number for the ticket.
|
|
1348
|
-
const prNumber = resolvePrNumber(tk);
|
|
1349
|
-
if (prNumber === null) {
|
|
1350
|
-
errorLog(`[epic-tick] teardown: no PR binding for ${tk}; skipping`);
|
|
1351
|
-
return;
|
|
1352
|
-
}
|
|
1353
|
-
// Fetch setup to get the expected head SHA if available; fall back to empty.
|
|
1354
|
-
let expectedSha = "";
|
|
1355
|
-
try {
|
|
1356
|
-
const setup = await fetchEffectiveSupervisorSetup(access, epic_key);
|
|
1357
|
-
const binding = (setup.pr_bindings ?? {})[tk];
|
|
1358
|
-
if (binding && typeof binding === "object") {
|
|
1359
|
-
const b = binding;
|
|
1360
|
-
if (typeof b.head_sha === "string")
|
|
1361
|
-
expectedSha = b.head_sha;
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
catch {
|
|
1365
|
-
// Best-effort; proceed with empty SHA (endpoint still deletes by PR number)
|
|
1366
|
-
}
|
|
1367
|
-
try {
|
|
1368
|
-
await deletePullRequestBranch(access, prNumber, expectedSha || "");
|
|
1369
|
-
log(`[epic-tick] teardown: branch deleted for PR #${prNumber} (ticket=${tk})`);
|
|
1370
|
-
}
|
|
1371
|
-
catch (err) {
|
|
1372
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "error";
|
|
1373
|
-
errorLog(`[epic-tick] teardown: branch-delete failed (${safeMsg}) for ${tk}`);
|
|
1374
|
-
}
|
|
1375
|
-
// Remove local worktree idempotently; errors are benign.
|
|
1376
|
-
try {
|
|
1377
|
-
spawnSync("git", ["worktree", "remove", "--force", tk], { stdio: "ignore" });
|
|
1378
|
-
log(`[epic-tick] teardown: worktree removed for ${tk}`);
|
|
1379
|
-
}
|
|
1380
|
-
catch {
|
|
1381
|
-
// Already removed or never created — idempotent skip.
|
|
1382
|
-
}
|
|
1383
|
-
},
|
|
1384
|
-
jiraTransitionSeam: async (_ek, tk) => {
|
|
1385
|
-
try {
|
|
1386
|
-
const result = await transitionJiraStatus(access, tk, "auto");
|
|
1387
|
-
if (result.status === "skipped") {
|
|
1388
|
-
log(`[epic-tick] jira-transition: no matching transition for ${tk} (skipped)`);
|
|
1389
|
-
}
|
|
1390
|
-
else {
|
|
1391
|
-
log(`[epic-tick] jira-transition: transitioned ${tk}`);
|
|
1392
|
-
}
|
|
1393
|
-
}
|
|
1394
|
-
catch (err) {
|
|
1395
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "error";
|
|
1396
|
-
errorLog(`[epic-tick] jira-transition failed (${safeMsg}) for ${tk}`);
|
|
1397
|
-
}
|
|
1398
|
-
},
|
|
1399
|
-
// BAPI-441 remediation seams.
|
|
1400
|
-
readWorkerLiveness: async (_ek, tk) => {
|
|
1401
|
-
const runId = ticketRunIdMap.get(tk);
|
|
1402
|
-
if (!runId)
|
|
1403
|
-
return { alive: false, workerId: null };
|
|
1404
|
-
return extractWorkerLiveness(localEvents, runId, nowFn(), livenessWindowSeconds);
|
|
1405
|
-
},
|
|
1406
|
-
remediateCas: async (ek, tk, attemptKind, reason) => {
|
|
1407
|
-
// BAPI-487 Requirement 1: resolve the PR number + head SHA via the same
|
|
1408
|
-
// gh-discovery the done-gate pass uses, NOT the never-populated
|
|
1409
|
-
// `pr_bindings` map (which stranded remediation on `remediate: no PR
|
|
1410
|
-
// binding`). resolvePrBinding returns both the number and the current
|
|
1411
|
-
// head SHA, so the separate legacy review-status head-SHA fetch is gone.
|
|
1412
|
-
const prBinding = resolvePrBinding(tk);
|
|
1413
|
-
if (prBinding === null) {
|
|
1414
|
-
throw new Error(`remediate: no PR binding for ${tk}`);
|
|
1415
|
-
}
|
|
1416
|
-
const prNumber = prBinding.prNumber;
|
|
1417
|
-
const headSha = prBinding.headSha;
|
|
1418
|
-
// BAPI-500: remediation runs AFTER the fold step in the SAME reconcile
|
|
1419
|
-
// pass. When this ticket folded to `blocked` this tick, the block CAS
|
|
1420
|
-
// already bumped its row_version to snapshot+1, so prefer the confirmed
|
|
1421
|
-
// same-pass post-fold version; fall back to the tick-start snapshot when
|
|
1422
|
-
// the ticket was not folded this tick, then to 0. Sending the stale
|
|
1423
|
-
// tick-start snapshot is exactly the deterministic 400 loop this fixes.
|
|
1424
|
-
const rowVersion = observed.ticket_post_fold_row_versions?.get(tk) ??
|
|
1425
|
-
observed.ticket_row_versions.get(tk) ??
|
|
1426
|
-
0;
|
|
1427
|
-
// Deterministic block-state idempotency key: stable for a given durable
|
|
1428
|
-
// row_version so a same-tick retry replays (409, swallowed); advances
|
|
1429
|
-
// with the next attempt. Derived from the SAME local `rowVersion` sent
|
|
1430
|
-
// as `expected_row_version` so the key and the CAS token stay in lockstep.
|
|
1431
|
-
const idempotencyKey = `remediate:${ek}:${tk}:${rowVersion}`;
|
|
1432
|
-
const result = await remediateEpicTicket(access, {
|
|
1433
|
-
pr_number: prNumber,
|
|
1434
|
-
epic_run_id: ek,
|
|
1435
|
-
ticket_key: tk,
|
|
1436
|
-
expected_row_version: rowVersion,
|
|
1437
|
-
head_sha: headSha,
|
|
1438
|
-
idempotency_key: idempotencyKey,
|
|
1439
|
-
attempt_kind: attemptKind,
|
|
1440
|
-
reason,
|
|
1441
|
-
});
|
|
1442
|
-
if (result.conflict) {
|
|
1443
|
-
return { conflict: true, reviewDigest: null, truncated: false };
|
|
1444
|
-
}
|
|
1445
|
-
return {
|
|
1446
|
-
conflict: false,
|
|
1447
|
-
reviewDigest: result.response.review_digest,
|
|
1448
|
-
truncated: result.response.truncated,
|
|
1449
|
-
};
|
|
1450
|
-
},
|
|
1451
|
-
sendNudge: async (_ek, tk, attempt, reviewDigest, truncated, reason, workerId) => {
|
|
1452
|
-
const runId = ticketRunIdMap.get(tk);
|
|
1453
|
-
if (!runId)
|
|
1454
|
-
throw new Error(`nudge: no run_id for ${tk}`);
|
|
1455
|
-
// workerId is resolved by readWorkerLiveness from the same heartbeat
|
|
1456
|
-
// scan and null-checked by the reconcile pass before remediateCas, so
|
|
1457
|
-
// the two seams stay consistent and no budget is burned on a missing id.
|
|
1458
|
-
const input = buildSupervisorRemediationWorkerMessage({
|
|
1459
|
-
runId,
|
|
1460
|
-
workerId,
|
|
1461
|
-
ticketKey: tk,
|
|
1462
|
-
reason,
|
|
1463
|
-
attempt,
|
|
1464
|
-
reviewDigest: reviewDigest ?? "",
|
|
1465
|
-
truncated,
|
|
1466
|
-
causeSeq: maxSeqForRun(runId),
|
|
1467
|
-
});
|
|
1468
|
-
sendWorkerMessage(input);
|
|
1469
|
-
},
|
|
1470
|
-
resumeDispatch: async (ek, tk, attempt) => {
|
|
1471
|
-
// Claim an attempt-scoped pending dispatch row FIRST so the spawn's
|
|
1472
|
-
// run_spawned correlation (inside orchestrateStartTickets) has a row to
|
|
1473
|
-
// transition and the re-dispatched run_id is durably recorded against
|
|
1474
|
-
// the ticket. The claim is idempotent (lease-held/already-spawned are
|
|
1475
|
-
// returned, not thrown).
|
|
1476
|
-
await recordEpicDispatch(access, {
|
|
1477
|
-
epicKey: ek,
|
|
1478
|
-
ticketKey: tk,
|
|
1479
|
-
planVersion: plan.plan_version,
|
|
1480
|
-
leaseOwner: lease_owner,
|
|
1481
|
-
ttlSeconds: DEFAULT_DISPATCH_KEY_TTL_SECONDS,
|
|
1482
|
-
attempt,
|
|
1483
|
-
});
|
|
1484
|
-
// dispatchSeam returns the new run_id; orchestrate correlates it into
|
|
1485
|
-
// the attempt-scoped epic_dispatch row, so the next tick's liveness map
|
|
1486
|
-
// (built from the dispatch ledger) tracks the fresh worker.
|
|
1487
|
-
await dispatchSeam(ek, tk, attempt);
|
|
1488
|
-
},
|
|
1489
|
-
// BAPI-654 (T2): wire the backend per-ticket commit-watermark gate into the
|
|
1490
|
-
// reconcile pass. Absent runtime seam ⇒ undefined ⇒ gate disabled (legacy).
|
|
1491
|
-
checkShadowFreshness: deps.checkShadowFreshness
|
|
1492
|
-
? (tk) => deps.checkShadowFreshness(access, observed.epic_key, tk)
|
|
1493
|
-
: undefined,
|
|
1494
|
-
};
|
|
1495
|
-
const reconcileResult = await reconcileEpic(access, observed, plan, reconcileDeps, remediationConfig);
|
|
1496
|
-
log(`[epic-tick] reconcile done: epic=${epic_key} ` +
|
|
1497
|
-
`signals=${reconcileResult.signals_folded} ` +
|
|
1498
|
-
`dispatched=${reconcileResult.dispatched} ` +
|
|
1499
|
-
`merges=${reconcileResult.merges_actioned}`);
|
|
1500
|
-
for (const w of reconcileResult.warnings) {
|
|
1501
|
-
errorLog(`[epic-tick] warning: ${w}`);
|
|
1502
|
-
}
|
|
1503
|
-
// Step 5.5 (N-3 / BAPI-507): self-complete the run once every approved-plan
|
|
1504
|
-
// ticket is durably `done`. Deferred while any terminal signal folded THIS
|
|
1505
|
-
// tick is still unpersisted (`unfolded_terminal_signals`) so the run closes
|
|
1506
|
-
// on a SUBSEQUENT tick — after Postgres durably reflects all-done — rather
|
|
1507
|
-
// than from a same-tick local projection. Fail-open: a stale CAS (a
|
|
1508
|
-
// concurrent terminal transition already closed the run, or the top-of-tick
|
|
1509
|
-
// terminal guard will) is bounded operational noise, never a tick failure.
|
|
1510
|
-
if (shouldSelfCompleteEpicRun(plan, observed) &&
|
|
1511
|
-
observed.unfolded_terminal_signals.length === 0) {
|
|
1512
|
-
try {
|
|
1513
|
-
await completeEpicRunFn(access, epicRunState.epic_run.epic_run_id);
|
|
1514
|
-
log(`[epic-tick] epic=${epic_key} self-completed: all plan tickets done`);
|
|
1515
|
-
}
|
|
1516
|
-
catch (err) {
|
|
1517
|
-
errorLog(`[epic-tick] self-completion CAS failed for epic=${epic_key}: ` +
|
|
1518
|
-
`${safeDiagnosticMessage(err, "self-complete error")}`);
|
|
1519
|
-
}
|
|
1520
|
-
}
|
|
1521
|
-
}
|
|
1522
|
-
else {
|
|
1523
|
-
log(`[epic-tick] no plan available for epic=${epic_key}; skipping dispatch and merge steps`);
|
|
1524
|
-
}
|
|
1525
|
-
// Step 6: Budget / dead-state check
|
|
1526
|
-
const epicRun = epicRunState.epic_run;
|
|
1527
|
-
if (epicRun.budget_wall_clock_seconds !== null &&
|
|
1528
|
-
epicRun.consumed_wall_clock_seconds !== null) {
|
|
1529
|
-
const elapsedMs = nowFn() - startMs;
|
|
1530
|
-
const consumedTotalMs = epicRun.consumed_wall_clock_seconds * 1000 + elapsedMs;
|
|
1531
|
-
if (consumedTotalMs > epicRun.budget_wall_clock_seconds * 1000) {
|
|
1532
|
-
errorLog(`[epic-tick] wall-clock budget exhausted for epic=${epic_key}`);
|
|
1533
|
-
await escalateOnce(epic_key, "budget-exhausted");
|
|
1534
|
-
exitCode = 1;
|
|
1535
|
-
reason = "budget exhausted";
|
|
1536
|
-
}
|
|
1537
|
-
}
|
|
1538
|
-
return {
|
|
1539
|
-
run_id: epic_key,
|
|
1540
|
-
status: exitCode === 0 ? "complete" : "failed",
|
|
1541
|
-
exit_code: exitCode,
|
|
1542
|
-
reason,
|
|
1543
|
-
last_seq: -1,
|
|
1544
|
-
worker_count: workerCount,
|
|
1545
|
-
};
|
|
1546
|
-
}
|
|
1547
|
-
catch (err) {
|
|
1548
|
-
const safeMsg = err instanceof Error ? err.constructor.name : "runtime error";
|
|
1549
|
-
errorLog(`[epic-tick] unexpected error (${safeMsg}) for epic=${epic_key}`);
|
|
1550
|
-
exitCode = 2;
|
|
1551
|
-
reason = "unexpected runtime error";
|
|
1552
|
-
return {
|
|
1553
|
-
run_id: epic_key,
|
|
1554
|
-
status: "failed",
|
|
1555
|
-
exit_code: exitCode,
|
|
1556
|
-
reason,
|
|
1557
|
-
last_seq: -1,
|
|
1558
|
-
worker_count: workerCount,
|
|
1559
|
-
};
|
|
1560
|
-
}
|
|
1561
|
-
finally {
|
|
1562
|
-
// Step 7: Release the lease unconditionally
|
|
1563
|
-
if (leaseAcquired) {
|
|
1564
|
-
if (releaseLease !== undefined) {
|
|
1565
|
-
try {
|
|
1566
|
-
await releaseLease(epic_key);
|
|
1567
|
-
log(`[epic-tick] lease released for epic=${epic_key}`);
|
|
1568
|
-
}
|
|
1569
|
-
catch {
|
|
1570
|
-
// Best-effort; TTL expiry is the fallback
|
|
1571
|
-
}
|
|
1572
|
-
}
|
|
1573
|
-
else {
|
|
1574
|
-
log(`[epic-tick] lease will expire via TTL for epic=${epic_key}`);
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
}
|
|
1579
|
-
/**
|
|
1580
|
-
* BAPI-586/BAPI-1127: resolve the epic run's EFFECTIVE base branch — the branch
|
|
1581
|
-
* every fresh dispatch cuts from and every child PR targets.
|
|
1582
|
-
*
|
|
1583
|
-
* Two layers, deliberately kept apart:
|
|
1584
|
-
*
|
|
1585
|
-
* 1. DECLARATION, delegated in full to the dependency-free
|
|
1586
|
-
* {@link resolveDeclaredRunBaseBranch} leaf, which is the shared cross-runtime
|
|
1587
|
-
* contract this function does not get a second opinion about. The ordered
|
|
1588
|
-
* `base_branch` → `baseBranch` scan, the skip-and-continue treatment of a
|
|
1589
|
-
* non-string or blank candidate, and the trim all live there.
|
|
1590
|
-
* 2. OPERATIONAL POLICY, which is this function's own and is NOT shared with
|
|
1591
|
-
* Python: an undeclared policy defaults to `main`, and the branch that will
|
|
1592
|
-
* actually be handed to git is validated before it is returned.
|
|
1593
|
-
*
|
|
1594
|
-
* The frozen dispositions (BAPI-1127) show up here as follows:
|
|
1595
|
-
*
|
|
1596
|
-
* - A NON-STRING candidate is absent, not fatal. `{base_branch: 42,
|
|
1597
|
-
* baseBranch: "epic/X"}` now resolves to `epic/X`; before BAPI-1127 it failed
|
|
1598
|
-
* closed, and `{base_branch: "", baseBranch: "epic/X"}` reported `main` — a
|
|
1599
|
-
* different real branch from the one the server provisioned.
|
|
1600
|
-
* - A MALFORMED declared name does NOT fall back to `main`. Silently
|
|
1601
|
-
* substituting the default for a bad declaration is how a wrong base becomes
|
|
1602
|
-
* invisible (the BAPI-586 defect), so it fails closed and dispatch refuses.
|
|
1603
|
-
* Only an ACTUAL absence of a declaration reaches the default.
|
|
1604
|
-
*
|
|
1605
|
-
* Validation happens here, once, ahead of both operational consumers (dispatch
|
|
1606
|
-
* and the done gate) rather than inside the shared resolver, so that Python and
|
|
1607
|
-
* TypeScript agree about what a policy declares while each keeps its own
|
|
1608
|
-
* judgment about what is safe to use. The failure carries only the rule that
|
|
1609
|
-
* failed — never the policy document or an unbounded branch value.
|
|
1610
|
-
*/
|
|
1611
|
-
export function resolveEffectiveRunBaseBranch(policyJson) {
|
|
1612
|
-
const DEFAULT_BASE = "main";
|
|
1613
|
-
const declaredBaseBranch = resolveDeclaredRunBaseBranch(policyJson);
|
|
1614
|
-
const effectiveBaseBranch = declaredBaseBranch ?? DEFAULT_BASE;
|
|
1615
|
-
const validationError = validateBranchName(effectiveBaseBranch);
|
|
1616
|
-
if (validationError) {
|
|
1617
|
-
return { ok: false, error: `epic run policy base_branch is invalid: ${validationError}` };
|
|
1618
|
-
}
|
|
1619
|
-
return { ok: true, declaredBaseBranch, effectiveBaseBranch };
|
|
1620
|
-
}
|
|
1621
|
-
/**
|
|
1622
|
-
* Build the production EpicRuntimeDeps for use inside `runEpicTickCommand`.
|
|
1623
|
-
*
|
|
1624
|
-
* Fail-open: if Bridge API access is unresolvable, returns an empty `{}`
|
|
1625
|
-
* object so `runEpicTick` falls back to its observe-only defaults (exit 0).
|
|
1626
|
-
* Never throws out of this factory.
|
|
1627
|
-
*/
|
|
1628
|
-
export async function buildProductionEpicRuntimeDeps(epicKey) {
|
|
1629
|
-
let access;
|
|
1630
|
-
try {
|
|
1631
|
-
const accessResult = await resolveConductorBridgeApiAccess();
|
|
1632
|
-
if (!accessResult.ok) {
|
|
1633
|
-
process.stderr.write(`[epic-tick] factory: observe-only — bridge access unavailable (${accessResult.kind})\n`);
|
|
1634
|
-
return {};
|
|
1635
|
-
}
|
|
1636
|
-
access = accessResult.access;
|
|
1637
|
-
}
|
|
1638
|
-
catch {
|
|
1639
|
-
process.stderr.write(`[epic-tick] factory: observe-only — bridge access resolution failed\n`);
|
|
1640
|
-
return {};
|
|
1641
|
-
}
|
|
1642
|
-
// BAPI-586: resolve the run's configured base branch ONCE (from the epic run's
|
|
1643
|
-
// policy_json) so every fresh dispatch cuts from — and every PR targets — the
|
|
1644
|
-
// authoritative run base rather than a hard-coded `main`. Fail-open on a fetch
|
|
1645
|
-
// error (observe-only would already default to `main`); a malformed configured
|
|
1646
|
-
// base is captured as an error and re-raised at dispatch time so a bad base
|
|
1647
|
-
// never silently dispatches.
|
|
1648
|
-
//
|
|
1649
|
-
// BAPI-1127: the fetch-failure fallback declares NOTHING and dispatches from
|
|
1650
|
-
// `main`, which is what "we could not read the policy" honestly means — the
|
|
1651
|
-
// two values are kept separate so a later reader cannot mistake the default
|
|
1652
|
-
// for a declaration the run never made.
|
|
1653
|
-
const UNDECLARED_MAIN = {
|
|
1654
|
-
ok: true,
|
|
1655
|
-
declaredBaseBranch: undefined,
|
|
1656
|
-
effectiveBaseBranch: "main",
|
|
1657
|
-
};
|
|
1658
|
-
let cachedRunBase = UNDECLARED_MAIN;
|
|
1659
|
-
try {
|
|
1660
|
-
const runState = await fetchEpicRunState(access, epicKey);
|
|
1661
|
-
cachedRunBase = resolveEffectiveRunBaseBranch(runState.epic_run.policy_json);
|
|
1662
|
-
}
|
|
1663
|
-
catch {
|
|
1664
|
-
cachedRunBase = UNDECLARED_MAIN;
|
|
1665
|
-
}
|
|
1666
|
-
// Shared closure state populated by fetchPlan and consumed by dispatchSeam.
|
|
1667
|
-
let cachedPlanVersion = 0;
|
|
1668
|
-
const automationMap = new Map();
|
|
1669
|
-
// BAPI-507 (N-2): per-ticket normalized declared touched-file set, sourced from
|
|
1670
|
-
// the plan DAG node's `touched_files`. Consumed by dispatchSeam to inject the
|
|
1671
|
-
// declared file scope into the implementation worker's environment.
|
|
1672
|
-
const touchedFilesMap = new Map();
|
|
1673
|
-
const fetchPlan = async (ek, acc) => {
|
|
1674
|
-
let response;
|
|
1675
|
-
try {
|
|
1676
|
-
response = await getEpicPlan(acc, ek, "approved");
|
|
1677
|
-
}
|
|
1678
|
-
catch (err) {
|
|
1679
|
-
// 404 / no approved plan → null (no-plan mode); other errors bubble up
|
|
1680
|
-
// so the fail-closed plan-unavailable path in runEpicTick fires.
|
|
1681
|
-
const status = err.status;
|
|
1682
|
-
if (status === 404)
|
|
1683
|
-
return null;
|
|
1684
|
-
throw err;
|
|
1685
|
-
}
|
|
1686
|
-
if (!response || !response.plan_blob)
|
|
1687
|
-
return null;
|
|
1688
|
-
const dag = response.plan_blob;
|
|
1689
|
-
cachedPlanVersion = response.plan_version;
|
|
1690
|
-
// Populate the automation + declared-touched-files maps for the dispatch seam.
|
|
1691
|
-
for (const node of dag.nodes) {
|
|
1692
|
-
const nodeKey = node.ticket_key.trim();
|
|
1693
|
-
const kind = node.automations?.[0]?.kind;
|
|
1694
|
-
if (kind) {
|
|
1695
|
-
automationMap.set(nodeKey, kind);
|
|
1696
|
-
}
|
|
1697
|
-
// BAPI-507 (N-2): normalize defensively (trim, drop blanks, dedupe, sort;
|
|
1698
|
-
// no filesystem access). Missing/non-array touched_files → unspecified, so
|
|
1699
|
-
// the ticket simply gets no declared scope rather than failing dispatch.
|
|
1700
|
-
const declared = normalizeDeclaredTouchedFiles(node.touched_files);
|
|
1701
|
-
if (declared.length > 0) {
|
|
1702
|
-
touchedFilesMap.set(nodeKey, declared);
|
|
1703
|
-
}
|
|
1704
|
-
}
|
|
1705
|
-
// Map DAG nodes to EpicTicketNode, preserving each node's normalized declared
|
|
1706
|
-
// touched-file set (drop automations/status/edges).
|
|
1707
|
-
const tickets = dag.nodes.map((n) => {
|
|
1708
|
-
const nodeKey = n.ticket_key.trim();
|
|
1709
|
-
const declared = touchedFilesMap.get(nodeKey);
|
|
1710
|
-
return {
|
|
1711
|
-
ticket_key: nodeKey,
|
|
1712
|
-
depends_on: (n.depends_on ?? []).map((k) => k.trim()),
|
|
1713
|
-
...(declared && declared.length > 0 ? { touched_files: declared } : {}),
|
|
1714
|
-
};
|
|
1715
|
-
});
|
|
1716
|
-
// Recompute the hash locally — do NOT trust the server-returned plan_hash.
|
|
1717
|
-
// This makes the integrity gate fail-closed: a tampered or drifted blob
|
|
1718
|
-
// will hash differently than approved_plan_hash and halt the tick.
|
|
1719
|
-
const planHash = hashPlan(dag);
|
|
1720
|
-
return { plan_hash: planHash, plan_version: response.plan_version, tickets };
|
|
1721
|
-
};
|
|
1722
|
-
const dispatchSeam = async (ek, tk, attempt = 0) => {
|
|
1723
|
-
// Guard: fetchPlan must run before dispatchSeam so cachedPlanVersion and
|
|
1724
|
-
// automationMap are populated. A zero version means the factory seam was
|
|
1725
|
-
// wired but fetchPlan was never called — fail explicitly rather than silently
|
|
1726
|
-
// creating a dispatch key with version 0.
|
|
1727
|
-
if (cachedPlanVersion === 0) {
|
|
1728
|
-
throw new Error(`dispatchSeam called before fetchPlan for epic ${ek} ticket ${tk}; cachedPlanVersion is 0`);
|
|
1729
|
-
}
|
|
1730
|
-
// BAPI-586/BAPI-1127: fail CLOSED on a malformed configured run base rather
|
|
1731
|
-
// than dispatching a worker (and opening a PR) against a bad base. The check
|
|
1732
|
-
// is here — ahead of the dispatch claim, the spawn command, and any git or
|
|
1733
|
-
// provider work — because `resolveEffectiveRunBaseBranch` validates the ref
|
|
1734
|
-
// but this is the boundary that actually uses it. Only `effectiveBaseBranch`
|
|
1735
|
-
// (declaration, else `main`) is handed on; the declaration itself stays
|
|
1736
|
-
// separately readable on `cachedRunBase` and is never overwritten.
|
|
1737
|
-
if (!cachedRunBase.ok) {
|
|
1738
|
-
throw new Error(`invalid configured base branch for epic ${ek}: ${cachedRunBase.error}`);
|
|
1739
|
-
}
|
|
1740
|
-
const runBaseBranch = cachedRunBase.effectiveBaseBranch;
|
|
1741
|
-
// BAPI-441: a remediation re-dispatch (attempt > 0) reuses the existing
|
|
1742
|
-
// branch/worktree (resume mode) and claims an attempt-scoped dispatch key so
|
|
1743
|
-
// it is not deduped against the original epic dispatch.
|
|
1744
|
-
const isResume = attempt > 0;
|
|
1745
|
-
// The dispatch kind comes from the plan node's automation (start-tickets or
|
|
1746
|
-
// review-tickets); default to start-tickets when unspecified.
|
|
1747
|
-
const kind = automationMap.get(tk) ?? "start-tickets";
|
|
1748
|
-
// Operator dry-run: when BAPI_EPIC_IMPLEMENTER_DISPATCH_DRY_RUN=1, dispatch resolves
|
|
1749
|
-
// the spawn command + model routing but opens NO terminal, creates NO worktree,
|
|
1750
|
-
// and opens NO PR (start-tickets/review-tickets dryRun). The full loop dispatch
|
|
1751
|
-
// path (ready-set → claim key → dispatch → correlate run_id) still exercises;
|
|
1752
|
-
// dry-run rows carry no runId, so a synthetic one is substituted for correlation.
|
|
1753
|
-
const dispatchDryRun = process.env.BAPI_EPIC_IMPLEMENTER_DISPATCH_DRY_RUN === "1";
|
|
1754
|
-
// BAPI-507 (N-2): thread the ticket's declared file scope into the
|
|
1755
|
-
// IMPLEMENTATION dispatch identity only. A `review-tickets` node does not open
|
|
1756
|
-
// an implementation PR, so it gets no file-scope env (Step 8.5).
|
|
1757
|
-
const declaredTouchedFiles = kind === "review-tickets" ? undefined : touchedFilesMap.get(tk);
|
|
1758
|
-
const identity = {
|
|
1759
|
-
epic_key: ek,
|
|
1760
|
-
epic_run_id: ek,
|
|
1761
|
-
plan_version: cachedPlanVersion,
|
|
1762
|
-
dispatch_key: buildEpicDispatchKey(ek, tk, cachedPlanVersion, attempt),
|
|
1763
|
-
// BAPI-586: carry the authoritative run base so orchestrateStartTickets
|
|
1764
|
-
// seeds worktrees from — and workers target their PR at — the run base.
|
|
1765
|
-
base_branch: runBaseBranch,
|
|
1766
|
-
...(declaredTouchedFiles && declaredTouchedFiles.length > 0
|
|
1767
|
-
? { declared_touched_files: declaredTouchedFiles }
|
|
1768
|
-
: {}),
|
|
1769
|
-
};
|
|
1770
|
-
const deps = createDefaultStartTicketsDeps();
|
|
1771
|
-
let runId;
|
|
1772
|
-
if (kind === "review-tickets") {
|
|
1773
|
-
const result = await orchestrateReviewTickets(deps, {
|
|
1774
|
-
keys: [tk],
|
|
1775
|
-
epic: identity,
|
|
1776
|
-
agentName: "claude",
|
|
1777
|
-
dryRun: dispatchDryRun,
|
|
1778
|
-
maxParallel: 1,
|
|
1779
|
-
auto: true,
|
|
1780
|
-
reviewOverrides: {},
|
|
1781
|
-
// BAPI-474: the Conductor epic-dispatch path stays git-fetch-free — it
|
|
1782
|
-
// already dispatches into the correct worktree/branch context, so the
|
|
1783
|
-
// fresh-base materialization (an interactive-CLI concern) is unneeded here.
|
|
1784
|
-
noRefreshBase: true,
|
|
1785
|
-
});
|
|
1786
|
-
if (!result.ok) {
|
|
1787
|
-
throw new Error(`review-tickets dispatch failed: ${result.error}`);
|
|
1788
|
-
}
|
|
1789
|
-
runId = result.rows[0]?.runId;
|
|
1790
|
-
}
|
|
1791
|
-
else {
|
|
1792
|
-
// BAPI-409 / IH-1: epic dispatch (dispatch_key set) requires the conductor
|
|
1793
|
-
// stage to mint a run_id and provision per-worker env/supervisor context.
|
|
1794
|
-
// `conductorEnabled: true` alone is necessary but not sufficient — the
|
|
1795
|
-
// BAPI-409 guard in orchestrateStartTickets fails closed unless the
|
|
1796
|
-
// createConductorContext seam (and its siblings) is injected via the third
|
|
1797
|
-
// `overrides` argument, exactly as the packaged start-tickets CLI does. The
|
|
1798
|
-
// orchestrator short-circuits on dryRun before using them, so passing them
|
|
1799
|
-
// unconditionally is safe; dispatchDryRun preserves the operator dry-run seam.
|
|
1800
|
-
const result = await orchestrateStartTickets(deps, {
|
|
1801
|
-
keys: [tk],
|
|
1802
|
-
epic: identity,
|
|
1803
|
-
agentName: "claude",
|
|
1804
|
-
dryRun: dispatchDryRun,
|
|
1805
|
-
autoApprove: true,
|
|
1806
|
-
maxParallel: 1,
|
|
1807
|
-
// F-base: a merge-gated dependent MUST cut from the predecessor's merged
|
|
1808
|
-
// code. With refreshMain:false the worktree was cut from a STALE local
|
|
1809
|
-
// `main` (never fetched/ff'd after the predecessor merged on origin), so
|
|
1810
|
-
// dependents built without the predecessor's code — defeating the whole
|
|
1811
|
-
// merge-gated handoff. Refresh (fetch origin) before cut.
|
|
1812
|
-
refreshMain: true,
|
|
1813
|
-
// BAPI-527 (Step 10): unattended conductor dispatch must NOT mutate the
|
|
1814
|
-
// operator's local checkout. `nonMutatingBase: true` resolves origin/<base>
|
|
1815
|
-
// via a fetch-only immutable SHA and cuts new worktrees from it — never a
|
|
1816
|
-
// `git merge --ff-only` / `git branch --force` / branch switch on the host
|
|
1817
|
-
// checkout. Interactive start-tickets keeps the old refreshBaseBranch path.
|
|
1818
|
-
nonMutatingBase: true,
|
|
1819
|
-
branchOverrides: {},
|
|
1820
|
-
// BAPI-586: the authoritative run base (retains "main" as the default when
|
|
1821
|
-
// no custom base is configured), not a hard-coded literal. Also carried on
|
|
1822
|
-
// `identity.base_branch` above; orchestrateStartTickets reconciles both.
|
|
1823
|
-
baseBranch: runBaseBranch,
|
|
1824
|
-
conductorEnabled: true,
|
|
1825
|
-
// Epic dispatch always runs the plain implementation workflow; the
|
|
1826
|
-
// review-and-implement workflow is a manual/front-door-only seam.
|
|
1827
|
-
workflow: "implement",
|
|
1828
|
-
// BAPI-441: re-dispatch reuses the existing branch/worktree.
|
|
1829
|
-
resumeMode: isResume,
|
|
1830
|
-
// F7: on a FRESH dispatch, refuse a stale leftover `feature/<KEY>` branch
|
|
1831
|
-
// (e.g. a prior run's worktree) rather than silently building on it. No
|
|
1832
|
-
// effect on resume (which reuses a located worktree via a different path).
|
|
1833
|
-
guardStaleWorktree: !isResume,
|
|
1834
|
-
}, {
|
|
1835
|
-
createConductorContext: createStartTicketsConductorContext,
|
|
1836
|
-
provisionConductorHooksForRows,
|
|
1837
|
-
emitStartTicketsRunStarted,
|
|
1838
|
-
});
|
|
1839
|
-
if (!result.ok) {
|
|
1840
|
-
throw new Error(`start-tickets dispatch failed: ${result.error}`);
|
|
1841
|
-
}
|
|
1842
|
-
runId = result.rows[0]?.runId;
|
|
1843
|
-
}
|
|
1844
|
-
if (!runId && dispatchDryRun) {
|
|
1845
|
-
// Dry-run dispatch produced no real run_id; substitute a synthetic id so the
|
|
1846
|
-
// idempotent correlate step still runs and the dispatch row is observable.
|
|
1847
|
-
runId = `dry-run:${identity.dispatch_key}`;
|
|
1848
|
-
}
|
|
1849
|
-
if (!runId) {
|
|
1850
|
-
throw new Error(`dispatch returned no runId for ticket ${tk}`);
|
|
1851
|
-
}
|
|
1852
|
-
return runId;
|
|
1853
|
-
};
|
|
1854
|
-
const dispatchReviewSeam = async (ek, tk, attempt = 0) => {
|
|
1855
|
-
// BAPI-445: spawn the pre-implementation spec re-review as the review-tickets
|
|
1856
|
-
// automation kind — ALWAYS a review, regardless of the ticket's own plan-node
|
|
1857
|
-
// automation kind (which is an implementation kind). fetchPlan must have run
|
|
1858
|
-
// first so cachedPlanVersion is populated (same guard as dispatchSeam).
|
|
1859
|
-
if (cachedPlanVersion === 0) {
|
|
1860
|
-
throw new Error(`dispatchReviewSeam called before fetchPlan for epic ${ek} ticket ${tk}; cachedPlanVersion is 0`);
|
|
1861
|
-
}
|
|
1862
|
-
const dispatchDryRun = process.env.BAPI_EPIC_IMPLEMENTER_DISPATCH_DRY_RUN === "1";
|
|
1863
|
-
// Deliberately omit `dispatch_key` from the identity: the reconcile pass owns
|
|
1864
|
-
// the idempotent :review key claim (recordEpicDispatch with reviewRole) and the
|
|
1865
|
-
// run_spawned correlation. orchestrateReviewTickets still mints the run_id and
|
|
1866
|
-
// injects BAPI_EPIC_IMPLEMENTER_RUN_ID into the review agent's environment, which is
|
|
1867
|
-
// exactly the correlation channel the Python review orchestrator reads to stamp
|
|
1868
|
-
// the spec_review.* verdict event with this review run's id (Phase 2).
|
|
1869
|
-
const identity = {
|
|
1870
|
-
epic_key: ek,
|
|
1871
|
-
epic_run_id: ek,
|
|
1872
|
-
plan_version: cachedPlanVersion,
|
|
1873
|
-
};
|
|
1874
|
-
const deps = createDefaultStartTicketsDeps();
|
|
1875
|
-
const result = await orchestrateReviewTickets(deps, {
|
|
1876
|
-
keys: [tk],
|
|
1877
|
-
epic: identity,
|
|
1878
|
-
agentName: "claude",
|
|
1879
|
-
dryRun: dispatchDryRun,
|
|
1880
|
-
maxParallel: 1,
|
|
1881
|
-
auto: true,
|
|
1882
|
-
// Product directive: the spec re-review is `/review-ticket --auto --rounds=2`.
|
|
1883
|
-
rounds: 2,
|
|
1884
|
-
reviewOverrides: {},
|
|
1885
|
-
// BAPI-474: see the sibling dispatchSeam comment — Conductor dispatch stays
|
|
1886
|
-
// git-fetch-free.
|
|
1887
|
-
noRefreshBase: true,
|
|
1888
|
-
});
|
|
1889
|
-
if (!result.ok) {
|
|
1890
|
-
throw new Error(`spec re-review dispatch failed: ${result.error}`);
|
|
1891
|
-
}
|
|
1892
|
-
let runId = result.rows[0]?.runId;
|
|
1893
|
-
if (!runId && dispatchDryRun) {
|
|
1894
|
-
// Dry-run produced no real run_id; substitute a synthetic, attempt-scoped id
|
|
1895
|
-
// so the reconcile correlate step still records the :review dispatch row.
|
|
1896
|
-
runId = `dry-run:review:${ek}:${tk}:${cachedPlanVersion}:r${attempt}`;
|
|
1897
|
-
}
|
|
1898
|
-
if (!runId) {
|
|
1899
|
-
throw new Error(`spec re-review dispatch returned no runId for ticket ${tk}`);
|
|
1900
|
-
}
|
|
1901
|
-
return runId;
|
|
1902
|
-
};
|
|
1903
|
-
const fetchLocalEvents = async (_ek, runIds) => {
|
|
1904
|
-
// Workers and the epic-tick process share the same local SQLite ledger
|
|
1905
|
-
// (~/.config/bridge/events.db). pollConductorEvents opens it read-only.
|
|
1906
|
-
//
|
|
1907
|
-
// Scope the read to this epic's dispatched run_ids. The shared ledger holds
|
|
1908
|
-
// events for every epic/worker on the machine (up to RETENTION_MAX_ROWS),
|
|
1909
|
-
// but rebuildObservedState only folds signals whose run_id maps to one of
|
|
1910
|
-
// these dispatches — so the run_ids filter pushes that scoping into SQL and
|
|
1911
|
-
// avoids loading sibling-epic events on every tick. With no known run_ids
|
|
1912
|
-
// (first tick before any dispatch) there is nothing to fold, so skip the
|
|
1913
|
-
// read entirely.
|
|
1914
|
-
//
|
|
1915
|
-
// pollConductorEvents returns at most POLL_LIMIT_MAX events per call
|
|
1916
|
-
// (default 100, capped at 1000) starting at `since_seq`. rebuildObservedState
|
|
1917
|
-
// folds terminal signals (gate.met/run.stopped/merge.succeeded/ci.failed)
|
|
1918
|
-
// ONLY from the events it is handed, so a single capped page silently hides
|
|
1919
|
-
// recent terminal signals once the (scoped) result grows past one page —
|
|
1920
|
-
// done-detection then breaks. Drain the COMPLETE history by paginating on the
|
|
1921
|
-
// `next_seq` cursor until a short (or empty) page signals the tail.
|
|
1922
|
-
if (runIds !== undefined && runIds.length === 0) {
|
|
1923
|
-
return [];
|
|
1924
|
-
}
|
|
1925
|
-
const runIdsFilter = runIds && runIds.length > 0 ? { run_ids: [...runIds] } : undefined;
|
|
1926
|
-
const events = [];
|
|
1927
|
-
let sinceSeq = 1;
|
|
1928
|
-
// Retention caps (retention_days/retention_max_rows) bound the ledger, but
|
|
1929
|
-
// cap total iterations defensively against a non-advancing cursor.
|
|
1930
|
-
const MAX_PAGES = 10_000;
|
|
1931
|
-
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
1932
|
-
const result = await pollConductorEvents({
|
|
1933
|
-
data_mode: "full",
|
|
1934
|
-
since_seq: sinceSeq,
|
|
1935
|
-
limit: POLL_LIMIT_MAX,
|
|
1936
|
-
filter: runIdsFilter,
|
|
1937
|
-
});
|
|
1938
|
-
events.push(...result.events);
|
|
1939
|
-
// Stop on a short/empty page (no more rows) or a cursor that fails to
|
|
1940
|
-
// advance (guards against an infinite loop).
|
|
1941
|
-
if (result.count < POLL_LIMIT_MAX || result.next_seq <= sinceSeq) {
|
|
1942
|
-
break;
|
|
1943
|
-
}
|
|
1944
|
-
sinceSeq = result.next_seq;
|
|
1945
|
-
}
|
|
1946
|
-
return events;
|
|
1947
|
-
};
|
|
1948
|
-
const escalateOnce = async (ek, reason) => {
|
|
1949
|
-
const candidate = {
|
|
1950
|
-
reason,
|
|
1951
|
-
kind: "escalation",
|
|
1952
|
-
worker_id: null,
|
|
1953
|
-
state: null,
|
|
1954
|
-
liveness: null,
|
|
1955
|
-
elapsed_ms: 0,
|
|
1956
|
-
context: {},
|
|
1957
|
-
};
|
|
1958
|
-
// Attempt to extract a ticket key from structured reason strings like
|
|
1959
|
-
// "dispatch-orphan:TICKET-123".
|
|
1960
|
-
const ticketMatch = /^dispatch-orphan:(.+)$/.exec(reason);
|
|
1961
|
-
if (ticketMatch) {
|
|
1962
|
-
candidate.worker_id = ticketMatch[1];
|
|
1963
|
-
candidate.context = { ticket_key: ticketMatch[1] };
|
|
1964
|
-
}
|
|
1965
|
-
const assessment = {
|
|
1966
|
-
classification: "stuck",
|
|
1967
|
-
confidence: 1,
|
|
1968
|
-
reason,
|
|
1969
|
-
};
|
|
1970
|
-
const idempotencyKey = makeSupervisorIdempotencyKey({
|
|
1971
|
-
run_id: ek,
|
|
1972
|
-
worker_id: candidate.worker_id,
|
|
1973
|
-
reason,
|
|
1974
|
-
kind: "escalation",
|
|
1975
|
-
cooldown_window: "epic-escalation",
|
|
1976
|
-
});
|
|
1977
|
-
await dispatchSupervisorNotification(ek, candidate, assessment, idempotencyKey);
|
|
1978
|
-
};
|
|
1979
|
-
// postActionWaitSeam: the inline parse-after-merge path in runEpicTick
|
|
1980
|
-
// (epic-runtime.ts Step 3.5) is the authoritative execution path when
|
|
1981
|
-
// post_action_waits.parse_after_merge.enabled is true. The postActionWaitSeam
|
|
1982
|
-
// in reconcile is a scheduling hook for a separate async wait; wiring it to
|
|
1983
|
-
// a real action here would cause double-running. Leave it as a no-op.
|
|
1984
|
-
const postActionWaitSeam = async (_ek, _tk) => { };
|
|
1985
|
-
void epicKey; // epicKey reserved for future factory-level per-epic setup
|
|
1986
|
-
// Note: `access` is not closed over by the returned seams — fetchPlan receives
|
|
1987
|
-
// credentials as a parameter from runEpicTick's resolver, and dispatchSeam
|
|
1988
|
-
// calls createDefaultStartTicketsDeps() which resolves credentials independently.
|
|
1989
|
-
// The variable exists only to satisfy the availability guard above.
|
|
1990
|
-
void access;
|
|
1991
|
-
return {
|
|
1992
|
-
fetchPlan,
|
|
1993
|
-
dispatchSeam,
|
|
1994
|
-
dispatchReviewSeam,
|
|
1995
|
-
fetchLocalEvents,
|
|
1996
|
-
escalateOnce,
|
|
1997
|
-
postActionWaitSeam,
|
|
1998
|
-
// BAPI-654 (T2): backend-authoritative shadow ops. Like fetchPlan, they
|
|
1999
|
-
// receive `access` as a parameter, so they close over no credentials.
|
|
2000
|
-
reconcileShadowMerge: (acc, ek, mergedTicketKey) => reconcileShadowMerge(acc, { epicKey: ek, mergedTicketKey }),
|
|
2001
|
-
// BAPI-845: forward the WHOLE decision, not just the verdict. Dropping the
|
|
2002
|
-
// deadline state here is what left the reconcile pass able only to hold
|
|
2003
|
-
// forever; the reason token is what lets it say why.
|
|
2004
|
-
checkShadowFreshness: async (acc, ek, tk) => {
|
|
2005
|
-
const freshness = await fetchShadowDispatchFreshness(acc, {
|
|
2006
|
-
epicKey: ek,
|
|
2007
|
-
ticketKey: tk,
|
|
2008
|
-
});
|
|
2009
|
-
return {
|
|
2010
|
-
verdict: freshness.verdict,
|
|
2011
|
-
deadlineExpired: freshness.deadlineExpired,
|
|
2012
|
-
blockedAdvanceReason: freshness.blockedAdvanceReason,
|
|
2013
|
-
};
|
|
2014
|
-
},
|
|
2015
|
-
// BAPI-442 seams are wired at the reconcileDeps level inside runEpicTick
|
|
2016
|
-
// (they need the per-tick `access` and `prBindings` closure). The factory
|
|
2017
|
-
// returns the dispatchSeam with isReReview support; the other two seams are
|
|
2018
|
-
// defined inline in the reconcileDeps object in runEpicTick.
|
|
2019
|
-
};
|
|
2020
|
-
}
|