@bridge_gpt/mcp-server 0.2.76 → 0.2.77
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 +8 -6
- package/build/agents.generated.js +3 -3
- package/build/cli-dispatch.js +333 -0
- package/build/commands.generated.js +5 -5
- package/build/conductor/bridge-api-client.js +52 -7
- package/build/conductor/declare-blocked.js +142 -7
- package/build/conductor/driver-register.js +8 -2
- package/build/conductor/epic-implementer-cli.js +11 -7
- package/build/conductor/epic-server-journal.js +39 -22
- package/build/conductor/launch-plan.js +28 -7
- package/build/conductor/local-merge.js +1 -1
- package/build/conductor/readiness-prerequisites.js +89 -2
- package/build/conductor/recovery-cli.js +2 -0
- package/build/docs.generated.js +67 -4
- package/build/doctor.js +97 -1
- package/build/drive-epic.js +223 -6
- package/build/engine-paths.js +10 -0
- package/build/epic-coherence-input-cli.js +105 -10
- package/build/epic-coherence-input.js +877 -4
- package/build/epic-coherence-input.test-fixtures.js +117 -0
- package/build/epic-implementer-bin.js +901 -94
- package/build/epic-implementer-env.js +2 -2
- package/build/executor/completion-contract.js +14 -1
- package/build/executor/guarded-fast-forward-push.js +25 -2
- package/build/executor/job-runner.js +83 -27
- package/build/executor/likely-tests.js +78 -6
- package/build/executor/provider-checks.js +73 -0
- package/build/executor/rebase-finalization.js +29 -27
- package/build/executor/rename-aside.js +265 -0
- package/build/executor/required-work-ledger.js +82 -4
- package/build/executor/types.js +121 -0
- package/build/executor/worktree.js +27 -1
- package/build/index.js +2449 -386
- package/build/install-bridge-conductor-assessment.js +13 -0
- package/build/install-bridge-conductor.js +60 -776
- package/build/install-bridge.js +4 -11
- package/build/language-catalog.generated.js +2649 -0
- package/build/pipelines.generated.js +45 -17
- package/build/plan-execution-ledger.js +8 -0
- package/build/plan-generation.js +34 -0
- package/build/plane/build-freshness.js +6 -0
- package/build/plane/cli.js +12 -5
- package/build/printed-remedy-commands.js +9 -0
- package/build/readiness-prerequisites.generated.js +28 -0
- package/build/readme.generated.js +1 -1
- package/build/run-unit-tests-launcher.js +3 -1
- package/build/server.js +7946 -0
- package/build/start-tickets-prereqs.js +3 -6
- package/build/test-support/console-guard.js +30 -0
- package/build/test-support/module-imports.js +155 -0
- package/build/test-support/server-client.js +96 -0
- package/build/test-support/stdio-server.js +146 -0
- package/build/v2-readiness-requirements.js +31 -2
- package/build/version.generated.js +3 -3
- package/docs/EPIC-IMPLEMENTER.md +71 -2
- package/docs/epic-implementer/getting-started.md +4 -0
- package/package.json +3 -3
- package/pipelines/learn-repository.json +19 -1
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BAPI-1781 — rename a leftover branch aside, backup first, never delete.
|
|
3
|
+
*
|
|
4
|
+
* A relaunched epic run can meet a ticket branch left behind by an earlier run.
|
|
5
|
+
* The fresh-dispatch stale-branch guard refuses it (correctly). When the server's
|
|
6
|
+
* dispatch payload says the branch's owning run has ENDED (`done`/`abandoned`),
|
|
7
|
+
* no job of that run is live, and the provider showed zero open PRs, this module
|
|
8
|
+
* preserves the old commits under a backup name and frees the ticket branch so the
|
|
9
|
+
* ordinary guarded fresh worktree can be cut from the base.
|
|
10
|
+
*
|
|
11
|
+
* Order (each step revalidates before it mutates, like the BAPI-1530 fenced
|
|
12
|
+
* rename-aside in `worktree.ts`):
|
|
13
|
+
* 1. origin backup: create-only push of the old tip to `refs/heads/<backup>`,
|
|
14
|
+
* then read it back at exactly the old tip;
|
|
15
|
+
* 2. local: non-overwriting `git branch -m <branch> <backup>`, then reinspect;
|
|
16
|
+
* 3. origin source: move `refs/heads/<branch>` to the fresh base with
|
|
17
|
+
* a lease on `refs/heads/<branch>` at the old tip, then read it back.
|
|
18
|
+
*
|
|
19
|
+
* Never: branch deletion, remote ref deletion, an unleased or unrestricted force
|
|
20
|
+
* push, overwriting a backup, or reset/clean of anyone's files. A retry recognizes
|
|
21
|
+
* matching backups and an already-moved source as completed steps.
|
|
22
|
+
*
|
|
23
|
+
* Outcomes:
|
|
24
|
+
* * `not_applicable` — no mutation happened and the plan's facts do not establish
|
|
25
|
+
* eligibility. The caller leaves the ordinary stale-branch guard in control,
|
|
26
|
+
* which refuses exactly as before this ticket.
|
|
27
|
+
* * `refused` — eligibility was established but the operation could not be done
|
|
28
|
+
* safely. Maps to the existing `setup_refused` failure kind; any backup already
|
|
29
|
+
* created stays where it is. No backup is claimed.
|
|
30
|
+
* * `renamed` — the rename (or its verified idempotent completion) is established;
|
|
31
|
+
* carries the executor-owned confirmation.
|
|
32
|
+
*/
|
|
33
|
+
import { commandSucceeded } from "../start-tickets-prereqs.js";
|
|
34
|
+
import { leasedRefPushArgs } from "./guarded-fast-forward-push.js";
|
|
35
|
+
import { branchExists, isAncestor, resolveCommit } from "../worktree-core.js";
|
|
36
|
+
import { findWorktreeByBranch, parseGitWorktreePorcelain } from "./worktree-inspection.js";
|
|
37
|
+
import { renameAsidePlanAuthorizes } from "./types.js";
|
|
38
|
+
const FULL_SHA = /^[0-9a-f]{40}$/;
|
|
39
|
+
/** Read one exact ref on origin. Only a successful query listing nothing is `missing`. */
|
|
40
|
+
async function readRemoteRef(deps, ref) {
|
|
41
|
+
try {
|
|
42
|
+
const listed = await deps.runCommand("git", ["ls-remote", "origin", ref], { cwd: deps.cwd });
|
|
43
|
+
if (!commandSucceeded(listed))
|
|
44
|
+
return { kind: "unavailable" };
|
|
45
|
+
const lines = listed.stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
46
|
+
if (lines.length === 0)
|
|
47
|
+
return { kind: "missing" };
|
|
48
|
+
if (lines.length !== 1)
|
|
49
|
+
return { kind: "unavailable" };
|
|
50
|
+
const [sha, name] = lines[0].split(/\s+/);
|
|
51
|
+
const normalized = (sha ?? "").toLowerCase();
|
|
52
|
+
if (name !== ref || !FULL_SHA.test(normalized))
|
|
53
|
+
return { kind: "unavailable" };
|
|
54
|
+
return { kind: "present", sha: normalized };
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return { kind: "unavailable" };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** A local branch's tip: `missing`, a SHA, or `unavailable` (exists but unresolvable). */
|
|
61
|
+
async function readLocalBranch(coreDeps, branch) {
|
|
62
|
+
let exists;
|
|
63
|
+
try {
|
|
64
|
+
exists = await branchExists(coreDeps, branch);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return { kind: "unavailable" };
|
|
68
|
+
}
|
|
69
|
+
if (!exists)
|
|
70
|
+
return { kind: "missing" };
|
|
71
|
+
const tip = await resolveCommit(coreDeps, `refs/heads/${branch}`);
|
|
72
|
+
return tip === null ? { kind: "unavailable" } : { kind: "present", sha: tip.toLowerCase() };
|
|
73
|
+
}
|
|
74
|
+
/** `git check-ref-format` on `refs/heads/<name>`; argv only, never a shell. */
|
|
75
|
+
async function isValidBranchName(deps, name) {
|
|
76
|
+
if (name.length === 0 || name.startsWith("-"))
|
|
77
|
+
return false;
|
|
78
|
+
try {
|
|
79
|
+
const checked = await deps.runCommand("git", ["check-ref-format", `refs/heads/${name}`], { cwd: deps.cwd });
|
|
80
|
+
return checked.exitCode === 0;
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A leased push of `<sha>` to `refs/heads/<ref>` on origin. `expected` is the
|
|
88
|
+
* lease: `""` means create-only (the ref must not exist), otherwise the exact SHA
|
|
89
|
+
* the remote ref must hold. There is no unleased fallback.
|
|
90
|
+
*/
|
|
91
|
+
async function leasedPush(deps, ref, sha, expected) {
|
|
92
|
+
try {
|
|
93
|
+
const args = leasedRefPushArgs(sha, ref, expected);
|
|
94
|
+
if (args === null)
|
|
95
|
+
return false;
|
|
96
|
+
const pushed = await deps.runCommand("git", args, { cwd: deps.cwd });
|
|
97
|
+
return pushed.exitCode === 0;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** True when `candidate` already sits at (or behind) the fresh base. */
|
|
104
|
+
async function atOrBehindBase(coreDeps, candidate, baseSha) {
|
|
105
|
+
if (candidate === baseSha.toLowerCase())
|
|
106
|
+
return true;
|
|
107
|
+
return (await isAncestor(coreDeps, candidate, baseSha)) === "yes";
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Perform (or verify the completion of) the planned rename-aside. See the module
|
|
111
|
+
* comment for the order, outcomes, and the never-delete rule.
|
|
112
|
+
*/
|
|
113
|
+
export async function renameAsideLeftoverBranch(args) {
|
|
114
|
+
const { branch, plan, deps, coreDeps } = args;
|
|
115
|
+
const baseSha = args.baseSha.toLowerCase();
|
|
116
|
+
const mayMutate = args.mayMutate ?? (() => true);
|
|
117
|
+
const skip = (reason) => ({ kind: "not_applicable", reason });
|
|
118
|
+
const refuse = (reason) => ({
|
|
119
|
+
kind: "refused",
|
|
120
|
+
error: `cannot rename leftover branch '${branch}' aside: ${reason}`,
|
|
121
|
+
});
|
|
122
|
+
// --- Server facts: every one must positively authorize (never `eligible` alone).
|
|
123
|
+
if (plan.branch !== branch)
|
|
124
|
+
return skip("plan is bound to a different branch");
|
|
125
|
+
if (!renameAsidePlanAuthorizes(plan))
|
|
126
|
+
return skip("server facts do not establish an ended, PR-free owner");
|
|
127
|
+
const oldSha = plan.old_tip_sha.toLowerCase();
|
|
128
|
+
const backup = plan.backup_name;
|
|
129
|
+
const confirmation = {
|
|
130
|
+
old_branch: branch,
|
|
131
|
+
backup_name: backup,
|
|
132
|
+
old_run_id: plan.owning_run_id,
|
|
133
|
+
short_sha: plan.short_sha,
|
|
134
|
+
};
|
|
135
|
+
if (!FULL_SHA.test(oldSha) || oldSha.slice(0, 12) !== plan.short_sha)
|
|
136
|
+
return skip("planned old tip is malformed");
|
|
137
|
+
if (!FULL_SHA.test(baseSha))
|
|
138
|
+
return skip("fresh base is not a full SHA");
|
|
139
|
+
if (oldSha === baseSha)
|
|
140
|
+
return skip("the old tip is the fresh base");
|
|
141
|
+
if (!(await isValidBranchName(deps, branch)) || !(await isValidBranchName(deps, backup))) {
|
|
142
|
+
return skip("source or backup ref name is not a valid branch name");
|
|
143
|
+
}
|
|
144
|
+
// --- Observe local and origin state (read-only).
|
|
145
|
+
const local = await readLocalBranch(coreDeps, branch);
|
|
146
|
+
const localBackup = await readLocalBranch(coreDeps, backup);
|
|
147
|
+
const origin = await readRemoteRef(deps, `refs/heads/${branch}`);
|
|
148
|
+
const originBackup = await readRemoteRef(deps, `refs/heads/${backup}`);
|
|
149
|
+
if (local.kind === "unavailable" || localBackup.kind === "unavailable")
|
|
150
|
+
return skip("local refs could not be read");
|
|
151
|
+
if (origin.kind === "unavailable")
|
|
152
|
+
return skip("origin branch could not be read; unreadable is not absence");
|
|
153
|
+
// A worktree holding the old branch would collide with the fresh worktree and may
|
|
154
|
+
// hold uncommitted work: leave it alone and let the guard refuse as before.
|
|
155
|
+
const listed = await deps.runCommand("git", ["worktree", "list", "--porcelain"], { cwd: deps.cwd });
|
|
156
|
+
if (!commandSucceeded(listed))
|
|
157
|
+
return skip("worktrees could not be listed");
|
|
158
|
+
const worktrees = parseGitWorktreePorcelain(listed.stdout);
|
|
159
|
+
if (findWorktreeByBranch(worktrees, branch) !== undefined) {
|
|
160
|
+
return skip("the leftover branch is checked out in a worktree; nothing was changed");
|
|
161
|
+
}
|
|
162
|
+
// Identify the operation state. A fresh operation needs the local tip at the
|
|
163
|
+
// planned old SHA. A replay needs the local backup at the old SHA and the source
|
|
164
|
+
// branch gone or already at (or behind) the fresh base.
|
|
165
|
+
const freshStart = local.kind === "present" && local.sha === oldSha;
|
|
166
|
+
const localBackupDone = localBackup.kind === "present" && localBackup.sha === oldSha;
|
|
167
|
+
let replay = false;
|
|
168
|
+
if (!freshStart) {
|
|
169
|
+
if (!localBackupDone)
|
|
170
|
+
return skip("the local branch tip does not equal the planned old tip");
|
|
171
|
+
if (local.kind === "present" && !(await atOrBehindBase(coreDeps, local.sha, baseSha))) {
|
|
172
|
+
return skip("the local branch carries commits that are not on the fresh base");
|
|
173
|
+
}
|
|
174
|
+
replay = true;
|
|
175
|
+
}
|
|
176
|
+
if (origin.kind === "present" && origin.sha !== oldSha && !replay) {
|
|
177
|
+
return skip("the origin branch tip does not equal the planned old tip");
|
|
178
|
+
}
|
|
179
|
+
// ---------------- Eligibility established: from here, failures refuse. -------
|
|
180
|
+
if (freshStart && localBackup.kind === "present") {
|
|
181
|
+
return refuse(`local '${backup}' already exists; nothing was changed`);
|
|
182
|
+
}
|
|
183
|
+
if (originBackup.kind === "unavailable")
|
|
184
|
+
return refuse(`origin '${backup}' could not be read; nothing was changed`);
|
|
185
|
+
if (originBackup.kind === "present" && originBackup.sha !== oldSha) {
|
|
186
|
+
return refuse(`origin '${backup}' exists at a different commit; nothing was changed`);
|
|
187
|
+
}
|
|
188
|
+
// On replay the origin source must be the old tip (not yet moved), already moved
|
|
189
|
+
// to (or behind) the base, or confirmed absent. Anything else is someone else's.
|
|
190
|
+
if (replay && origin.kind === "present" && origin.sha !== oldSha && !(await atOrBehindBase(coreDeps, origin.sha, baseSha))) {
|
|
191
|
+
return refuse("origin branch moved to an unrelated commit; nothing was changed");
|
|
192
|
+
}
|
|
193
|
+
// A moved origin source must have been preserved first.
|
|
194
|
+
if (origin.kind === "present" && origin.sha !== oldSha && originBackup.kind !== "present") {
|
|
195
|
+
return refuse(`origin branch was moved but origin '${backup}' is missing; refusing to continue`);
|
|
196
|
+
}
|
|
197
|
+
const originNeedsMove = origin.kind === "present" && origin.sha === oldSha;
|
|
198
|
+
// 1. Origin backup first, whenever the origin branch still holds the old tip.
|
|
199
|
+
if (originNeedsMove && originBackup.kind === "missing") {
|
|
200
|
+
if (!mayMutate())
|
|
201
|
+
return refuse("preparation authority is no longer valid; nothing was changed");
|
|
202
|
+
const created = await leasedPush(deps, backup, oldSha, "");
|
|
203
|
+
const readBack = await readRemoteRef(deps, `refs/heads/${backup}`);
|
|
204
|
+
if (!created || readBack.kind !== "present" || readBack.sha !== oldSha) {
|
|
205
|
+
return refuse(`origin backup '${backup}' could not be created and verified; nothing was force-pushed`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// 2. Local rename, revalidated immediately before the mutation.
|
|
209
|
+
if (freshStart) {
|
|
210
|
+
if (!mayMutate())
|
|
211
|
+
return refuse("preparation authority is no longer valid; the origin backup (if any) is kept");
|
|
212
|
+
const tipNow = await readLocalBranch(coreDeps, branch);
|
|
213
|
+
const destinationNow = await readLocalBranch(coreDeps, backup);
|
|
214
|
+
if (tipNow.kind !== "present" || tipNow.sha !== oldSha) {
|
|
215
|
+
return refuse("the local branch moved since it was inspected; the origin backup (if any) is kept");
|
|
216
|
+
}
|
|
217
|
+
if (destinationNow.kind !== "missing")
|
|
218
|
+
return refuse(`local '${backup}' appeared; nothing was renamed`);
|
|
219
|
+
const renamed = await deps.runCommand("git", ["branch", "-m", branch, backup], { cwd: deps.cwd });
|
|
220
|
+
if (!commandSucceeded(renamed))
|
|
221
|
+
return refuse(`'git branch -m' to '${backup}' failed; the branch was left as it was`);
|
|
222
|
+
const backupTip = await readLocalBranch(coreDeps, backup);
|
|
223
|
+
const sourceAfter = await readLocalBranch(coreDeps, branch);
|
|
224
|
+
if (backupTip.kind !== "present" || backupTip.sha !== oldSha || sourceAfter.kind !== "missing") {
|
|
225
|
+
return refuse(`renaming to '${backup}' could not be confirmed; refusing to continue`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
// 3. Move the origin source to the fresh base, leased on the old tip.
|
|
229
|
+
if (originNeedsMove) {
|
|
230
|
+
if (!mayMutate())
|
|
231
|
+
return refuse("preparation authority is no longer valid; backups are kept");
|
|
232
|
+
const verifiedBackup = await readRemoteRef(deps, `refs/heads/${backup}`);
|
|
233
|
+
if (verifiedBackup.kind !== "present" || verifiedBackup.sha !== oldSha) {
|
|
234
|
+
return refuse(`origin backup '${backup}' is not verified at the old tip; nothing was force-pushed`);
|
|
235
|
+
}
|
|
236
|
+
const moved = await leasedPush(deps, branch, baseSha, oldSha);
|
|
237
|
+
const after = await readRemoteRef(deps, `refs/heads/${branch}`);
|
|
238
|
+
if (!moved || after.kind !== "present" || after.sha !== baseSha) {
|
|
239
|
+
return refuse("the leased move of the origin branch failed; backups are kept");
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
// Reinspect before the ordinary fresh worktree is created.
|
|
243
|
+
const finalLocalBackup = await readLocalBranch(coreDeps, backup);
|
|
244
|
+
const finalOrigin = await readRemoteRef(deps, `refs/heads/${branch}`);
|
|
245
|
+
if (finalLocalBackup.kind !== "present" || finalLocalBackup.sha !== oldSha) {
|
|
246
|
+
return refuse(`local '${backup}' is not at the old tip after the rename; refusing to continue`);
|
|
247
|
+
}
|
|
248
|
+
if (finalOrigin.kind === "unavailable")
|
|
249
|
+
return refuse("origin could not be re-read after the rename");
|
|
250
|
+
if (finalOrigin.kind === "present") {
|
|
251
|
+
if (finalOrigin.sha === oldSha)
|
|
252
|
+
return refuse("the origin branch still holds the old tip after the rename");
|
|
253
|
+
const finalOriginBackup = await readRemoteRef(deps, `refs/heads/${backup}`);
|
|
254
|
+
if (finalOriginBackup.kind !== "present" || finalOriginBackup.sha !== oldSha) {
|
|
255
|
+
return refuse(`origin '${backup}' is not verified at the old tip after the rename`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
try {
|
|
259
|
+
deps.errorLog?.(`[executor] rename-aside: kept '${branch}' (${oldSha.slice(0, 12)}) as '${backup}'${replay ? " (completed earlier; verified)" : ""}; preparing a fresh worktree from ${baseSha.slice(0, 12)}`);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
/* advisory */
|
|
263
|
+
}
|
|
264
|
+
return { kind: "renamed", confirmation };
|
|
265
|
+
}
|
|
@@ -64,6 +64,20 @@ export const MAX_TOOL_USE_INDEX = MAX_TASKS * 8;
|
|
|
64
64
|
/** Resolved (`succeeded`) obligations evicted to make room are remembered this far, for duplicate/contradiction and replacement checks. */
|
|
65
65
|
const MAX_EVICTED = MAX_TASKS * 4;
|
|
66
66
|
const MAX_WORKER_STOPS = MAX_TASKS * 2;
|
|
67
|
+
/** BAPI-1779 P5 — the largest Monitor `timeout_ms` read as a real expiry budget; larger is unreadable. */
|
|
68
|
+
const MAX_MONITOR_TIMEOUT_MS = 24 * 60 * 60 * 1000;
|
|
69
|
+
/**
|
|
70
|
+
* BAPI-1779 P5 — the Monitor call's own requested timeout, from its tool input
|
|
71
|
+
* (`timeout_ms`). Only a finite, positive, bounded number is kept; anything
|
|
72
|
+
* else (absent, non-numeric, out of range, or a `persistent` monitor that has
|
|
73
|
+
* no expiry) is unreadable and returns `null`. The raw input is never kept.
|
|
74
|
+
*/
|
|
75
|
+
function readMonitorTimeoutMs(input) {
|
|
76
|
+
if (!isRecord(input) || input["persistent"] === true)
|
|
77
|
+
return null;
|
|
78
|
+
const t = input["timeout_ms"];
|
|
79
|
+
return typeof t === "number" && Number.isFinite(t) && t > 0 && t <= MAX_MONITOR_TIMEOUT_MS ? t : null;
|
|
80
|
+
}
|
|
67
81
|
/**
|
|
68
82
|
* The digest an obligation's input is identified by, for optional-watcher
|
|
69
83
|
* matching and exact re-issue replacement.
|
|
@@ -1215,6 +1229,10 @@ export function createRequiredWorkLedger(init) {
|
|
|
1215
1229
|
resultDelivered: false,
|
|
1216
1230
|
failedByResult: false,
|
|
1217
1231
|
erroredBeforeLaunch: false,
|
|
1232
|
+
monitorTimeoutMs: null,
|
|
1233
|
+
terminalAt: null,
|
|
1234
|
+
stoppedByWorker: false,
|
|
1235
|
+
stoppedByTeardown: false,
|
|
1218
1236
|
...spec,
|
|
1219
1237
|
required: spec.required ?? !isOptional(spec.kind, spec.inputDigest),
|
|
1220
1238
|
};
|
|
@@ -1309,6 +1327,13 @@ export function createRequiredWorkLedger(init) {
|
|
|
1309
1327
|
real.resultDelivered = true;
|
|
1310
1328
|
if (real.launchedAt === null && ph.launchedAt !== null && real.state === "pending")
|
|
1311
1329
|
real.launchedAt = ph.launchedAt;
|
|
1330
|
+
// BAPI-1779 P5: stop provenance and terminal time recorded on the placeholder belong to this run.
|
|
1331
|
+
if (ph.stoppedByWorker)
|
|
1332
|
+
real.stoppedByWorker = true;
|
|
1333
|
+
if (ph.stoppedByTeardown)
|
|
1334
|
+
real.stoppedByTeardown = true;
|
|
1335
|
+
if (real.terminalAt === null && real.state === "pending")
|
|
1336
|
+
real.terminalAt = ph.terminalAt;
|
|
1312
1337
|
if (TERMINAL_STATES.has(ph.state))
|
|
1313
1338
|
return applyTerminal(real, ph.state);
|
|
1314
1339
|
return "applied";
|
|
@@ -1410,7 +1435,10 @@ export function createRequiredWorkLedger(init) {
|
|
|
1410
1435
|
track(id, { toolUseId: id, taskId: null, kind: "bash_bg", inputDigest, background: true, placeholder: false });
|
|
1411
1436
|
}
|
|
1412
1437
|
else if (name === "Monitor") {
|
|
1413
|
-
track(id, { toolUseId: id, taskId: null, kind: "monitor", inputDigest, background: true, placeholder: false });
|
|
1438
|
+
const m = track(id, { toolUseId: id, taskId: null, kind: "monitor", inputDigest, background: true, placeholder: false });
|
|
1439
|
+
// BAPI-1779 P5: keep only the validated timeout duration, never the input.
|
|
1440
|
+
if (m && m.kind === "monitor" && m.monitorTimeoutMs === null)
|
|
1441
|
+
m.monitorTimeoutMs = readMonitorTimeoutMs(input);
|
|
1414
1442
|
}
|
|
1415
1443
|
else if (name === "TaskStop") {
|
|
1416
1444
|
// R13: the worker's OWN stop request. It turns a later stop into
|
|
@@ -1628,6 +1656,18 @@ export function createRequiredWorkLedger(init) {
|
|
|
1628
1656
|
}
|
|
1629
1657
|
if (next === "stopped" && workerStops.has(o.key))
|
|
1630
1658
|
next = "withdrawn";
|
|
1659
|
+
// BAPI-1779 P5: record stop provenance and the first stop's clock for the
|
|
1660
|
+
// monitor-expiry rule. A stop event that arrives once the executor began
|
|
1661
|
+
// teardown (stdin closed, stream ended, process exited) is a teardown stop,
|
|
1662
|
+
// even if the same run had already ended: provenance is never guessed away.
|
|
1663
|
+
if (next === "stopped" || next === "withdrawn") {
|
|
1664
|
+
if (next === "withdrawn")
|
|
1665
|
+
o.stoppedByWorker = true;
|
|
1666
|
+
if (stdinClosed || streamEnd !== null || processExit !== null)
|
|
1667
|
+
o.stoppedByTeardown = true;
|
|
1668
|
+
if (o.terminalAt === null && o.state === "pending")
|
|
1669
|
+
o.terminalAt = clock();
|
|
1670
|
+
}
|
|
1631
1671
|
// BAPI-1455: a killed foreground call can deliver its error result before
|
|
1632
1672
|
// the lifecycle `stopped`. The lifecycle names the real end, so a
|
|
1633
1673
|
// result-derived `failed` is refined to `stopped` (one ending, not two).
|
|
@@ -1820,6 +1860,42 @@ export function createRequiredWorkLedger(init) {
|
|
|
1820
1860
|
return { o, state: replaceable && succeededLater(o) ? "replaced" : own };
|
|
1821
1861
|
});
|
|
1822
1862
|
};
|
|
1863
|
+
/**
|
|
1864
|
+
* BAPI-1779 P5 — a `Monitor` that ended by its own expiry is not required.
|
|
1865
|
+
*
|
|
1866
|
+
* This reuses the existing envelope `required` field (the same one
|
|
1867
|
+
* `optional_watchers` sets), so old servers read it unchanged and no new
|
|
1868
|
+
* server task state is needed. The recorded terminal state (`stopped`) is
|
|
1869
|
+
* kept as it is; only `required` changes.
|
|
1870
|
+
*
|
|
1871
|
+
* Signal (a), a structured timeout field on the task notification: no
|
|
1872
|
+
* captured real expired-monitor notification with such a field was available
|
|
1873
|
+
* in this repository, so none is read. The rule relies on signal (b) alone,
|
|
1874
|
+
* and never infers expiry from prose, `stopped`, or `killed` alone.
|
|
1875
|
+
*
|
|
1876
|
+
* Signal (b): the call's own validated `timeout_ms` has elapsed between the
|
|
1877
|
+
* recorded start (`launchedAt`) and the first stop (`terminalAt`), on the
|
|
1878
|
+
* ledger's clock. Known worker-stop or teardown provenance overrides it, and
|
|
1879
|
+
* any unreadable or contradictory timing keeps the monitor required.
|
|
1880
|
+
*/
|
|
1881
|
+
const monitorExpired = (o, state) => {
|
|
1882
|
+
if (o.kind !== "monitor" || state !== "stopped" || o.placeholder)
|
|
1883
|
+
return false;
|
|
1884
|
+
if (o.stoppedByWorker || o.stoppedByTeardown || workerStops.has(o.key))
|
|
1885
|
+
return false;
|
|
1886
|
+
if (o.taskId !== null && deferredWorkerStops.has(o.taskId))
|
|
1887
|
+
return false;
|
|
1888
|
+
const timeout = o.monitorTimeoutMs;
|
|
1889
|
+
const start = o.launchedAt;
|
|
1890
|
+
const end = o.terminalAt;
|
|
1891
|
+
if (timeout === null || start === null || end === null)
|
|
1892
|
+
return false;
|
|
1893
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
|
|
1894
|
+
return false;
|
|
1895
|
+
return end - start >= timeout;
|
|
1896
|
+
};
|
|
1897
|
+
/** The `required` flag the verdict and the envelope use (P5 monitor expiry applied). */
|
|
1898
|
+
const effectiveRequired = (o, state) => o.required && !monitorExpired(o, state);
|
|
1823
1899
|
// --- public API -----------------------------------------------------------
|
|
1824
1900
|
// --- oversize lines (BAPI-1586) -------------------------------------------
|
|
1825
1901
|
let oversizeParser = null;
|
|
@@ -2002,7 +2078,7 @@ export function createRequiredWorkLedger(init) {
|
|
|
2002
2078
|
// BAPI-1455: a command whose own terminal result was delivered is resolved,
|
|
2003
2079
|
// whatever its exit code; its recorded state is kept as it is.
|
|
2004
2080
|
const delivered = (o, state) => o.resultDelivered && DELIVERY_RESOLVABLE_KINDS.has(o.kind) && DELIVERY_RESOLVABLE_STATES.has(state);
|
|
2005
|
-
const unresolvedRequired = effective.some(({ o, state }) => o
|
|
2081
|
+
const unresolvedRequired = effective.some(({ o, state }) => effectiveRequired(o, state) && !isTaskResolved({ kind: o.kind, state, result_delivered: delivered(o, state) }));
|
|
2006
2082
|
const anyConflict = effective.some(({ state }) => state === "conflict");
|
|
2007
2083
|
let execution = unresolvedRequired || anyConflict || snap.required.length > 0 || unexplainedPlaceholder ? "incomplete" : "complete";
|
|
2008
2084
|
if (!sufficient && execution === "complete")
|
|
@@ -2013,7 +2089,7 @@ export function createRequiredWorkLedger(init) {
|
|
|
2013
2089
|
kind: o.kind,
|
|
2014
2090
|
// A task still pending when the verdict is taken never reached a terminal.
|
|
2015
2091
|
state: state === "pending" ? "unknown" : state,
|
|
2016
|
-
required: o
|
|
2092
|
+
required: effectiveRequired(o, state),
|
|
2017
2093
|
input_digest: o.inputDigest,
|
|
2018
2094
|
...(delivered(o, state) ? { result_delivered: true } : {}),
|
|
2019
2095
|
}));
|
|
@@ -2064,7 +2140,9 @@ export function createRequiredWorkLedger(init) {
|
|
|
2064
2140
|
...(facts.verificationFacts ? { verification_facts: facts.verificationFacts } : {}),
|
|
2065
2141
|
};
|
|
2066
2142
|
const withNullCause = { ...candidate, cause: null };
|
|
2067
|
-
const cause = successRefusalReason(withNullCause) === null
|
|
2143
|
+
const cause = successRefusalReason(withNullCause) === null
|
|
2144
|
+
? null
|
|
2145
|
+
: deriveCompletionCause(facts.endCause !== undefined ? { ...candidate, end_cause: facts.endCause } : candidate, { jobType: init.jobType ?? null });
|
|
2068
2146
|
return boundEnvelope({ ...candidate, cause });
|
|
2069
2147
|
};
|
|
2070
2148
|
return {
|
package/build/executor/types.js
CHANGED
|
@@ -227,3 +227,124 @@ export const INTEGRATION_ACTION_OUTCOMES = [
|
|
|
227
227
|
"indeterminate",
|
|
228
228
|
"failed",
|
|
229
229
|
];
|
|
230
|
+
// ---------------------------------------------------------------------------
|
|
231
|
+
// BAPI-1781 — leftover-branch rename-aside: server plan and executor confirmation
|
|
232
|
+
// ---------------------------------------------------------------------------
|
|
233
|
+
/** The payload key the reconciler stamps on a fresh `implement`/`spec_review` job. */
|
|
234
|
+
export const RENAME_ASIDE_PLAN_PAYLOAD_KEY = "worktree_rename_aside_plan";
|
|
235
|
+
/** The completion result key the executor uses for its confirmation. */
|
|
236
|
+
export const RENAME_ASIDE_RESULT_KEY = "rename_aside";
|
|
237
|
+
/** The exact confirmation keys, in the order both languages declare them. */
|
|
238
|
+
export const RENAME_ASIDE_KEYS = ["old_branch", "backup_name", "old_run_id", "short_sha"];
|
|
239
|
+
const RENAME_ASIDE_SHORT_SHA_RE = /^[0-9a-f]{12}$/;
|
|
240
|
+
const RENAME_ASIDE_FULL_SHA_RE = /^[0-9a-f]{40}$/;
|
|
241
|
+
const RENAME_ASIDE_IDENTITY_MAX_CHARS = 255;
|
|
242
|
+
const RENAME_ASIDE_PLAN_KEYS = [
|
|
243
|
+
"branch", "owning_run_id", "owning_run_status", "live_job_read", "open_pr_read",
|
|
244
|
+
"old_tip_sha", "short_sha", "backup_name", "eligible",
|
|
245
|
+
];
|
|
246
|
+
function isPlainObject(value) {
|
|
247
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
248
|
+
}
|
|
249
|
+
function hasExactKeys(value, keys) {
|
|
250
|
+
const own = Object.keys(value);
|
|
251
|
+
return own.length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
|
|
252
|
+
}
|
|
253
|
+
/** A non-empty, bounded identity with no whitespace or control characters. */
|
|
254
|
+
function isRenameAsideIdentity(value) {
|
|
255
|
+
if (typeof value !== "string" || value.length === 0 || value.length > RENAME_ASIDE_IDENTITY_MAX_CHARS)
|
|
256
|
+
return false;
|
|
257
|
+
for (const ch of value) {
|
|
258
|
+
const code = ch.codePointAt(0);
|
|
259
|
+
if (code < 0x20 || code === 0x7f || /\s/.test(ch))
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
/** Runtime check of a confirmation object: exactly the four keys, each well formed. */
|
|
265
|
+
export function isRenameAside(value) {
|
|
266
|
+
if (!isPlainObject(value) || !hasExactKeys(value, RENAME_ASIDE_KEYS))
|
|
267
|
+
return false;
|
|
268
|
+
return (isRenameAsideIdentity(value.old_branch) &&
|
|
269
|
+
isRenameAsideIdentity(value.backup_name) &&
|
|
270
|
+
isRenameAsideIdentity(value.old_run_id) &&
|
|
271
|
+
typeof value.short_sha === "string" &&
|
|
272
|
+
RENAME_ASIDE_SHORT_SHA_RE.test(value.short_sha));
|
|
273
|
+
}
|
|
274
|
+
/** The backup name the server derives: `<branch>-<old_run_id>-<old_tip_sha[:12]>`. */
|
|
275
|
+
export function deriveRenameAsideBackupName(branch, oldRunId, oldTipSha) {
|
|
276
|
+
return `${branch}-${oldRunId}-${oldTipSha.slice(0, 12)}`;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Validate the server's plan at the payload boundary. Returns `null` for an
|
|
280
|
+
* absent or malformed plan, or one bound to a different branch than the job's
|
|
281
|
+
* claimed branch. A valid plan may still be ineligible: uncertainty is kept, never
|
|
282
|
+
* converted into authority. When the plan names an owner, the old SHA, its
|
|
283
|
+
* 12-character prefix, and the derived backup name must all agree exactly.
|
|
284
|
+
*/
|
|
285
|
+
export function parseRenameAsidePlan(raw, claimedBranch) {
|
|
286
|
+
if (!isPlainObject(raw) || !hasExactKeys(raw, RENAME_ASIDE_PLAN_KEYS))
|
|
287
|
+
return null;
|
|
288
|
+
const { branch, owning_run_id, owning_run_status, live_job_read, open_pr_read, old_tip_sha, short_sha, backup_name, eligible } = raw;
|
|
289
|
+
if (!isRenameAsideIdentity(branch) || branch !== claimedBranch)
|
|
290
|
+
return null;
|
|
291
|
+
if (owning_run_id !== null && !isRenameAsideIdentity(owning_run_id))
|
|
292
|
+
return null;
|
|
293
|
+
if (owning_run_status !== "done" && owning_run_status !== "abandoned" && owning_run_status !== "other" && owning_run_status !== "unknown")
|
|
294
|
+
return null;
|
|
295
|
+
if (typeof eligible !== "boolean")
|
|
296
|
+
return null;
|
|
297
|
+
if (!isPlainObject(live_job_read) || !hasExactKeys(live_job_read, ["outcome", "live_job"]))
|
|
298
|
+
return null;
|
|
299
|
+
if (live_job_read.outcome !== "ok" && live_job_read.outcome !== "failed")
|
|
300
|
+
return null;
|
|
301
|
+
if (live_job_read.live_job !== null && typeof live_job_read.live_job !== "boolean")
|
|
302
|
+
return null;
|
|
303
|
+
if (!isPlainObject(open_pr_read) || !hasExactKeys(open_pr_read, ["outcome", "open_count"]))
|
|
304
|
+
return null;
|
|
305
|
+
if (open_pr_read.outcome !== "ok" && open_pr_read.outcome !== "failed" && open_pr_read.outcome !== "unknown")
|
|
306
|
+
return null;
|
|
307
|
+
const count = open_pr_read.open_count;
|
|
308
|
+
if (count !== null && (typeof count !== "number" || !Number.isInteger(count) || count < 0))
|
|
309
|
+
return null;
|
|
310
|
+
if (old_tip_sha !== null && (typeof old_tip_sha !== "string" || !RENAME_ASIDE_FULL_SHA_RE.test(old_tip_sha)))
|
|
311
|
+
return null;
|
|
312
|
+
if (short_sha !== null && (typeof short_sha !== "string" || !RENAME_ASIDE_SHORT_SHA_RE.test(short_sha)))
|
|
313
|
+
return null;
|
|
314
|
+
if (backup_name !== null && !isRenameAsideIdentity(backup_name))
|
|
315
|
+
return null;
|
|
316
|
+
// Identity fields travel together, and must agree with each other exactly.
|
|
317
|
+
const identity = [owning_run_id, old_tip_sha, short_sha, backup_name];
|
|
318
|
+
const present = identity.filter((value) => value !== null).length;
|
|
319
|
+
if (present !== 0 && present !== identity.length)
|
|
320
|
+
return null;
|
|
321
|
+
if (present === identity.length) {
|
|
322
|
+
if (short_sha !== old_tip_sha.slice(0, 12))
|
|
323
|
+
return null;
|
|
324
|
+
if (backup_name !== deriveRenameAsideBackupName(branch, owning_run_id, old_tip_sha))
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
branch,
|
|
329
|
+
owning_run_id: owning_run_id,
|
|
330
|
+
owning_run_status,
|
|
331
|
+
live_job_read: { outcome: live_job_read.outcome, live_job: live_job_read.live_job },
|
|
332
|
+
open_pr_read: { outcome: open_pr_read.outcome, open_count: count },
|
|
333
|
+
old_tip_sha: old_tip_sha,
|
|
334
|
+
short_sha: short_sha,
|
|
335
|
+
backup_name: backup_name,
|
|
336
|
+
eligible,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* True only when every server-observed fact positively authorizes a rename-aside:
|
|
341
|
+
* an ended owner, a successful live-job read showing none, a successful provider
|
|
342
|
+
* read showing zero open PRs, and a complete identity. `eligible` is ignored.
|
|
343
|
+
*/
|
|
344
|
+
export function renameAsidePlanAuthorizes(plan) {
|
|
345
|
+
return ((plan.owning_run_status === "done" || plan.owning_run_status === "abandoned") &&
|
|
346
|
+
plan.live_job_read.outcome === "ok" && plan.live_job_read.live_job === false &&
|
|
347
|
+
plan.open_pr_read.outcome === "ok" && plan.open_pr_read.open_count === 0 &&
|
|
348
|
+
plan.owning_run_id !== null && plan.old_tip_sha !== null &&
|
|
349
|
+
plan.short_sha !== null && plan.backup_name !== null);
|
|
350
|
+
}
|
|
@@ -15,6 +15,7 @@ import { branchExists, createWorktreeForTicket, isAncestor, provePriorHeadLineag
|
|
|
15
15
|
import { findWorktreeByBranch, listGitWorktrees, parseGitWorktreePorcelain } from "./worktree-inspection.js";
|
|
16
16
|
import { buildExecutorWorktreeLockPath, parseExecutorWorktreeLock } from "./worktree-lock.js";
|
|
17
17
|
import { provisionCommandsForWorktree } from "../command-provisioning.js";
|
|
18
|
+
import { renameAsideLeftoverBranch } from "./rename-aside.js";
|
|
18
19
|
/**
|
|
19
20
|
* Resolve the branch for a real spawn job: `expected_branch` wins; else
|
|
20
21
|
* `feature/<ticket_key>`; else a structured contract failure.
|
|
@@ -32,6 +33,8 @@ export function resolveExecutorBranch(job) {
|
|
|
32
33
|
return { ok: true, branch: `feature/${ticketKey}` };
|
|
33
34
|
return { ok: false, error: "no branch could be resolved (no expected_branch and no ticket_key)" };
|
|
34
35
|
}
|
|
36
|
+
/** BAPI-1781: the job types that run the stale-branch guard and may rename aside. */
|
|
37
|
+
const RENAME_ASIDE_JOB_TYPES = new Set(["implement", "spec_review"]);
|
|
35
38
|
/** Configure only this branch; inherited routing must already be safe. */
|
|
36
39
|
export async function configureExecutorBranch(worktreePath, branch, deps) {
|
|
37
40
|
const failure = "executor push routing could not be confirmed";
|
|
@@ -381,6 +384,28 @@ export async function ensureExecutorWorktree(job, options, deps, policy = {}) {
|
|
|
381
384
|
}
|
|
382
385
|
return ensurePriorAttemptWorktree(key, branch, prior.head, baseSha, options, deps, postSwitch);
|
|
383
386
|
}
|
|
387
|
+
// BAPI-1781: a leftover branch from an ENDED earlier run is renamed aside —
|
|
388
|
+
// backup first, never deleted — only when every server fact and the local and
|
|
389
|
+
// origin tips positively allow it. Otherwise nothing changes and the guard below
|
|
390
|
+
// refuses exactly as before. A failure after eligibility is a setup refusal.
|
|
391
|
+
let renameAside;
|
|
392
|
+
if (policy.renameAsidePlan &&
|
|
393
|
+
typeof job.job_type === "string" &&
|
|
394
|
+
RENAME_ASIDE_JOB_TYPES.has(job.job_type)) {
|
|
395
|
+
const renamed = await renameAsideLeftoverBranch({
|
|
396
|
+
branch,
|
|
397
|
+
plan: policy.renameAsidePlan,
|
|
398
|
+
baseSha,
|
|
399
|
+
deps,
|
|
400
|
+
coreDeps: toWorktreeCoreDeps(deps),
|
|
401
|
+
...(policy.preparation ? { mayMutate: policy.preparation.mayMutate } : {}),
|
|
402
|
+
});
|
|
403
|
+
if (renamed.kind === "refused") {
|
|
404
|
+
return { ok: false, error: renamed.error, failureKind: "setup_refused" };
|
|
405
|
+
}
|
|
406
|
+
if (renamed.kind === "renamed")
|
|
407
|
+
renameAside = renamed.confirmation;
|
|
408
|
+
}
|
|
384
409
|
const row = await createWorktreeForTicket(toWorktreeCoreDeps(deps), key, { [key]: branch }, options.worktrunkBinary, baseSha, guardStaleWorktree, {
|
|
385
410
|
...(postSwitch ? { postSwitch } : {}),
|
|
386
411
|
alignExistingBranchTo: baseSha,
|
|
@@ -396,7 +421,8 @@ export async function ensureExecutorWorktree(job, options, deps, policy = {}) {
|
|
|
396
421
|
// BAPI-731: `baseSha` is already the pinned immutable commit this fresh
|
|
397
422
|
// worktree was cut from and verified against (`verifyHeadMatches`), so it is
|
|
398
423
|
// the expectation — no extra resolution needed.
|
|
399
|
-
|
|
424
|
+
const finalized = await finalizeExecutorWorktree(row.path, branch, baseSha, deps);
|
|
425
|
+
return finalized.ok && renameAside ? { ...finalized, renameAside } : finalized;
|
|
400
426
|
}
|
|
401
427
|
return {
|
|
402
428
|
ok: false,
|