rungate 0.3.0 → 0.4.0
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/lib/brief-precedence.ts +114 -0
- package/lib/ci-checkout.ts +27 -1
- package/lib/compliance-backfill.ts +16 -4
- package/lib/compliance-report.ts +109 -8
- package/lib/config-readers.ts +86 -0
- package/lib/conformity.ts +364 -27
- package/lib/create-sc.ts +20 -25
- package/lib/decomposition-waves.ts +197 -0
- package/lib/gate-check-audit.ts +190 -0
- package/lib/generators/agents-md.ts +10 -5
- package/lib/issue-extraction.ts +368 -0
- package/lib/phase2-decomposition.ts +270 -0
- package/lib/prior-branch.ts +24 -1
- package/lib/prove-label-gate.ts +93 -0
- package/lib/release-preflight.ts +102 -0
- package/lib/rungate-schema.ts +13 -1
- package/lib/scaffold/pre-push-hook.ts +165 -0
- package/lib/scaffold/steps.ts +42 -101
- package/lib/scope-denylist.ts +258 -0
- package/lib/task-completion-checks.ts +50 -3
- package/lib/typescript-project.ts +233 -0
- package/lib/verified-push.ts +179 -2
- package/lib/worktree-cleanup.ts +201 -19
- package/lib/worktree-repo.ts +300 -0
- package/package.json +4 -2
package/lib/verified-push.ts
CHANGED
|
@@ -83,7 +83,11 @@ export type PushOutcome =
|
|
|
83
83
|
/** The push ran and exited non-zero. */
|
|
84
84
|
| { kind: "rejected"; detail: string }
|
|
85
85
|
/** The push exited zero and the remote does not carry HEAD. */
|
|
86
|
-
| { kind: "unconfirmed"; sha: string; remoteSha: string | null; detail: string }
|
|
86
|
+
| { kind: "unconfirmed"; sha: string; remoteSha: string | null; detail: string }
|
|
87
|
+
/** The upstream names a ref other than the branch's own. Nothing was pushed. */
|
|
88
|
+
| { kind: "ref-mismatch"; branch: string; remoteRef: string; detail: string }
|
|
89
|
+
/** The caller expected a different repository than the tree's origin. */
|
|
90
|
+
| { kind: "repo-mismatch"; expected: string; actual: string | null; detail: string };
|
|
87
91
|
|
|
88
92
|
/**
|
|
89
93
|
* The outcomes that mean a commit this run reported on may not be on the
|
|
@@ -96,12 +100,122 @@ export const OUTCOMES_LEAVING_WORK_LOCAL: ReadonlySet<PushOutcome["kind"]> = new
|
|
|
96
100
|
"not-attempted",
|
|
97
101
|
"rejected",
|
|
98
102
|
"unconfirmed",
|
|
103
|
+
"ref-mismatch",
|
|
104
|
+
"repo-mismatch",
|
|
99
105
|
]);
|
|
100
106
|
|
|
101
107
|
export function leftWorkLocal(outcome: PushOutcome): boolean {
|
|
102
108
|
return OUTCOMES_LEAVING_WORK_LOCAL.has(outcome.kind);
|
|
103
109
|
}
|
|
104
110
|
|
|
111
|
+
/**
|
|
112
|
+
* The `owner/name` a git remote URL points at, or `null` if it names none.
|
|
113
|
+
*
|
|
114
|
+
* Returns `null` rather than a best guess for anything it cannot parse —
|
|
115
|
+
* including the filesystem paths every fixture in the suite uses as its
|
|
116
|
+
* origin. `repoMatches` turns `null` into "does not match", so an
|
|
117
|
+
* unrecognised remote refuses a push instead of permitting one, which is the
|
|
118
|
+
* direction this is allowed to be wrong in (#430).
|
|
119
|
+
*/
|
|
120
|
+
export function parseRemoteSlug(url: string): string | null {
|
|
121
|
+
const trimmed = url.trim();
|
|
122
|
+
if (!trimmed) return null;
|
|
123
|
+
// scp-style (`git@host:owner/name.git`) and URL-style, with any userinfo —
|
|
124
|
+
// which is where a token lives on an HTTPS remote — discarded.
|
|
125
|
+
const m = trimmed.match(/^(?:[a-z+]+:\/\/)?(?:[^@/]*@)?[^/:]+[:/](.+?)(?:\.git)?\/?$/i);
|
|
126
|
+
const path = m?.[1];
|
|
127
|
+
if (!path) return null;
|
|
128
|
+
const parts = path.split("/").filter(Boolean);
|
|
129
|
+
if (parts.length !== 2) return null;
|
|
130
|
+
return `${parts[0]}/${parts[1]}`.toLowerCase();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Whether a remote URL names the given `owner/name`. Unparseable matches nothing. */
|
|
134
|
+
export function repoMatches(url: string, slug: string): boolean {
|
|
135
|
+
const parsed = parseRemoteSlug(url);
|
|
136
|
+
return parsed !== null && parsed === slug.trim().toLowerCase();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The `owner/name` of a tree's `origin`, or `null` when it cannot be read.
|
|
141
|
+
*
|
|
142
|
+
* Reads the CONFIGURED url. `originPushUrl` reads the effective one, and
|
|
143
|
+
* `originIdentity` requires them to agree — see there for why one alone is
|
|
144
|
+
* not enough.
|
|
145
|
+
*/
|
|
146
|
+
export function originSlug(cwd: string, env: NodeJS.ProcessEnv = process.env): string | null {
|
|
147
|
+
const r = runner(cwd, env)(["config", "--get", "remote.origin.url"], 5000);
|
|
148
|
+
return r.ok ? parseRemoteSlug(r.output) : null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The url a push to `origin` would actually use, rewrites applied. */
|
|
152
|
+
export function originPushUrl(cwd: string, env: NodeJS.ProcessEnv = process.env): string | null {
|
|
153
|
+
const r = runner(cwd, env)(["remote", "get-url", "--push", "origin"], 5000);
|
|
154
|
+
return r.ok && r.output.trim() !== "" ? r.output.trim() : null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Whether this tree is `expected`, judged on the url the push will use.
|
|
159
|
+
*
|
|
160
|
+
* ## Why two urls and not one
|
|
161
|
+
*
|
|
162
|
+
* The first version of this read only `config --get remote.origin.url`, on
|
|
163
|
+
* the reasoning that `url.<base>.insteadOf` rewrites are a local transport
|
|
164
|
+
* alias — a mirror, a proxy, a cache — and not a statement about which
|
|
165
|
+
* project you are shipping. That reasoning is fine and the conclusion was
|
|
166
|
+
* wrong, because it made the authorisation check read a different value than
|
|
167
|
+
* the action uses: `git push` resolves rewrites, so a rewrite pointing
|
|
168
|
+
* `https://github.com/owner/name` at some other repository would satisfy
|
|
169
|
+
* this check and then write that other repository. A guard that approves one
|
|
170
|
+
* destination and permits a push to another is not a guard.
|
|
171
|
+
*
|
|
172
|
+
* So both are read and both must agree. A rewrite in play is a refusal, not
|
|
173
|
+
* an approval — the mirror user loses an auto-push and runs `git push`
|
|
174
|
+
* themselves, which is the cost this file is allowed to impose
|
|
175
|
+
* (`leftWorkLocal` already reports the work may be local).
|
|
176
|
+
*
|
|
177
|
+
* ## What this does NOT check
|
|
178
|
+
*
|
|
179
|
+
* The host. `issueRepo` is `owner/name` and carries no host, so there is
|
|
180
|
+
* nothing here to compare one against: `https://example.invalid/owner/name`
|
|
181
|
+
* and `https://github.com/owner/name` are the same slug to this function.
|
|
182
|
+
* That is a real limit and is stated rather than papered over. It is not the
|
|
183
|
+
* only thing standing between a run and the wrong forge — the GitHub client
|
|
184
|
+
* in `lib/github.ts` has its own base url and credentials, and a push to an
|
|
185
|
+
* unexpected host needs credentials for that host. Hardcoding `github.com`
|
|
186
|
+
* here would bind the harness to one forge for a check that is about repo
|
|
187
|
+
* identity, which is the wrong place to make that decision.
|
|
188
|
+
*/
|
|
189
|
+
export function originIdentity(
|
|
190
|
+
cwd: string,
|
|
191
|
+
expected: string,
|
|
192
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
193
|
+
): { ok: true; slug: string } | { ok: false; detail: string } {
|
|
194
|
+
const configured = originSlug(cwd, env);
|
|
195
|
+
if (configured === null) {
|
|
196
|
+
return { ok: false, detail: "this tree's origin url is unreadable or names no owner/name" };
|
|
197
|
+
}
|
|
198
|
+
const want = expected.trim().toLowerCase();
|
|
199
|
+
if (configured !== want) {
|
|
200
|
+
return { ok: false, detail: `this tree's origin is ${configured}` };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const pushUrl = originPushUrl(cwd, env);
|
|
204
|
+
if (pushUrl === null) {
|
|
205
|
+
return { ok: false, detail: `this tree's origin is ${configured} but its push url is unreadable` };
|
|
206
|
+
}
|
|
207
|
+
const pushSlug = parseRemoteSlug(pushUrl);
|
|
208
|
+
if (pushSlug !== configured) {
|
|
209
|
+
return {
|
|
210
|
+
ok: false,
|
|
211
|
+
detail: `this tree's origin is configured as ${configured} but a push would go to ` +
|
|
212
|
+
`${redactSecrets(pushUrl)} — a \`url.<base>.insteadOf\` rewrite is in play, so the ` +
|
|
213
|
+
`repository this check approved is not the one the push would write`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
return { ok: true, slug: configured };
|
|
217
|
+
}
|
|
218
|
+
|
|
105
219
|
/** The sha `ls-remote` reports for a ref, or null if its output names none. */
|
|
106
220
|
export function parseLsRemoteSha(output: string, ref: string): string | null {
|
|
107
221
|
for (const line of output.split("\n")) {
|
|
@@ -159,6 +273,33 @@ export function classifyPush(raw: PushReadings): PushOutcome {
|
|
|
159
273
|
const remoteRef = r.remoteRef.output.trim();
|
|
160
274
|
const upstream = `${remoteName} ${remoteRef}`;
|
|
161
275
|
|
|
276
|
+
// #429 — the push below is `HEAD:${remoteRef}`, and `remoteRef` is whatever
|
|
277
|
+
// `branch.<b>.merge` says. `git checkout -b <name> origin/main`, the
|
|
278
|
+
// ordinary way to start work here, sets that to `refs/heads/main` — so an
|
|
279
|
+
// unattended auto-push on a feature branch wrote `main` and reported a
|
|
280
|
+
// verified success, which it was, to the wrong ref. Four `wip:` commits
|
|
281
|
+
// reached origin/main that way on 2026-10-15 from a session that never ran
|
|
282
|
+
// `git push`.
|
|
283
|
+
//
|
|
284
|
+
// Refusing rather than rewriting the target: a branch whose upstream names
|
|
285
|
+
// a different ref may well be deliberate — this repo has several — and
|
|
286
|
+
// guessing which the operator meant is the kind of repair
|
|
287
|
+
// `.claude/rules/checks-must-be-able-to-fail.md` warns about. This is
|
|
288
|
+
// bookkeeping, not a gate, so the refusal costs a manual `git push` and
|
|
289
|
+
// `leftWorkLocal` already says the work may be local.
|
|
290
|
+
if (remoteRef !== `refs/heads/${branch}`) {
|
|
291
|
+
return {
|
|
292
|
+
kind: "ref-mismatch",
|
|
293
|
+
branch,
|
|
294
|
+
remoteRef,
|
|
295
|
+
detail: `branch ${branch} is configured to track ${upstream}, so an auto-push would write ` +
|
|
296
|
+
`${remoteRef} from a branch that is not it. Nothing was pushed. This is usually a branch ` +
|
|
297
|
+
`created with \`git checkout -b ${branch} origin/main\`, which sets the upstream to main ` +
|
|
298
|
+
`rather than to a ref of its own name (#429). Push explicitly with ` +
|
|
299
|
+
`\`git push -u origin ${branch}\` if that is what you meant.`,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
162
303
|
if (!r.ahead.ok) {
|
|
163
304
|
return {
|
|
164
305
|
kind: "unmeasured",
|
|
@@ -318,11 +459,47 @@ function runner(cwd: string, env: NodeJS.ProcessEnv) {
|
|
|
318
459
|
*/
|
|
319
460
|
export function verifiedPush(
|
|
320
461
|
cwd: string,
|
|
321
|
-
opts: { env?: NodeJS.ProcessEnv } = {},
|
|
462
|
+
opts: { env?: NodeJS.ProcessEnv; expectRepo?: string } = {},
|
|
322
463
|
): PushOutcome {
|
|
323
464
|
const env = opts.env ?? process.env;
|
|
324
465
|
const git = runner(cwd, env);
|
|
325
466
|
|
|
467
|
+
// #430 — the caller says which repository it believes it is shipping, and
|
|
468
|
+
// that belief is compared against the tree rather than assumed to match it.
|
|
469
|
+
//
|
|
470
|
+
// `gates/orchestrator.ts` pushes `process.cwd()` and guards on
|
|
471
|
+
// `issueRepo && issue > 0`. `test/contract.test.ts` runs the ship gate with
|
|
472
|
+
// `issueRepo: "test/repo"` and `issue: 9998` — both truthy — from inside
|
|
473
|
+
// the real rungate checkout, so running the test suite pushed to origin.
|
|
474
|
+
// The cwd choice is right and stays; what was missing is this comparison.
|
|
475
|
+
//
|
|
476
|
+
// Checked FIRST, before any other reading, because "this is not the repo
|
|
477
|
+
// you meant" invalidates everything downstream — an ahead-count against the
|
|
478
|
+
// wrong tree's upstream is not a fact worth reporting.
|
|
479
|
+
//
|
|
480
|
+
// The opt-in is `!== undefined` and nothing more. The first draft also
|
|
481
|
+
// required `.trim() !== ""`, which made a blank `expectRepo` SKIP the
|
|
482
|
+
// check — malformed input disabling the guard, which is the fail-open
|
|
483
|
+
// shape this repo keeps finding (`.claude/rules/checks-must-be-able-to-
|
|
484
|
+
// fail.md`). A caller that passed `""` because its config was empty would
|
|
485
|
+
// have got the old unconditional push back, silently. Asking the question
|
|
486
|
+
// is the caller's decision; once asked, an unanswerable version of it is a
|
|
487
|
+
// refusal.
|
|
488
|
+
if (opts.expectRepo !== undefined) {
|
|
489
|
+
const identity = originIdentity(cwd, opts.expectRepo, env);
|
|
490
|
+
if (!identity.ok) {
|
|
491
|
+
return {
|
|
492
|
+
kind: "repo-mismatch",
|
|
493
|
+
expected: opts.expectRepo,
|
|
494
|
+
actual: originSlug(cwd, env),
|
|
495
|
+
detail: `the caller is shipping ${JSON.stringify(opts.expectRepo)} and ${identity.detail}. ` +
|
|
496
|
+
`Nothing was pushed. A run whose issue repository and working tree disagree is either a ` +
|
|
497
|
+
`fixture pointed at a real checkout or a real run in the wrong directory, and both are ` +
|
|
498
|
+
`reasons not to write a remote (#430).`,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
326
503
|
const localSha = git(["rev-parse", "HEAD"], 5000);
|
|
327
504
|
const branch = git(["symbolic-ref", "--short", "HEAD"], 5000);
|
|
328
505
|
const b = branch.output.trim();
|
package/lib/worktree-cleanup.ts
CHANGED
|
@@ -9,13 +9,22 @@
|
|
|
9
9
|
* GitHub issue #564
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { readdirSync, statSync, existsSync } from "fs";
|
|
12
|
+
import { readdirSync, realpathSync, statSync, existsSync } from "fs";
|
|
13
13
|
import { join } from "path";
|
|
14
14
|
import { spawnSync } from "child_process";
|
|
15
15
|
|
|
16
16
|
export interface CleanupResult {
|
|
17
17
|
removed: string[];
|
|
18
18
|
kept: string[];
|
|
19
|
+
/**
|
|
20
|
+
* Entries the run never judged — too new, or not a directory (#431).
|
|
21
|
+
*
|
|
22
|
+
* These used to `continue` without being recorded anywhere, so
|
|
23
|
+
* `removed + kept` did not add up to the number of entries and the printed
|
|
24
|
+
* line said "144 kept" against 149 worktrees. A bucket that exists only as
|
|
25
|
+
* the gap between two other numbers is a bucket nobody reconciles.
|
|
26
|
+
*/
|
|
27
|
+
skipped: string[];
|
|
19
28
|
errors: string[];
|
|
20
29
|
}
|
|
21
30
|
|
|
@@ -72,6 +81,151 @@ export function unpushedKeepReason(
|
|
|
72
81
|
return null;
|
|
73
82
|
}
|
|
74
83
|
|
|
84
|
+
/** What `origin` knows about a branch. `unpushedCommitCount` collapses two of these. */
|
|
85
|
+
export type OriginState =
|
|
86
|
+
/** The repo has no `origin`, so "pushed" is not a question that applies. */
|
|
87
|
+
| { kind: "no-origin" }
|
|
88
|
+
/** A git invocation failed. Not a verdict. */
|
|
89
|
+
| { kind: "unknown" }
|
|
90
|
+
/** Commits exist here and nowhere else. */
|
|
91
|
+
| { kind: "ahead"; count: number }
|
|
92
|
+
/** Every commit on the branch is also on an `origin/*` ref. */
|
|
93
|
+
| { kind: "on-origin" };
|
|
94
|
+
|
|
95
|
+
export function originState(projectRoot: string, branch: string): OriginState {
|
|
96
|
+
const remotes = spawnSync("git", ["remote"], { cwd: projectRoot, encoding: "utf-8", timeout: 5000 });
|
|
97
|
+
if (remotes.status !== 0) return { kind: "unknown" };
|
|
98
|
+
if (!remotes.stdout.split("\n").map(r => r.trim()).includes("origin")) return { kind: "no-origin" };
|
|
99
|
+
|
|
100
|
+
const count = spawnSync("git", ["rev-list", "--count", branch, "--not", "--remotes=origin"], {
|
|
101
|
+
cwd: projectRoot, encoding: "utf-8", timeout: 10_000,
|
|
102
|
+
});
|
|
103
|
+
if (count.status !== 0) return { kind: "unknown" };
|
|
104
|
+
const n = parseInt(count.stdout.trim(), 10);
|
|
105
|
+
if (!Number.isFinite(n)) return { kind: "unknown" };
|
|
106
|
+
return n > 0 ? { kind: "ahead", count: n } : { kind: "on-origin" };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Why a clean, unlocked worktree must be kept, or null to remove it (#431).
|
|
111
|
+
*
|
|
112
|
+
* ## Why "unmerged" stopped being a reason on its own
|
|
113
|
+
*
|
|
114
|
+
* 149 worktrees had accumulated here, 71 of them clean and unmerged, the
|
|
115
|
+
* oldest 13.7 days old, and the cleanup removed none of them for weeks. The
|
|
116
|
+
* rule was "never remove an unmerged branch", which reads as prudence and is
|
|
117
|
+
* actually the wrong question: **`git worktree remove` deletes a checkout,
|
|
118
|
+
* not a branch.** The ref survives, its commits survive, and `git checkout`
|
|
119
|
+
* brings it all back. Nothing is lost.
|
|
120
|
+
*
|
|
121
|
+
* What CAN be lost is work that exists in exactly one place: uncommitted
|
|
122
|
+
* changes — checked before this is called — and commits that never reached
|
|
123
|
+
* origin. So the real safety property is "is every commit on this branch
|
|
124
|
+
* also somewhere else", and asking it directly both protects more (an
|
|
125
|
+
* unpushed branch merged into a local-only main was removable before) and
|
|
126
|
+
* permits more (an unmerged fan-out branch fully pushed is just a stale
|
|
127
|
+
* directory).
|
|
128
|
+
*
|
|
129
|
+
* `merged` is still load-bearing in exactly one case: a repo with no
|
|
130
|
+
* `origin` at all, where "also somewhere else" has no meaning and the only
|
|
131
|
+
* remaining evidence is that main contains the work. Without that arm this
|
|
132
|
+
* change would delete unmerged local-only work, which is the regression that
|
|
133
|
+
* gets a safety check reverted — and `unpushedCommitCount` returns `0` for a
|
|
134
|
+
* remote-less repo, so it would have looked exactly like a pushed branch.
|
|
135
|
+
*
|
|
136
|
+
* One exported binding, so there is one thing to mutate.
|
|
137
|
+
*/
|
|
138
|
+
export function removalKeepReason(
|
|
139
|
+
entry: string,
|
|
140
|
+
branch: string,
|
|
141
|
+
merged: boolean,
|
|
142
|
+
origin: OriginState,
|
|
143
|
+
): string | null {
|
|
144
|
+
switch (origin.kind) {
|
|
145
|
+
case "unknown":
|
|
146
|
+
return `${entry} (could not tell whether ${branch} is on origin)`;
|
|
147
|
+
case "ahead":
|
|
148
|
+
return `${entry} (${origin.count} commit(s) on ${branch} not on origin)`;
|
|
149
|
+
case "no-origin":
|
|
150
|
+
return merged ? null : `${entry} (no origin remote, and ${branch} is not merged into main)`;
|
|
151
|
+
case "on-origin":
|
|
152
|
+
// Merged or not. The branch ref is not touched by `worktree remove`.
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The worktree paths git reports as locked, or `null` if it could not say.
|
|
159
|
+
*
|
|
160
|
+
* `null` is not an empty set. An unreadable listing means every claim is
|
|
161
|
+
* invisible, and the caller keeps everything rather than treating silence as
|
|
162
|
+
* permission — the same rule `unpushedCommitCount` follows for `null`.
|
|
163
|
+
*/
|
|
164
|
+
export function lockedWorktreePaths(projectRoot: string): Set<string> | null {
|
|
165
|
+
const list = spawnSync("git", ["worktree", "list", "--porcelain"], {
|
|
166
|
+
cwd: projectRoot, encoding: "utf-8", timeout: 15_000,
|
|
167
|
+
});
|
|
168
|
+
if (list.status !== 0) return null;
|
|
169
|
+
|
|
170
|
+
const paths = new Set<string>();
|
|
171
|
+
let current: string | null = null;
|
|
172
|
+
for (const line of list.stdout.split("\n")) {
|
|
173
|
+
if (line.startsWith("worktree ")) current = line.slice("worktree ".length).trim();
|
|
174
|
+
else if (line.startsWith("locked") && current) paths.add(realPath(current));
|
|
175
|
+
}
|
|
176
|
+
return paths;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Why a worktree must be kept on the strength of locks alone, or null (#431).
|
|
181
|
+
*
|
|
182
|
+
* One exported binding for the same reason `unpushedKeepReason` is one: the
|
|
183
|
+
* `null` arm — git could not list the worktrees, so every claim is
|
|
184
|
+
* invisible — needs git to fail, which no fixture can stage. Inline, all
|
|
185
|
+
* three lock mutations scored ZERO red, including reverting the realpath
|
|
186
|
+
* comparison that makes the check work at all on macOS. Driven directly,
|
|
187
|
+
* each arm is a case.
|
|
188
|
+
*
|
|
189
|
+
* `null` keeps everything. An empty set means "nothing is claimed" and
|
|
190
|
+
* would licence removing all of it, so the two must not collapse.
|
|
191
|
+
*/
|
|
192
|
+
export function lockKeepReason(
|
|
193
|
+
entry: string,
|
|
194
|
+
worktreePath: string,
|
|
195
|
+
locked: ReadonlySet<string> | null,
|
|
196
|
+
): string | null {
|
|
197
|
+
if (locked === null) return `${entry} (could not read which worktrees are locked)`;
|
|
198
|
+
// Resolved on BOTH sides. git reports worktree paths with symlinks
|
|
199
|
+
// resolved; the caller builds this one with `join`. On macOS the temp
|
|
200
|
+
// directory is under a `/var` → `/private/var` symlink, so a raw
|
|
201
|
+
// comparison never matches and the check is inert on the platform it was
|
|
202
|
+
// written on.
|
|
203
|
+
return locked.has(realPath(worktreePath)) ? `${entry} (locked)` : null;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* A path with symlinks resolved, or the path itself if it cannot be read.
|
|
208
|
+
*
|
|
209
|
+
* git reports worktree paths resolved. On macOS the system temp directory —
|
|
210
|
+
* and therefore every fixture in the suite — lives under `/var`, which is a
|
|
211
|
+
* symlink to `/private/var`, so a set built from git's output and probed
|
|
212
|
+
* with a `join()`ed path never matches. The lock check would have been
|
|
213
|
+
* silently inert on the platform it was written on: a guard that cannot see
|
|
214
|
+
* what it guards, which is the defect class this file keeps meeting.
|
|
215
|
+
*
|
|
216
|
+
* Falling back to the raw path on failure is deliberate. A miss here means
|
|
217
|
+
* a lock is not seen, so it must not ALSO swallow the error silently — the
|
|
218
|
+
* caller keeps anything it cannot classify, and an unreadable path fails
|
|
219
|
+
* the `existsSync`/`statSync` above long before this matters.
|
|
220
|
+
*/
|
|
221
|
+
function realPath(p: string): string {
|
|
222
|
+
try {
|
|
223
|
+
return realpathSync(p);
|
|
224
|
+
} catch {
|
|
225
|
+
return p;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
75
229
|
/**
|
|
76
230
|
* Clean up stale git worktrees from .claude/worktrees/.
|
|
77
231
|
*
|
|
@@ -83,9 +237,22 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
|
|
|
83
237
|
const result: CleanupResult = {
|
|
84
238
|
removed: [],
|
|
85
239
|
kept: [],
|
|
240
|
+
skipped: [],
|
|
86
241
|
errors: [],
|
|
87
242
|
};
|
|
88
243
|
|
|
244
|
+
// `git worktree lock` is the one durable claim a running job can make on a
|
|
245
|
+
// worktree, and it is git's own — `worktree remove` refuses a locked tree
|
|
246
|
+
// regardless of what this function decides (#431). Read once, up front,
|
|
247
|
+
// because the per-entry alternative is 149 subprocesses.
|
|
248
|
+
//
|
|
249
|
+
// Read from the porcelain listing rather than by probing for the admin
|
|
250
|
+
// file: a lock recorded in a form this function does not recognise would
|
|
251
|
+
// look unlocked, and "I did not see a claim" must not be how a claim gets
|
|
252
|
+
// ignored. A listing that cannot be read leaves the set null, and a null
|
|
253
|
+
// set keeps everything.
|
|
254
|
+
const locked = lockedWorktreePaths(projectRoot);
|
|
255
|
+
|
|
89
256
|
const worktreesDir = join(projectRoot, ".claude", "worktrees");
|
|
90
257
|
|
|
91
258
|
// Early exit if directory doesn't exist
|
|
@@ -109,13 +276,18 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
|
|
|
109
276
|
// Skip if not a directory
|
|
110
277
|
try {
|
|
111
278
|
const stat = statSync(worktreePath);
|
|
112
|
-
if (!stat.isDirectory())
|
|
279
|
+
if (!stat.isDirectory()) {
|
|
280
|
+
result.skipped.push(`${entry} (not a directory)`);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
113
283
|
|
|
114
284
|
// Check age filter if provided
|
|
115
285
|
if (maxAgeMs !== undefined) {
|
|
116
286
|
const ageMs = now - stat.mtimeMs;
|
|
117
287
|
if (ageMs < maxAgeMs) {
|
|
118
|
-
// Too new,
|
|
288
|
+
// Too new to judge. Recorded, because an entry counted in neither
|
|
289
|
+
// bucket is how the printed totals stopped adding up (#431).
|
|
290
|
+
result.skipped.push(`${entry} (younger than the age filter)`);
|
|
119
291
|
continue;
|
|
120
292
|
}
|
|
121
293
|
}
|
|
@@ -124,6 +296,16 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
|
|
|
124
296
|
continue;
|
|
125
297
|
}
|
|
126
298
|
|
|
299
|
+
// A locked worktree is a claim by something still using it. git refuses
|
|
300
|
+
// to remove one anyway; recording it as KEPT rather than letting the
|
|
301
|
+
// removal fail into `errors` keeps "something owns this" distinct from
|
|
302
|
+
// "the removal broke" (#431).
|
|
303
|
+
const lockReason = lockKeepReason(entry, worktreePath, locked);
|
|
304
|
+
if (lockReason) {
|
|
305
|
+
result.kept.push(lockReason);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
|
|
127
309
|
// Check for uncommitted changes
|
|
128
310
|
const statusCheck = spawnSync("git", ["status", "--porcelain"], {
|
|
129
311
|
cwd: worktreePath,
|
|
@@ -197,21 +379,14 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
|
|
|
197
379
|
continue;
|
|
198
380
|
}
|
|
199
381
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
// A branch merged into a main that was never pushed exists in exactly one
|
|
209
|
-
// place on earth, and this function runs unattended from a SessionStart
|
|
210
|
-
// hook. #228 and #232 are both about work that was correct and became
|
|
211
|
-
// unreachable; removing a worktree whose commits are not on origin is the
|
|
212
|
-
// same loss with a tidier name.
|
|
213
|
-
const keepReason = unpushedKeepReason(
|
|
214
|
-
entry, branchName, unpushedCommitCount(projectRoot, branchName),
|
|
382
|
+
// Merged into LOCAL main is not the same as safe to delete (#232), and
|
|
383
|
+
// UNmerged is not the same as unsafe to delete (#431). Both questions go
|
|
384
|
+
// to one decider, because they were two `if`s in a row and the first one
|
|
385
|
+
// short-circuited the second — the unmerged arm returned before the
|
|
386
|
+
// origin check ever ran, so the weaker proxy was deciding everything and
|
|
387
|
+
// the stronger property was dead code for every branch that needed it.
|
|
388
|
+
const keepReason = removalKeepReason(
|
|
389
|
+
entry, branchName, mergeCheck.status === 0, originState(projectRoot, branchName),
|
|
215
390
|
);
|
|
216
391
|
if (keepReason) {
|
|
217
392
|
result.kept.push(keepReason);
|
|
@@ -244,7 +419,14 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
|
|
|
244
419
|
}
|
|
245
420
|
|
|
246
421
|
// Log summary
|
|
247
|
-
|
|
422
|
+
// All four buckets. `removed + kept + skipped + errors` is the number of
|
|
423
|
+
// entries examined, which is the property test/worktree-cleanup-orphans
|
|
424
|
+
// asserts — a summary that cannot be reconciled against the directory is
|
|
425
|
+
// how 149 worktrees hid behind "144 kept" (#431).
|
|
426
|
+
console.log(
|
|
427
|
+
`Worktree cleanup: ${result.removed.length} removed, ${result.kept.length} kept, ` +
|
|
428
|
+
`${result.skipped.length} skipped, ${result.errors.length} error(s)`,
|
|
429
|
+
);
|
|
248
430
|
|
|
249
431
|
return result;
|
|
250
432
|
}
|