@bridge_gpt/mcp-server 0.2.75 → 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 +5 -5
- package/build/cli-dispatch.js +333 -0
- package/build/codex-auto-recovery.js +25 -7
- package/build/commands.generated.js +8 -8
- package/build/conductor/bridge-api-client.js +193 -13
- package/build/conductor/declare-blocked.js +146 -7
- package/build/conductor/driver-pass.js +8 -0
- package/build/conductor/driver-register.js +8 -2
- package/build/conductor/epic-implementer-cli.js +15 -10
- package/build/conductor/epic-server-journal.js +52 -22
- 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/install-doctor.js +30 -2
- package/build/conductor/launch-plan.js +28 -7
- package/build/conductor/local-merge.js +55 -13
- package/build/conductor/pr-ci-producer.js +12 -3
- package/build/conductor/readiness-prerequisites.js +89 -2
- package/build/conductor/readiness-sections.js +46 -13
- package/build/conductor/readiness.js +3 -40
- package/build/conductor/recovery-cli.js +14 -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/docs.generated.js +67 -4
- package/build/doctor.js +97 -1
- package/build/drive-epic.js +625 -33
- 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 +947 -120
- package/build/epic-implementer-env.js +2 -2
- package/build/epic-launch-context.js +8 -1
- package/build/epic-shared/cut-protocol.js +55 -3
- package/build/executor/completion-contract.js +14 -1
- package/build/executor/failure-reason-codes.js +2 -0
- package/build/executor/guarded-fast-forward-push.js +25 -2
- package/build/executor/integration-job.js +56 -2
- package/build/executor/job-runner.js +87 -28
- package/build/executor/likely-tests.js +78 -6
- package/build/executor/merge-job.js +45 -1
- package/build/executor/permissions.js +187 -2
- package/build/executor/provider-checks.js +101 -5
- package/build/executor/rebase-finalization.js +29 -27
- package/build/executor/reconcile-overlap-job.js +70 -17
- package/build/executor/rename-aside.js +265 -0
- package/build/executor/required-work-ledger.js +89 -6
- package/build/executor/resume-pre-spawn.js +32 -8
- package/build/executor/runner.js +26 -4
- package/build/executor/types.js +121 -0
- package/build/executor/worktree.js +39 -2
- package/build/index.js +2500 -495
- package/build/init.js +16 -0
- package/build/install-bridge-conductor-answers.js +4 -0
- package/build/install-bridge-conductor-apply.js +10 -0
- package/build/install-bridge-conductor-assessment.js +84 -0
- package/build/install-bridge-conductor-contracts.js +9 -1
- package/build/install-bridge-conductor-setup.js +103 -3
- package/build/install-bridge-conductor.js +440 -812
- package/build/install-bridge.js +4 -11
- package/build/language-catalog.generated.js +2649 -0
- package/build/mcp-host-config.js +54 -37
- package/build/phase-context-git-probe.js +16 -0
- package/build/pipelines.generated.js +47 -19
- package/build/plan-execution-ledger.js +35 -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/plane/plane-freshness.js +43 -26
- package/build/printed-remedy-commands.js +17 -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/secret-redaction.js +3 -0
- package/build/server.js +7946 -0
- package/build/setup-epic.js +41 -8
- package/build/start-tickets-prereqs.js +3 -6
- package/build/test-support/console-guard.js +30 -0
- package/build/test-support/create-preview-world.js +232 -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/ticket-delivery.js +65 -0
- package/build/v2-readiness-requirements.js +39 -5
- package/build/version.generated.js +3 -3
- package/build/worktree-core.js +51 -7
- package/docs/EPIC-IMPLEMENTER.md +150 -2
- package/docs/epic-implementer/getting-started.md +5 -1
- package/package.json +3 -3
- package/pipelines/implement-ticket.json +2 -2
- package/pipelines/learn-repository.json +19 -1
|
@@ -52,6 +52,7 @@ import { classifyMergeTree } from "./merge-tree-classifier.js";
|
|
|
52
52
|
import { RECONCILE_OVERLAP_PAYLOAD_SCHEMA_VERSION, } from "./reconcile-overlap-types.js";
|
|
53
53
|
import { runRequiredVerificationCommands } from "./required-verification.js";
|
|
54
54
|
import { validateWorkerFinalization } from "./worker-finalization.js";
|
|
55
|
+
import { captureExecutorMergeIndex, executorAllowedTreePathspecs, stageExecutorAllowedTree, unstageExecutorExcludedPaths, } from "./permissions.js";
|
|
55
56
|
import { payloadWorkerDatabaseConfigOption } from "./worker-database-config.js";
|
|
56
57
|
export const RECONCILE_OVERLAP_JOB_TYPE = "reconcile_overlap";
|
|
57
58
|
/** Result-envelope bounds, mirrored from the server's result model. */
|
|
@@ -81,17 +82,6 @@ const CI_WAIT_POLL_INTERVAL_MS = 30_000;
|
|
|
81
82
|
/** Finalization settling: GitHub updates a PR's head a moment after the push. */
|
|
82
83
|
const FINALIZATION_ATTEMPTS = 6;
|
|
83
84
|
const FINALIZATION_RETRY_DELAY_MS = 2_000;
|
|
84
|
-
/**
|
|
85
|
-
* Paths the wrapper never stages: the executor's own per-worktree artifacts. They
|
|
86
|
-
* are also excluded through `.git/info/exclude`, but a foreign repository's
|
|
87
|
-
* `.gitignore` may not name `.mcp.json`, so the pathspec is the second line.
|
|
88
|
-
*/
|
|
89
|
-
const WRAPPER_STAGE_EXCLUDES = [
|
|
90
|
-
":(exclude).conductor",
|
|
91
|
-
":(exclude).mcp.json",
|
|
92
|
-
":(exclude).cursor/mcp.json",
|
|
93
|
-
":(exclude).claude/settings.local.json",
|
|
94
|
-
];
|
|
95
85
|
const SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
|
|
96
86
|
class PayloadError extends Error {
|
|
97
87
|
}
|
|
@@ -365,6 +355,9 @@ export function createReconcileOverlapDriver(job, payload, seams) {
|
|
|
365
355
|
failingCommandNames: [],
|
|
366
356
|
editedReasons: new Map(),
|
|
367
357
|
};
|
|
358
|
+
// BAPI-1732: the protected-path index state of THIS attempt's conflicted merge.
|
|
359
|
+
// `null` means "not captured", which is different from a captured empty snapshot.
|
|
360
|
+
let mergeSnapshot = null;
|
|
368
361
|
const commands = verificationCommandUnion(payload.child, payload.peer);
|
|
369
362
|
// BAPI-1521: the root payload's declaration, with presence kept (absent for an
|
|
370
363
|
// older payload, which keeps the compatibility constants).
|
|
@@ -543,15 +536,35 @@ export function createReconcileOverlapDriver(job, payload, seams) {
|
|
|
543
536
|
}
|
|
544
537
|
return runs;
|
|
545
538
|
};
|
|
539
|
+
/** The shared staging scope: the whole tree minus the executor's protected paths. */
|
|
540
|
+
const stageScope = () => executorAllowedTreePathspecs();
|
|
541
|
+
/**
|
|
542
|
+
* Run a shared index-protection helper through the abort- and budget-aware git
|
|
543
|
+
* wrapper. A cancellation propagates unchanged; any other failure is `false`.
|
|
544
|
+
*/
|
|
545
|
+
const protectIndex = async (ctx, run) => {
|
|
546
|
+
try {
|
|
547
|
+
await run((args) => git(ctx, args));
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
catch (err) {
|
|
551
|
+
if (err instanceof ReconcileOverlapAborted)
|
|
552
|
+
throw err;
|
|
553
|
+
return false;
|
|
554
|
+
}
|
|
555
|
+
};
|
|
546
556
|
const commitStaged = async (ctx, message) => {
|
|
547
557
|
const r = await git(ctx, ["commit", "--no-verify", "--no-edit", "-m", message]);
|
|
548
558
|
if (r.exitCode !== 0)
|
|
549
559
|
return null;
|
|
550
560
|
return revParse(ctx, "HEAD");
|
|
551
561
|
};
|
|
562
|
+
/** `true` when changes are staged, `false` when none, `null` when the check failed. */
|
|
552
563
|
const stagedChanges = async (ctx) => {
|
|
553
564
|
const r = await git(ctx, ["diff", "--cached", "--quiet"]);
|
|
554
|
-
|
|
565
|
+
if (r.exitCode === 0)
|
|
566
|
+
return false;
|
|
567
|
+
return r.exitCode === 1 ? true : null;
|
|
555
568
|
};
|
|
556
569
|
/** Read both remote heads immediately before the push. */
|
|
557
570
|
const readRemoteHeads = async (ctx) => {
|
|
@@ -590,7 +603,7 @@ export function createReconcileOverlapDriver(job, payload, seams) {
|
|
|
590
603
|
while (ctx.remainingMs() > CI_WAIT_MARGIN_MS && !ctx.signal.aborted) {
|
|
591
604
|
let response;
|
|
592
605
|
try {
|
|
593
|
-
response = await seams.pollProviderChecks(sha);
|
|
606
|
+
response = await seams.pollProviderChecks(sha, payload.requiredChecks);
|
|
594
607
|
}
|
|
595
608
|
catch (err) {
|
|
596
609
|
if (err instanceof ProviderChecksUnobservable)
|
|
@@ -755,6 +768,20 @@ export function createReconcileOverlapDriver(job, payload, seams) {
|
|
|
755
768
|
return finish(fail(ReconcileOverlapMergeFailed, "merged", "the merge did not record the required epic commit"));
|
|
756
769
|
}
|
|
757
770
|
if (classification.kind === "conflicted") {
|
|
771
|
+
mergeSnapshot = null;
|
|
772
|
+
let captured = null;
|
|
773
|
+
try {
|
|
774
|
+
captured = await captureExecutorMergeIndex((args) => git(ctx, args));
|
|
775
|
+
}
|
|
776
|
+
catch (err) {
|
|
777
|
+
if (err instanceof ReconcileOverlapAborted)
|
|
778
|
+
throw err;
|
|
779
|
+
}
|
|
780
|
+
if (captured === null) {
|
|
781
|
+
await resetToChildHead(ctx);
|
|
782
|
+
return finish(fail(ReconcileOverlapMergeFailed, "merged", "the merge's protected index state could not be captured"));
|
|
783
|
+
}
|
|
784
|
+
mergeSnapshot = captured;
|
|
758
785
|
facts.mode = "conflicted";
|
|
759
786
|
facts.workerInvoked = true;
|
|
760
787
|
facts.preWorkerHead = payload.childHead;
|
|
@@ -787,7 +814,7 @@ export function createReconcileOverlapDriver(job, payload, seams) {
|
|
|
787
814
|
await writeReport(ctx, conflictReport(failing));
|
|
788
815
|
// `.conductor/` holds the executor's own report for the worker; it is not a
|
|
789
816
|
// change to the candidate.
|
|
790
|
-
const status = await git(ctx, ["status", "--porcelain", "--",
|
|
817
|
+
const status = await git(ctx, ["status", "--porcelain", "--", ...stageScope()]);
|
|
791
818
|
if (status.exitCode !== 0 || status.stdout.trim().length > 0) {
|
|
792
819
|
await resetToChildHead(ctx);
|
|
793
820
|
return finish(fail(ReconcileOverlapMergeFailed, "checked", "the worktree was not clean at the merge commit"));
|
|
@@ -822,7 +849,20 @@ export function createReconcileOverlapDriver(job, payload, seams) {
|
|
|
822
849
|
// Stage ONLY the resolved conflict paths: the merge commit is the
|
|
823
850
|
// conflict resolution, and any other repair becomes its own commit.
|
|
824
851
|
if (conflictPaths.length > 0) {
|
|
825
|
-
|
|
852
|
+
// `-f`: a conflicted protected path is tracked and unmerged, but `info/exclude`
|
|
853
|
+
// also names it, and Git refuses an ignored path without it.
|
|
854
|
+
const staged = await git(ctx, ["add", "-A", "-f", "--", ...conflictPaths]);
|
|
855
|
+
if (staged.exitCode !== 0) {
|
|
856
|
+
await resetToChildHead(ctx);
|
|
857
|
+
return fail(ReconcileOverlapMergeFailed, "worker-completed", "the resolved conflict paths could not be staged");
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
// BAPI-1732: undo anything the worker staged in protected paths, while
|
|
861
|
+
// keeping what the merge itself put there and the worker's resolutions.
|
|
862
|
+
const snapshot = mergeSnapshot;
|
|
863
|
+
if (snapshot === null || !(await protectIndex(ctx, (gitCall) => unstageExecutorExcludedPaths(gitCall, snapshot)))) {
|
|
864
|
+
await resetToChildHead(ctx);
|
|
865
|
+
return fail(ReconcileOverlapMergeFailed, "worker-completed", "the merge's protected index state could not be restored");
|
|
826
866
|
}
|
|
827
867
|
const unmerged = await git(ctx, ["ls-files", "-u"]);
|
|
828
868
|
if (unmerged.exitCode !== 0 || unmerged.stdout.trim().length > 0) {
|
|
@@ -837,9 +877,22 @@ export function createReconcileOverlapDriver(job, payload, seams) {
|
|
|
837
877
|
facts.mergeCommitSha = mergeCommit;
|
|
838
878
|
}
|
|
839
879
|
// Any remaining worker repair: one ordinary commit ON TOP of the merge.
|
|
840
|
-
await
|
|
841
|
-
if (await
|
|
880
|
+
const repairStaged = await protectIndex(ctx, (gitCall) => stageExecutorAllowedTree(gitCall));
|
|
881
|
+
if (!repairStaged || !(await protectIndex(ctx, (gitCall) => unstageExecutorExcludedPaths(gitCall)))) {
|
|
882
|
+
await resetToChildHead(ctx);
|
|
883
|
+
return fail(ReconcileOverlapMergeFailed, "worker-completed", "the worker's repair could not be staged safely");
|
|
884
|
+
}
|
|
885
|
+
const repairChanges = await stagedChanges(ctx);
|
|
886
|
+
if (repairChanges === null) {
|
|
887
|
+
await resetToChildHead(ctx);
|
|
888
|
+
return fail(ReconcileOverlapMergeFailed, "worker-completed", "the staged repair could not be inspected");
|
|
889
|
+
}
|
|
890
|
+
if (repairChanges) {
|
|
842
891
|
const repairPaths = await git(ctx, ["diff", "--cached", "--name-only", "-z"]);
|
|
892
|
+
if (repairPaths.exitCode !== 0) {
|
|
893
|
+
await resetToChildHead(ctx);
|
|
894
|
+
return fail(ReconcileOverlapMergeFailed, "worker-completed", "the repair's paths could not be listed");
|
|
895
|
+
}
|
|
843
896
|
const repairReason = facts.failingCommandNames.length > 0
|
|
844
897
|
? `repair for failing check(s): ${facts.failingCommandNames.join(", ")}`
|
|
845
898
|
: "repair after conflict resolution";
|
|
@@ -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.
|
|
@@ -378,7 +392,7 @@ const UNREADABLE = Symbol("unreadable");
|
|
|
378
392
|
const ROOT_KEYS = [
|
|
379
393
|
"type", "subtype", "session_id", "parent_tool_use_id", "message", "content",
|
|
380
394
|
"task_id", "tool_use_id", "status", "patch", "task_type", "is_backgrounded",
|
|
381
|
-
"owned_by_subagent", "tasks", "tool_use_result",
|
|
395
|
+
"owned_by_subagent", "tasks", "tool_use_result", "tool_result_meta",
|
|
382
396
|
];
|
|
383
397
|
const BLOCK_KEYS = [
|
|
384
398
|
"type", "id", "name", "tool_use_id", "is_error", "input", "text", "content",
|
|
@@ -608,7 +622,8 @@ function createStructuralParser() {
|
|
|
608
622
|
};
|
|
609
623
|
const endDrop = () => {
|
|
610
624
|
dropActive = false;
|
|
611
|
-
// Bounded message metadata (usage, model, id)
|
|
625
|
+
// Bounded message metadata (usage, model, id) and the recognized top-level
|
|
626
|
+
// `tool_result_meta` are charged to the unexplained budget only.
|
|
612
627
|
if (dropCount > MAX_OVERSIZE_SCALAR_CHARS && dropRec.w !== "meta") {
|
|
613
628
|
if (proj.large.length >= MAX_OVERSIZE_DROPPED_PATHS)
|
|
614
629
|
return reject();
|
|
@@ -670,6 +685,10 @@ function createStructuralParser() {
|
|
|
670
685
|
// A user event's top-level copy of the tool output; only the block's ids carry meaning.
|
|
671
686
|
if (k === "tool_use_result")
|
|
672
687
|
return drop({ w: "tur", src: "", i: 0, k }, true);
|
|
688
|
+
// BAPI-1742: bounded top-level Edit/Write completion metadata. Recognized so it
|
|
689
|
+
// is discarded, but still charged to the unexplained budget, never retained.
|
|
690
|
+
if (k === "tool_result_meta")
|
|
691
|
+
return drop({ w: "meta", src: "", i: 0, k }, false);
|
|
673
692
|
return drop({ w: "top", src: "", i: 0, k }, false);
|
|
674
693
|
case "message":
|
|
675
694
|
if (k === "content")
|
|
@@ -1210,6 +1229,10 @@ export function createRequiredWorkLedger(init) {
|
|
|
1210
1229
|
resultDelivered: false,
|
|
1211
1230
|
failedByResult: false,
|
|
1212
1231
|
erroredBeforeLaunch: false,
|
|
1232
|
+
monitorTimeoutMs: null,
|
|
1233
|
+
terminalAt: null,
|
|
1234
|
+
stoppedByWorker: false,
|
|
1235
|
+
stoppedByTeardown: false,
|
|
1213
1236
|
...spec,
|
|
1214
1237
|
required: spec.required ?? !isOptional(spec.kind, spec.inputDigest),
|
|
1215
1238
|
};
|
|
@@ -1304,6 +1327,13 @@ export function createRequiredWorkLedger(init) {
|
|
|
1304
1327
|
real.resultDelivered = true;
|
|
1305
1328
|
if (real.launchedAt === null && ph.launchedAt !== null && real.state === "pending")
|
|
1306
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;
|
|
1307
1337
|
if (TERMINAL_STATES.has(ph.state))
|
|
1308
1338
|
return applyTerminal(real, ph.state);
|
|
1309
1339
|
return "applied";
|
|
@@ -1405,7 +1435,10 @@ export function createRequiredWorkLedger(init) {
|
|
|
1405
1435
|
track(id, { toolUseId: id, taskId: null, kind: "bash_bg", inputDigest, background: true, placeholder: false });
|
|
1406
1436
|
}
|
|
1407
1437
|
else if (name === "Monitor") {
|
|
1408
|
-
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);
|
|
1409
1442
|
}
|
|
1410
1443
|
else if (name === "TaskStop") {
|
|
1411
1444
|
// R13: the worker's OWN stop request. It turns a later stop into
|
|
@@ -1623,6 +1656,18 @@ export function createRequiredWorkLedger(init) {
|
|
|
1623
1656
|
}
|
|
1624
1657
|
if (next === "stopped" && workerStops.has(o.key))
|
|
1625
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
|
+
}
|
|
1626
1671
|
// BAPI-1455: a killed foreground call can deliver its error result before
|
|
1627
1672
|
// the lifecycle `stopped`. The lifecycle names the real end, so a
|
|
1628
1673
|
// result-derived `failed` is refined to `stopped` (one ending, not two).
|
|
@@ -1815,6 +1860,42 @@ export function createRequiredWorkLedger(init) {
|
|
|
1815
1860
|
return { o, state: replaceable && succeededLater(o) ? "replaced" : own };
|
|
1816
1861
|
});
|
|
1817
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);
|
|
1818
1899
|
// --- public API -----------------------------------------------------------
|
|
1819
1900
|
// --- oversize lines (BAPI-1586) -------------------------------------------
|
|
1820
1901
|
let oversizeParser = null;
|
|
@@ -1997,7 +2078,7 @@ export function createRequiredWorkLedger(init) {
|
|
|
1997
2078
|
// BAPI-1455: a command whose own terminal result was delivered is resolved,
|
|
1998
2079
|
// whatever its exit code; its recorded state is kept as it is.
|
|
1999
2080
|
const delivered = (o, state) => o.resultDelivered && DELIVERY_RESOLVABLE_KINDS.has(o.kind) && DELIVERY_RESOLVABLE_STATES.has(state);
|
|
2000
|
-
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) }));
|
|
2001
2082
|
const anyConflict = effective.some(({ state }) => state === "conflict");
|
|
2002
2083
|
let execution = unresolvedRequired || anyConflict || snap.required.length > 0 || unexplainedPlaceholder ? "incomplete" : "complete";
|
|
2003
2084
|
if (!sufficient && execution === "complete")
|
|
@@ -2008,7 +2089,7 @@ export function createRequiredWorkLedger(init) {
|
|
|
2008
2089
|
kind: o.kind,
|
|
2009
2090
|
// A task still pending when the verdict is taken never reached a terminal.
|
|
2010
2091
|
state: state === "pending" ? "unknown" : state,
|
|
2011
|
-
required: o
|
|
2092
|
+
required: effectiveRequired(o, state),
|
|
2012
2093
|
input_digest: o.inputDigest,
|
|
2013
2094
|
...(delivered(o, state) ? { result_delivered: true } : {}),
|
|
2014
2095
|
}));
|
|
@@ -2059,7 +2140,9 @@ export function createRequiredWorkLedger(init) {
|
|
|
2059
2140
|
...(facts.verificationFacts ? { verification_facts: facts.verificationFacts } : {}),
|
|
2060
2141
|
};
|
|
2061
2142
|
const withNullCause = { ...candidate, cause: null };
|
|
2062
|
-
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 });
|
|
2063
2146
|
return boundEnvelope({ ...candidate, cause });
|
|
2064
2147
|
};
|
|
2065
2148
|
return {
|
|
@@ -17,6 +17,7 @@ import { createWorktreeForTicket } from "../worktree-core.js";
|
|
|
17
17
|
import { ContinuationLineageMismatch, ContinuationWorktreeMissing, ExecutorNamedError, WorktreeLostBeforePush, } from "./job-errors.js";
|
|
18
18
|
import { assertWorktreeOnBranch, listGitWorktrees, findWorktreeByBranch, remoteBranchExists as remoteBranchExistsDefault, } from "./worktree-inspection.js";
|
|
19
19
|
import { ciFixContextError } from "./prompt-spec.js";
|
|
20
|
+
import { executorAllowedTreePathspecs, stageExecutorAllowedTree, unstageExecutorExcludedPaths, } from "./permissions.js";
|
|
20
21
|
import { fastForwardRetainedWorktreeToBoundHead } from "./worktree.js";
|
|
21
22
|
/** The canonical WIP checkpoint commit message (executor-run, deterministic). */
|
|
22
23
|
export const RESUME_WIP_COMMIT_MESSAGE = "wip: auto-checkpoint before resume";
|
|
@@ -117,19 +118,42 @@ export async function recreateResumeWorktreeFromPushedBranch(job, expectedBranch
|
|
|
117
118
|
throw new ExecutorNamedError(WorktreeLostBeforePush, row.error ?? `failed to recreate worktree for '${expectedBranch}' from origin`);
|
|
118
119
|
}
|
|
119
120
|
/**
|
|
120
|
-
* Commit any dirty state as a deterministic WIP checkpoint so the
|
|
121
|
-
* is always clean and complete.
|
|
122
|
-
*
|
|
121
|
+
* Commit any ALLOWED dirty state as a deterministic WIP checkpoint so the
|
|
122
|
+
* injected diff is always clean and complete. NEVER discards work.
|
|
123
|
+
*
|
|
124
|
+
* Executor-owned and host files (see `EXECUTOR_STAGE_EXCLUDES`) are never
|
|
125
|
+
* committed: forbidden changes an earlier worker left staged are first returned
|
|
126
|
+
* to HEAD in the index (working-tree files are untouched), and status, staging,
|
|
127
|
+
* and the commit all use the shared root-relative exclusions. A tree dirty only in
|
|
128
|
+
* excluded paths is a normal no-op, `{ committed: false }`. `committed: true` is
|
|
129
|
+
* returned only after `git commit` exits successfully. Any failed Git step throws
|
|
130
|
+
* a plain `Error`, which callers' existing catches handle.
|
|
123
131
|
*/
|
|
124
132
|
export async function autoCheckpointDirtyState(worktreePath, seams, message = RESUME_WIP_COMMIT_MESSAGE) {
|
|
125
|
-
const
|
|
133
|
+
const git = (args) => seams.runCommand("git", args, { cwd: worktreePath });
|
|
134
|
+
const fail = (step) => new Error(`checkpoint ${step} failed`);
|
|
135
|
+
const scope = executorAllowedTreePathspecs();
|
|
136
|
+
await unstageExecutorExcludedPaths(git);
|
|
137
|
+
const status = await git(["status", "--porcelain", "--", ...scope]);
|
|
138
|
+
if (status.exitCode !== 0)
|
|
139
|
+
throw fail("status");
|
|
126
140
|
if (status.stdout.trim().length === 0) {
|
|
127
141
|
return { committed: false };
|
|
128
142
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
143
|
+
try {
|
|
144
|
+
await stageExecutorAllowedTree(git);
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
throw fail("staging");
|
|
148
|
+
}
|
|
149
|
+
const staged = await git(["diff", "--cached", "--quiet"]);
|
|
150
|
+
if (staged.exitCode === 0)
|
|
151
|
+
return { committed: false };
|
|
152
|
+
if (staged.exitCode !== 1)
|
|
153
|
+
throw fail("diff");
|
|
154
|
+
const committed = await git(["commit", "--no-verify", "-m", message]);
|
|
155
|
+
if (committed.exitCode !== 0)
|
|
156
|
+
throw fail("commit");
|
|
133
157
|
return { committed: true };
|
|
134
158
|
}
|
|
135
159
|
/** Read `git log --oneline origin/<base>..HEAD` in the worktree. */
|