@on-par/factory-core 0.9.14-next.2 → 0.9.14-next.20
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/dist/checkers/baseline.d.ts +3 -2
- package/dist/checkers/baseline.d.ts.map +1 -1
- package/dist/checkers/baseline.js +5 -5
- package/dist/checkers/baseline.js.map +1 -1
- package/dist/checkers/run-command.d.ts +4 -1
- package/dist/checkers/run-command.d.ts.map +1 -1
- package/dist/checkers/run-command.js +14 -2
- package/dist/checkers/run-command.js.map +1 -1
- package/dist/config/build-route.d.ts +35 -0
- package/dist/config/build-route.d.ts.map +1 -0
- package/dist/config/build-route.js +47 -0
- package/dist/config/build-route.js.map +1 -0
- package/dist/config/config-schema-lint.d.ts.map +1 -1
- package/dist/config/config-schema-lint.js +31 -27
- package/dist/config/config-schema-lint.js.map +1 -1
- package/dist/config/effort.d.ts.map +1 -1
- package/dist/config/effort.js +0 -1
- package/dist/config/effort.js.map +1 -1
- package/dist/config/example.d.ts.map +1 -1
- package/dist/config/example.js +8 -1
- package/dist/config/example.js.map +1 -1
- package/dist/config/index.d.ts +5 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +42 -75
- package/dist/config/index.js.map +1 -1
- package/dist/config/policy.d.ts +4 -6
- package/dist/config/policy.d.ts.map +1 -1
- package/dist/config/policy.js +29 -38
- package/dist/config/policy.js.map +1 -1
- package/dist/config/precedence.d.ts +17 -0
- package/dist/config/precedence.d.ts.map +1 -0
- package/dist/config/precedence.js +13 -0
- package/dist/config/precedence.js.map +1 -0
- package/dist/config/provider-order-exports.d.ts +3 -0
- package/dist/config/provider-order-exports.d.ts.map +1 -0
- package/dist/config/provider-order-exports.js +3 -0
- package/dist/config/provider-order-exports.js.map +1 -0
- package/dist/config/provider-order.d.ts +38 -0
- package/dist/config/provider-order.d.ts.map +1 -0
- package/dist/config/provider-order.js +99 -0
- package/dist/config/provider-order.js.map +1 -0
- package/dist/config/repo-config-file.d.ts +4 -0
- package/dist/config/repo-config-file.d.ts.map +1 -1
- package/dist/config/repo-config-file.js +35 -0
- package/dist/config/repo-config-file.js.map +1 -1
- package/dist/config/repo-harnesses.js +3 -3
- package/dist/config/repo-harnesses.js.map +1 -1
- package/dist/config/repo.d.ts +10 -18
- package/dist/config/repo.d.ts.map +1 -1
- package/dist/config/repo.js +127 -164
- package/dist/config/repo.js.map +1 -1
- package/dist/config/sandbox-schema.d.ts +30 -0
- package/dist/config/sandbox-schema.d.ts.map +1 -0
- package/dist/config/sandbox-schema.js +39 -0
- package/dist/config/sandbox-schema.js.map +1 -0
- package/dist/config/v2-models.d.ts +76 -0
- package/dist/config/v2-models.d.ts.map +1 -0
- package/dist/config/v2-models.js +125 -0
- package/dist/config/v2-models.js.map +1 -0
- package/dist/config/v2.d.ts +7 -0
- package/dist/config/v2.d.ts.map +1 -1
- package/dist/config/v2.js +2 -101
- package/dist/config/v2.js.map +1 -1
- package/dist/daemon/execution-config.d.ts +6 -0
- package/dist/daemon/execution-config.d.ts.map +1 -1
- package/dist/daemon/run-runtime.d.ts +6 -0
- package/dist/daemon/run-runtime.d.ts.map +1 -1
- package/dist/eval/index.d.ts +2 -1
- package/dist/eval/index.d.ts.map +1 -1
- package/dist/eval/index.js +2 -1
- package/dist/eval/index.js.map +1 -1
- package/dist/eval/judge.d.ts +0 -1
- package/dist/eval/judge.d.ts.map +1 -1
- package/dist/eval/judge.js +2 -6
- package/dist/eval/judge.js.map +1 -1
- package/dist/events/kinds.d.ts +1 -1
- package/dist/events/kinds.d.ts.map +1 -1
- package/dist/events/kinds.js +3 -0
- package/dist/events/kinds.js.map +1 -1
- package/dist/harness/catalog.d.ts +17 -0
- package/dist/harness/catalog.d.ts.map +1 -1
- package/dist/harness/catalog.js +35 -8
- package/dist/harness/catalog.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +9 -7
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +7 -4
- package/dist/internal.js.map +1 -1
- package/dist/kpis/index.d.ts.map +1 -1
- package/dist/kpis/index.js +8 -10
- package/dist/kpis/index.js.map +1 -1
- package/dist/kpis/steerability.d.ts.map +1 -1
- package/dist/kpis/steerability.js +4 -3
- package/dist/kpis/steerability.js.map +1 -1
- package/dist/models/index.d.ts +3 -2
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +7 -15
- package/dist/models/index.js.map +1 -1
- package/dist/phases/build.d.ts.map +1 -1
- package/dist/phases/build.js +2 -0
- package/dist/phases/build.js.map +1 -1
- package/dist/phases/ship.d.ts.map +1 -1
- package/dist/phases/ship.js +24 -16
- package/dist/phases/ship.js.map +1 -1
- package/dist/queue/activity.d.ts +21 -0
- package/dist/queue/activity.d.ts.map +1 -1
- package/dist/queue/activity.js +44 -0
- package/dist/queue/activity.js.map +1 -1
- package/dist/queue/claim-liveness.d.ts +17 -0
- package/dist/queue/claim-liveness.d.ts.map +1 -0
- package/dist/queue/claim-liveness.js +25 -0
- package/dist/queue/claim-liveness.js.map +1 -0
- package/dist/queue/prerequisite-order.d.ts +30 -0
- package/dist/queue/prerequisite-order.d.ts.map +1 -0
- package/dist/queue/prerequisite-order.js +92 -0
- package/dist/queue/prerequisite-order.js.map +1 -0
- package/dist/queue/stale-claims.d.ts.map +1 -1
- package/dist/queue/stale-claims.js +6 -18
- package/dist/queue/stale-claims.js.map +1 -1
- package/dist/queue/unpark.d.ts +5 -0
- package/dist/queue/unpark.d.ts.map +1 -1
- package/dist/queue/unpark.js +10 -0
- package/dist/queue/unpark.js.map +1 -1
- package/dist/router/context-ceiling.d.ts +18 -0
- package/dist/router/context-ceiling.d.ts.map +1 -0
- package/dist/router/context-ceiling.js +29 -0
- package/dist/router/context-ceiling.js.map +1 -0
- package/dist/router/index.d.ts +14 -20
- package/dist/router/index.d.ts.map +1 -1
- package/dist/router/index.js +56 -310
- package/dist/router/index.js.map +1 -1
- package/dist/run/adopt-pr.d.ts +1 -0
- package/dist/run/adopt-pr.d.ts.map +1 -1
- package/dist/run/adopt-pr.js +21 -30
- package/dist/run/adopt-pr.js.map +1 -1
- package/dist/run/check-verdict.d.ts +13 -0
- package/dist/run/check-verdict.d.ts.map +1 -0
- package/dist/run/check-verdict.js +27 -0
- package/dist/run/check-verdict.js.map +1 -0
- package/dist/run/ci-rework-loop.d.ts +7 -3
- package/dist/run/ci-rework-loop.d.ts.map +1 -1
- package/dist/run/ci-rework-loop.js +4 -11
- package/dist/run/ci-rework-loop.js.map +1 -1
- package/dist/run/lane-file-guard.d.ts +2 -2
- package/dist/run/lane-file-guard.d.ts.map +1 -1
- package/dist/run/lane-file-guard.js +4 -9
- package/dist/run/lane-file-guard.js.map +1 -1
- package/dist/run/lane-install.d.ts +31 -0
- package/dist/run/lane-install.d.ts.map +1 -0
- package/dist/run/lane-install.js +49 -0
- package/dist/run/lane-install.js.map +1 -0
- package/dist/run/park-comment.d.ts +20 -1
- package/dist/run/park-comment.d.ts.map +1 -1
- package/dist/run/park-comment.js +25 -5
- package/dist/run/park-comment.js.map +1 -1
- package/dist/run/ports.d.ts +2 -0
- package/dist/run/ports.d.ts.map +1 -1
- package/dist/run/ports.js +1 -0
- package/dist/run/ports.js.map +1 -1
- package/dist/run/pr-lookup.d.ts +56 -0
- package/dist/run/pr-lookup.d.ts.map +1 -0
- package/dist/run/pr-lookup.js +67 -0
- package/dist/run/pr-lookup.js.map +1 -0
- package/dist/run/run-issue.d.ts +3 -0
- package/dist/run/run-issue.d.ts.map +1 -1
- package/dist/run/run-issue.js +86 -65
- package/dist/run/run-issue.js.map +1 -1
- package/dist/run/state.d.ts +19 -0
- package/dist/run/state.d.ts.map +1 -1
- package/dist/run/state.js +52 -2
- package/dist/run/state.js.map +1 -1
- package/dist/run/terminal-events.d.ts +4 -0
- package/dist/run/terminal-events.d.ts.map +1 -0
- package/dist/run/terminal-events.js +15 -0
- package/dist/run/terminal-events.js.map +1 -0
- package/dist/sandbox/index.d.ts +2 -0
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +5 -1
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/writable-paths.d.ts +11 -0
- package/dist/sandbox/writable-paths.d.ts.map +1 -0
- package/dist/sandbox/writable-paths.js +45 -0
- package/dist/sandbox/writable-paths.js.map +1 -0
- package/dist/sim/pipeline.js +1 -1
- package/dist/sim/pipeline.js.map +1 -1
- package/dist/usage/index.js +1 -1
- package/dist/usage/index.js.map +1 -1
- package/dist/utils/index.d.ts +9 -2
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +7 -6
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lane-removal.d.ts +16 -0
- package/dist/utils/lane-removal.d.ts.map +1 -0
- package/dist/utils/lane-removal.js +62 -0
- package/dist/utils/lane-removal.js.map +1 -0
- package/dist/utils/median.d.ts +4 -0
- package/dist/utils/median.d.ts.map +1 -0
- package/dist/utils/median.js +11 -0
- package/dist/utils/median.js.map +1 -0
- package/dist/utils/worktree-gc.d.ts +1 -171
- package/dist/utils/worktree-gc.d.ts.map +1 -1
- package/dist/utils/worktree-gc.js +2 -739
- package/dist/utils/worktree-gc.js.map +1 -1
- package/dist/utils/worktree-keeps.d.ts +1 -19
- package/dist/utils/worktree-keeps.d.ts.map +1 -1
- package/dist/utils/worktree-keeps.js +2 -64
- package/dist/utils/worktree-keeps.js.map +1 -1
- package/dist/utils/worktree-name.d.ts +1 -9
- package/dist/utils/worktree-name.d.ts.map +1 -1
- package/dist/utils/worktree-name.js +2 -30
- package/dist/utils/worktree-name.js.map +1 -1
- package/dist/worktree/worktree-gc-decide.d.ts +40 -0
- package/dist/worktree/worktree-gc-decide.d.ts.map +1 -0
- package/dist/worktree/worktree-gc-decide.js +120 -0
- package/dist/worktree/worktree-gc-decide.js.map +1 -0
- package/dist/worktree/worktree-gc-evidence.d.ts +94 -0
- package/dist/worktree/worktree-gc-evidence.d.ts.map +1 -0
- package/dist/worktree/worktree-gc-evidence.js +218 -0
- package/dist/worktree/worktree-gc-evidence.js.map +1 -0
- package/dist/worktree/worktree-gc-issues.d.ts +26 -0
- package/dist/worktree/worktree-gc-issues.d.ts.map +1 -0
- package/dist/worktree/worktree-gc-issues.js +51 -0
- package/dist/worktree/worktree-gc-issues.js.map +1 -0
- package/dist/worktree/worktree-gc-scrub.d.ts +10 -0
- package/dist/worktree/worktree-gc-scrub.d.ts.map +1 -0
- package/dist/worktree/worktree-gc-scrub.js +89 -0
- package/dist/worktree/worktree-gc-scrub.js.map +1 -0
- package/dist/worktree/worktree-gc-types.d.ts +144 -0
- package/dist/worktree/worktree-gc-types.d.ts.map +1 -0
- package/dist/worktree/worktree-gc-types.js +33 -0
- package/dist/worktree/worktree-gc-types.js.map +1 -0
- package/dist/worktree/worktree-gc.d.ts +32 -0
- package/dist/worktree/worktree-gc.d.ts.map +1 -0
- package/dist/worktree/worktree-gc.js +321 -0
- package/dist/worktree/worktree-gc.js.map +1 -0
- package/dist/worktree/worktree-keeps.d.ts +20 -0
- package/dist/worktree/worktree-keeps.d.ts.map +1 -0
- package/dist/worktree/worktree-keeps.js +65 -0
- package/dist/worktree/worktree-keeps.js.map +1 -0
- package/dist/worktree/worktree-name.d.ts +10 -0
- package/dist/worktree/worktree-name.d.ts.map +1 -0
- package/dist/worktree/worktree-name.js +31 -0
- package/dist/worktree/worktree-name.js.map +1 -0
- package/package.json +5 -5
- package/dist/utils/worktree-gc-issues.d.ts +0 -22
- package/dist/utils/worktree-gc-issues.d.ts.map +0 -1
- package/dist/utils/worktree-gc-issues.js +0 -80
- package/dist/utils/worktree-gc-issues.js.map +0 -1
|
@@ -1,740 +1,3 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, renameSync, rmSync, statSync, writeSync, } from 'node:fs';
|
|
4
|
-
import { basename, join, resolve } from 'node:path';
|
|
5
|
-
import { promisify } from 'node:util';
|
|
6
|
-
import { getFactoryPaths } from '../config/index.js';
|
|
7
|
-
import { factoryBranchPrefixes, shellEscape } from './index.js';
|
|
8
|
-
import { removeMicroVm } from './microvm.js';
|
|
9
|
-
import { resolveActiveClaim, resolveIssueDisposition, resolveIssueExistence, } from './worktree-gc-issues.js';
|
|
10
|
-
import { isFactoryDirName } from './worktree-name.js';
|
|
11
|
-
import { readWorktreeKeeps, releaseWorktreeKeeps } from './worktree-keeps.js';
|
|
12
|
-
const exec = promisify(execCb);
|
|
13
|
-
/** Dedupes resolveIssueDisposition's lookup-failure warning across repeated sweeps — the factory
|
|
14
|
-
* loop calls sweepWorktrees every iteration, and a worktree tied to a nonexistent issue number
|
|
15
|
-
* fails that lookup on every one of them. The first failure for a given issue since the last
|
|
16
|
-
* reconcile-clear warns in full; every following one folds into a one-line "suppressed N"
|
|
17
|
-
* summary instead of repeating the same text. `reconcile()` drops an issue's tracking once it's
|
|
18
|
-
* no longer among the sweep's candidates, so a later re-appearance (or a different worktree
|
|
19
|
-
* reusing the number) warns in full again. Keyed by issue number, not by worktree path, since
|
|
20
|
-
* the failing lookup is per-issue (see ADR, this PR). */
|
|
21
|
-
export class IssueWarnDedup {
|
|
22
|
-
counts = new Map();
|
|
23
|
-
/** Records one occurrence for `issue`. Returns true the first time since the last
|
|
24
|
-
* reconcile-clear (caller should log the full warning), false thereafter. */
|
|
25
|
-
record(issue) {
|
|
26
|
-
const count = (this.counts.get(issue) ?? 0) + 1;
|
|
27
|
-
this.counts.set(issue, count);
|
|
28
|
-
return count === 1;
|
|
29
|
-
}
|
|
30
|
-
/** Occurrences suppressed for `issue` since its last full warning (0 before the second one). */
|
|
31
|
-
suppressedCount(issue) {
|
|
32
|
-
return Math.max(0, (this.counts.get(issue) ?? 0) - 1);
|
|
33
|
-
}
|
|
34
|
-
/** Drops tracking for every issue not in `activeIssues` — call once per sweep with the issue
|
|
35
|
-
* numbers still present among that sweep's candidates. */
|
|
36
|
-
reconcile(activeIssues) {
|
|
37
|
-
for (const issue of this.counts.keys()) {
|
|
38
|
-
if (!activeIssues.has(issue))
|
|
39
|
-
this.counts.delete(issue);
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
const defaultIssueWarnDedup = new IssueWarnDedup();
|
|
44
|
-
const CREDENTIAL_BASENAMES = new Set(['.git-credentials', '.npmrc']);
|
|
45
|
-
/** Removal reasons that prove the work reached the remote — the only ones whose local
|
|
46
|
-
* branch is safe to force-delete unconditionally. `ttl-expired` fires on age alone and is
|
|
47
|
-
* excluded: its branch may be the last reachable handle on unpushed commits. The issue-driven
|
|
48
|
-
* reasons (`issue-closed` / `issue-parked`) are also excluded here — they delete the branch
|
|
49
|
-
* only when the candidate's per-candidate `branchReapable` flag proved remote evidence at
|
|
50
|
-
* decision time. See ADR (this PR). */
|
|
51
|
-
const BRANCH_REAPABLE_REASONS = new Set(['merged', 'remote-gone']);
|
|
52
|
-
/** Reasons whose real-mode action is `'quarantine'` rather than `'remove'` — the two heuristic
|
|
53
|
-
* signals (#1355) that carry no merge/ancestry proof, unlike every other `GcReason`. */
|
|
54
|
-
const QUARANTINE_REASONS = new Set(['issue-not-found', 'no-active-claim']);
|
|
55
|
-
/** Where a quarantined worktree lands: `<state>/quarantine/`, matching every other runtime
|
|
56
|
-
* path's home under the resolved state dir (see `getFactoryPaths`). */
|
|
57
|
-
function quarantineRoot(repoRoot) {
|
|
58
|
-
return join(getFactoryPaths(repoRoot).state, 'quarantine');
|
|
59
|
-
}
|
|
60
|
-
/** The destination for a quarantined worktree: its own basename under `quarantineDir`, unless
|
|
61
|
-
* that name is already occupied (e.g. a prior quarantine nobody cleared), in which case a
|
|
62
|
-
* timestamp suffix disambiguates rather than overwriting or failing. */
|
|
63
|
-
function quarantineDestination(quarantineDir, worktreePath) {
|
|
64
|
-
const base = basename(worktreePath);
|
|
65
|
-
const dest = join(quarantineDir, base);
|
|
66
|
-
return existsSync(dest) ? join(quarantineDir, `${base}-${Date.now()}`) : dest;
|
|
67
|
-
}
|
|
68
|
-
export function parseWorktreeList(porcelain) {
|
|
69
|
-
const entries = [];
|
|
70
|
-
const blocks = porcelain
|
|
71
|
-
.split(/\n\s*\n/)
|
|
72
|
-
.map((b) => b.trim())
|
|
73
|
-
.filter(Boolean);
|
|
74
|
-
for (const block of blocks) {
|
|
75
|
-
let path = null;
|
|
76
|
-
let head = null;
|
|
77
|
-
let branch = null;
|
|
78
|
-
for (const line of block.split('\n')) {
|
|
79
|
-
if (line.startsWith('worktree ')) {
|
|
80
|
-
path = line.slice('worktree '.length).trim();
|
|
81
|
-
}
|
|
82
|
-
else if (line.startsWith('HEAD ')) {
|
|
83
|
-
head = line.slice('HEAD '.length).trim();
|
|
84
|
-
}
|
|
85
|
-
else if (line.startsWith('branch ')) {
|
|
86
|
-
branch = line
|
|
87
|
-
.slice('branch '.length)
|
|
88
|
-
.trim()
|
|
89
|
-
.replace(/^refs\/heads\//, '');
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
if (path) {
|
|
93
|
-
entries.push({ path, head, branch });
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
return entries;
|
|
97
|
-
}
|
|
98
|
-
export function findCredentialFiles(worktreePath) {
|
|
99
|
-
const found = [];
|
|
100
|
-
let topLevel;
|
|
101
|
-
try {
|
|
102
|
-
topLevel = readdirSync(worktreePath);
|
|
103
|
-
}
|
|
104
|
-
catch {
|
|
105
|
-
return found;
|
|
106
|
-
}
|
|
107
|
-
for (const name of topLevel) {
|
|
108
|
-
if (name === '.env' || name.startsWith('.env.') || CREDENTIAL_BASENAMES.has(name)) {
|
|
109
|
-
const filePath = join(worktreePath, name);
|
|
110
|
-
try {
|
|
111
|
-
// lstat, not stat: a symlinked `.env` must never lead the scrub outside the worktree.
|
|
112
|
-
if (lstatSync(filePath).isFile())
|
|
113
|
-
found.push(filePath);
|
|
114
|
-
}
|
|
115
|
-
catch { }
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
const claudeDir = join(worktreePath, '.claude');
|
|
119
|
-
if (isRealDirectory(claudeDir)) {
|
|
120
|
-
walkFiles(claudeDir, found);
|
|
121
|
-
}
|
|
122
|
-
return found;
|
|
123
|
-
}
|
|
124
|
-
function walkFiles(dir, found) {
|
|
125
|
-
let entries;
|
|
126
|
-
try {
|
|
127
|
-
entries = readdirSync(dir, { withFileTypes: true });
|
|
128
|
-
}
|
|
129
|
-
catch {
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
for (const entry of entries) {
|
|
133
|
-
const full = join(dir, entry.name);
|
|
134
|
-
if (entry.isDirectory()) {
|
|
135
|
-
walkFiles(full, found);
|
|
136
|
-
}
|
|
137
|
-
else if (entry.isFile()) {
|
|
138
|
-
found.push(full);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
function isRealDirectory(path) {
|
|
143
|
-
try {
|
|
144
|
-
return lstatSync(path).isDirectory();
|
|
145
|
-
}
|
|
146
|
-
catch {
|
|
147
|
-
return false;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
/** Zero a file in place through one fd opened with O_NOFOLLOW. The worktree's agent can swap
|
|
151
|
-
* a credential file for a symlink after `findCredentialFiles` walks it; a path-based
|
|
152
|
-
* stat + write would then zero the link's target (e.g. `~/.ssh/id_*`). Throws ELOOP on a
|
|
153
|
-
* symlink and refuses anything that is not a regular file. */
|
|
154
|
-
export function zeroFill(filePath) {
|
|
155
|
-
const fd = openSync(filePath, constants.O_WRONLY | constants.O_NOFOLLOW);
|
|
156
|
-
try {
|
|
157
|
-
const stat = fstatSync(fd);
|
|
158
|
-
if (!stat.isFile())
|
|
159
|
-
throw new Error(`refusing to zero-fill non-regular file ${filePath}`);
|
|
160
|
-
const zeros = Buffer.alloc(Math.min(stat.size, 64 * 1024));
|
|
161
|
-
let offset = 0;
|
|
162
|
-
while (offset < stat.size) {
|
|
163
|
-
offset += writeSync(fd, zeros, 0, Math.min(zeros.length, stat.size - offset), offset);
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
finally {
|
|
167
|
-
closeSync(fd);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
/** Zero-fill then delete. A symlink is unlinked without zeroing — rm removes the link, never
|
|
171
|
-
* its target. */
|
|
172
|
-
export function scrubFile(filePath) {
|
|
173
|
-
try {
|
|
174
|
-
zeroFill(filePath);
|
|
175
|
-
}
|
|
176
|
-
catch (err) {
|
|
177
|
-
if (err?.code !== 'ELOOP')
|
|
178
|
-
throw err;
|
|
179
|
-
}
|
|
180
|
-
rmSync(filePath, { force: true });
|
|
181
|
-
}
|
|
182
|
-
async function defaultRunCommand(cmd, opts) {
|
|
183
|
-
const { stdout } = await exec(cmd, opts);
|
|
184
|
-
return { stdout: stdout.toString() };
|
|
185
|
-
}
|
|
186
|
-
function safeExec(runCommand, cmd, opts) {
|
|
187
|
-
return runCommand(cmd, opts).catch(() => null);
|
|
188
|
-
}
|
|
189
|
-
async function resolveMainTip(runCommand, repoRoot) {
|
|
190
|
-
const result = await safeExec(runCommand, 'git rev-parse --verify origin/main', { cwd: repoRoot });
|
|
191
|
-
const sha = result?.stdout.trim() ?? '';
|
|
192
|
-
return sha === '' ? null : sha;
|
|
193
|
-
}
|
|
194
|
-
async function hasPriorPushEvidence(runCommand, repoRoot, branch) {
|
|
195
|
-
const trackingRef = await safeExec(runCommand, `git rev-parse --verify --quiet ${shellEscape(`refs/remotes/origin/${branch}`)}`, { cwd: repoRoot });
|
|
196
|
-
if (trackingRef !== null && trackingRef.stdout.trim() !== '')
|
|
197
|
-
return true;
|
|
198
|
-
const reflog = await safeExec(runCommand, `git reflog show --no-abbrev ${shellEscape(`refs/remotes/origin/${branch}`)}`, { cwd: repoRoot });
|
|
199
|
-
if (reflog !== null && reflog.stdout.trim() !== '')
|
|
200
|
-
return true;
|
|
201
|
-
const upstream = await safeExec(runCommand, `git config --get ${shellEscape(`branch.${branch}.merge`)}`, {
|
|
202
|
-
cwd: repoRoot,
|
|
203
|
-
});
|
|
204
|
-
// git sets branch.<name>.merge automatically at worktree-creation time from the start point
|
|
205
|
-
// (e.g. `git worktree add -b <branch> <path> origin/main` sets it to refs/heads/main), so a
|
|
206
|
-
// non-empty value alone is not proof of a push. Only `git push -u origin <branch>` points it at
|
|
207
|
-
// the branch's own ref — require that exact match.
|
|
208
|
-
return upstream !== null && upstream.stdout.trim() === `refs/heads/${branch}`;
|
|
209
|
-
}
|
|
210
|
-
/** GitHub's verdict on the branch's PRs. `null` when no client/repo is available or the query
|
|
211
|
-
* fails — the caller must then fall back to local evidence (fail-safe: keep on doubt). */
|
|
212
|
-
async function resolvePrState(octokit, repo, branch, log) {
|
|
213
|
-
if (!octokit || !repo)
|
|
214
|
-
return null;
|
|
215
|
-
const [owner, repoName] = repo.split('/');
|
|
216
|
-
try {
|
|
217
|
-
const { data } = await octokit.rest.pulls.list({
|
|
218
|
-
owner,
|
|
219
|
-
repo: repoName,
|
|
220
|
-
state: 'all',
|
|
221
|
-
head: `${owner}:${branch}`,
|
|
222
|
-
});
|
|
223
|
-
if (data.some((pr) => pr.state === 'open'))
|
|
224
|
-
return 'open';
|
|
225
|
-
const merged = data.find((pr) => pr.merged_at != null);
|
|
226
|
-
if (merged)
|
|
227
|
-
return 'merged';
|
|
228
|
-
if (data.some((pr) => pr.state === 'closed'))
|
|
229
|
-
return 'closed';
|
|
230
|
-
return 'none';
|
|
231
|
-
}
|
|
232
|
-
catch (err) {
|
|
233
|
-
log('warn', `worktree-gc: GitHub PR query failed for ${branch} (${err?.message ?? String(err)}) — using local evidence only`);
|
|
234
|
-
return null;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
/** The lane issue number a candidate belongs to: capture group 1 of the lane-branch shape
|
|
238
|
-
* `<prefix>/<n>-*`, falling back to a trailing `-<n>` in the directory basename (covers
|
|
239
|
-
* detached checkouts of factory-named paths). `null` when neither matches. */
|
|
240
|
-
function laneIssueNumber(entry, lanePattern) {
|
|
241
|
-
const fromBranch = entry.branch?.match(lanePattern);
|
|
242
|
-
if (fromBranch)
|
|
243
|
-
return Number(fromBranch[1]);
|
|
244
|
-
const fromPath = basename(entry.path).match(/-(\d+)$/);
|
|
245
|
-
return fromPath ? Number(fromPath[1]) : null;
|
|
246
|
-
}
|
|
247
|
-
/** A worktree is clean when it has no modified tracked files. `--untracked-files=no` deliberately
|
|
248
|
-
* ignores untracked build residue (node_modules, artifacts) — the "live work" signal is tracked-file
|
|
249
|
-
* modifications. A probe failure (`safeExec` null) ⇒ false ⇒ keep. */
|
|
250
|
-
export async function isWorktreeClean(runCommand, worktreePath) {
|
|
251
|
-
const result = await safeExec(runCommand, 'git status --porcelain --untracked-files=no', { cwd: worktreePath });
|
|
252
|
-
return result !== null && result.stdout.trim() === '';
|
|
253
|
-
}
|
|
254
|
-
/** Commits reachable from `rev` that are on no `origin` ref; null when the probe fails or is unparseable (⇒ keep). */
|
|
255
|
-
export async function countUnpushedCommits(runCommand, repoRoot, rev) {
|
|
256
|
-
const result = await safeExec(runCommand, `git rev-list --count ${shellEscape(rev)} --not --remotes=origin`, {
|
|
257
|
-
cwd: repoRoot,
|
|
258
|
-
});
|
|
259
|
-
const n = result === null ? NaN : Number.parseInt(result.stdout.trim(), 10);
|
|
260
|
-
return Number.isInteger(n) ? n : null;
|
|
261
|
-
}
|
|
262
|
-
/** True only when `head` has exactly 0 commits ahead of origin/main — a lane that has not committed
|
|
263
|
-
* yet (every lane starts at origin/main), never proof of a merge (#2964). Probe failure ⇒ false. */
|
|
264
|
-
export async function isZeroCommitLane(runCommand, repoRoot, head) {
|
|
265
|
-
if (head === null)
|
|
266
|
-
return false;
|
|
267
|
-
const result = await safeExec(runCommand, `git rev-list --count origin/main..${shellEscape(head)}`, {
|
|
268
|
-
cwd: repoRoot,
|
|
269
|
-
});
|
|
270
|
-
return result !== null && result.stdout.trim() === '0';
|
|
271
|
-
}
|
|
272
|
-
export async function sweepWorktrees(opts, deps = {}) {
|
|
273
|
-
const { runCommand = defaultRunCommand, now = () => Date.now(), log = () => { }, octokit, sandbox, issueWarnDedup = defaultIssueWarnDedup, } = deps;
|
|
274
|
-
const { repoRoot, ttlDays, dryRun = false, repo } = opts;
|
|
275
|
-
const { stdout } = await runCommand('git worktree list --porcelain', { cwd: repoRoot });
|
|
276
|
-
const entries = parseWorktreeList(stdout);
|
|
277
|
-
const repoRootResolved = resolve(repoRoot);
|
|
278
|
-
const repoBase = basename(repoRootResolved);
|
|
279
|
-
// Slugs are [a-z0-9-] only (branchPrefixSlug), so interpolating them into a regex is safe.
|
|
280
|
-
// Matches the resolved prefix and the legacy ship-it one.
|
|
281
|
-
const lanePattern = new RegExp('^(?:' + factoryBranchPrefixes(opts.branchPrefix).join('|') + ')/(\\d+)-');
|
|
282
|
-
const candidates = entries.filter((entry) => {
|
|
283
|
-
const entryPath = resolve(entry.path);
|
|
284
|
-
if (entryPath === repoRootResolved)
|
|
285
|
-
return false;
|
|
286
|
-
const base = basename(entryPath);
|
|
287
|
-
if (isFactoryDirName(repoBase, base, entry.branch, opts.branchPrefix))
|
|
288
|
-
return true;
|
|
289
|
-
// Legacy lane paths (<repo>-ship-it-<n>) predate the -factory- infix; there the checked-out
|
|
290
|
-
// lane-branch shape is what proves factory ownership — manual/* and experiment worktrees
|
|
291
|
-
// under a <repo>-* name never match it and are never candidates.
|
|
292
|
-
return base.startsWith(`${repoBase}-`) && entry.branch !== null && lanePattern.test(entry.branch);
|
|
293
|
-
});
|
|
294
|
-
// Reconcile the issue-warn dedup tracker to this sweep's live candidates before resolving any
|
|
295
|
-
// disposition, so a worktree that's gone (or an issue number no longer in play) drops its
|
|
296
|
-
// suppression state and a later re-appearance warns in full again (see ADR, this PR).
|
|
297
|
-
const activeIssueNumbers = new Set();
|
|
298
|
-
for (const entry of candidates) {
|
|
299
|
-
const issueNumber = laneIssueNumber(entry, lanePattern);
|
|
300
|
-
if (issueNumber !== null)
|
|
301
|
-
activeIssueNumbers.add(issueNumber);
|
|
302
|
-
}
|
|
303
|
-
issueWarnDedup.reconcile(activeIssueNumbers);
|
|
304
|
-
const removed = [];
|
|
305
|
-
const held = [];
|
|
306
|
-
let kept = 0;
|
|
307
|
-
const keepsFile = opts.keepsFile ?? getFactoryPaths(repoRoot).worktreeKeeps;
|
|
308
|
-
const keeps = new Map(readWorktreeKeeps(keepsFile, log).map((k) => [k.issue, k]));
|
|
309
|
-
const keptByRecord = [];
|
|
310
|
-
const releasedKeeps = new Map();
|
|
311
|
-
const mainTip = candidates.length > 0 ? await resolveMainTip(runCommand, repoRoot) : null;
|
|
312
|
-
// Per-branch GitHub verdicts, memoized across the sweep (one pulls.list per candidate branch).
|
|
313
|
-
const prStateCache = new Map();
|
|
314
|
-
const prStateFor = (branch) => {
|
|
315
|
-
let state = prStateCache.get(branch);
|
|
316
|
-
if (!state) {
|
|
317
|
-
state = resolvePrState(octokit, repo, branch, log);
|
|
318
|
-
prStateCache.set(branch, state);
|
|
319
|
-
}
|
|
320
|
-
return state;
|
|
321
|
-
};
|
|
322
|
-
// Per-issue GitHub verdicts, memoized across the sweep (one issues.get per distinct lane issue).
|
|
323
|
-
const dispositionCache = new Map();
|
|
324
|
-
const dispositionFor = (issue) => {
|
|
325
|
-
let disposition = dispositionCache.get(issue);
|
|
326
|
-
if (!disposition) {
|
|
327
|
-
disposition = resolveIssueDisposition(octokit, repo, issue, log, issueWarnDedup);
|
|
328
|
-
dispositionCache.set(issue, disposition);
|
|
329
|
-
}
|
|
330
|
-
return disposition;
|
|
331
|
-
};
|
|
332
|
-
// Per-issue existence/claim verdicts (#1352/#1353), memoized across the sweep and shared by
|
|
333
|
-
// both the real-mode quarantine tier below and the dry-run-only diagnostic block further down
|
|
334
|
-
// — only one of the two ever runs per call, so sharing the cache is safe.
|
|
335
|
-
const issueExistenceCache = new Map();
|
|
336
|
-
const issueExistenceFor = (issue) => {
|
|
337
|
-
let p = issueExistenceCache.get(issue);
|
|
338
|
-
if (!p) {
|
|
339
|
-
p = resolveIssueExistence(octokit, repo, issue, log);
|
|
340
|
-
issueExistenceCache.set(issue, p);
|
|
341
|
-
}
|
|
342
|
-
return p;
|
|
343
|
-
};
|
|
344
|
-
const claimCache = new Map();
|
|
345
|
-
const claimFor = (issue) => {
|
|
346
|
-
let p = claimCache.get(issue);
|
|
347
|
-
if (!p) {
|
|
348
|
-
p = resolveActiveClaim(octokit, repo, issue, log);
|
|
349
|
-
claimCache.set(issue, p);
|
|
350
|
-
}
|
|
351
|
-
return p;
|
|
352
|
-
};
|
|
353
|
-
for (const entry of candidates) {
|
|
354
|
-
const entryIssue = laneIssueNumber(entry, lanePattern);
|
|
355
|
-
if (entryIssue !== null && opts.protectedIssues?.has(entryIssue)) {
|
|
356
|
-
kept++;
|
|
357
|
-
continue;
|
|
358
|
-
}
|
|
359
|
-
const keep = entryIssue === null ? undefined : keeps.get(entryIssue);
|
|
360
|
-
// A keep record protects the worktree from every reason except a closed issue with a clean tree.
|
|
361
|
-
if (keep &&
|
|
362
|
-
!((await dispositionFor(keep.issue)) === 'reap-closed' && (await isWorktreeClean(runCommand, entry.path)))) {
|
|
363
|
-
kept++;
|
|
364
|
-
keptByRecord.push({ path: entry.path, branch: entry.branch, issue: keep.issue, reason: keep.reason });
|
|
365
|
-
continue;
|
|
366
|
-
}
|
|
367
|
-
const ageDays = computeAgeDays(entry.path, now, log);
|
|
368
|
-
let pushEvidence;
|
|
369
|
-
const priorPush = async () => {
|
|
370
|
-
if (!entry.branch)
|
|
371
|
-
return false;
|
|
372
|
-
if (pushEvidence === undefined) {
|
|
373
|
-
pushEvidence = await hasPriorPushEvidence(runCommand, repoRoot, entry.branch);
|
|
374
|
-
}
|
|
375
|
-
return pushEvidence;
|
|
376
|
-
};
|
|
377
|
-
let zeroCommit;
|
|
378
|
-
const zeroCommitLane = async () => {
|
|
379
|
-
zeroCommit ??= await isZeroCommitLane(runCommand, repoRoot, entry.head);
|
|
380
|
-
return zeroCommit;
|
|
381
|
-
};
|
|
382
|
-
let reason = null;
|
|
383
|
-
let branchReapable = false;
|
|
384
|
-
let heldThisEntry = false;
|
|
385
|
-
if (ageDays > ttlDays && !keep) {
|
|
386
|
-
reason = 'ttl-expired';
|
|
387
|
-
}
|
|
388
|
-
if (!reason) {
|
|
389
|
-
// Issue disposition outranks PR state (see ADR, this PR): a clean worktree whose owning
|
|
390
|
-
// issue is closed or labeled factory:parked is garbage even while its PR is still open —
|
|
391
|
-
// a finished or parked issue's open PR proves the work is pushed. No verdict, or a dirty
|
|
392
|
-
// tree, falls through to the existing PR-state/local-evidence chain unchanged.
|
|
393
|
-
const issueNumber = laneIssueNumber(entry, lanePattern);
|
|
394
|
-
const disposition = issueNumber === null ? null : await dispositionFor(issueNumber);
|
|
395
|
-
if ((disposition === 'reap-parked' || disposition === 'reap-closed') &&
|
|
396
|
-
(await isWorktreeClean(runCommand, entry.path))) {
|
|
397
|
-
reason = disposition === 'reap-parked' ? 'issue-parked' : 'issue-closed';
|
|
398
|
-
if (entry.branch) {
|
|
399
|
-
const prState = await prStateFor(entry.branch);
|
|
400
|
-
if (prState === 'open' || prState === 'merged' || prState === 'closed') {
|
|
401
|
-
// A PR ever existed under this head ⇒ the branch was pushed.
|
|
402
|
-
branchReapable = true;
|
|
403
|
-
}
|
|
404
|
-
else {
|
|
405
|
-
const lsRemote = await safeExec(runCommand, `git ls-remote --heads origin ${shellEscape(entry.branch)}`, {
|
|
406
|
-
cwd: repoRoot,
|
|
407
|
-
});
|
|
408
|
-
branchReapable =
|
|
409
|
-
(lsRemote !== null && lsRemote.stdout.trim() !== '') ||
|
|
410
|
-
(entry.head !== null &&
|
|
411
|
-
(await safeExec(runCommand, `git merge-base --is-ancestor ${shellEscape(entry.head)} origin/main`, {
|
|
412
|
-
cwd: repoRoot,
|
|
413
|
-
})) !== null);
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
else if (disposition === 'reap-decomposed' && issueNumber !== null) {
|
|
418
|
-
// Decomposed parent (#1756): reap only a clean, fully-pushed tree with no open PR. An open
|
|
419
|
-
// PR falls through to the chain below, which keeps it; anything else unsafe is held.
|
|
420
|
-
const hold = (why) => {
|
|
421
|
-
heldThisEntry = true;
|
|
422
|
-
held.push({ path: entry.path, branch: entry.branch, issue: issueNumber, why });
|
|
423
|
-
};
|
|
424
|
-
const openDecomposedPr = entry.branch !== null && (await prStateFor(entry.branch)) === 'open';
|
|
425
|
-
if (!openDecomposedPr) {
|
|
426
|
-
if (!(await isWorktreeClean(runCommand, entry.path))) {
|
|
427
|
-
hold('decomposed parent has uncommitted changes');
|
|
428
|
-
}
|
|
429
|
-
else if (entry.head === null) {
|
|
430
|
-
hold('decomposed parent HEAD could not be resolved');
|
|
431
|
-
}
|
|
432
|
-
else {
|
|
433
|
-
const unpushedCount = await countUnpushedCommits(runCommand, repoRoot, entry.head);
|
|
434
|
-
if (unpushedCount === null) {
|
|
435
|
-
hold('could not verify decomposed parent is pushed');
|
|
436
|
-
}
|
|
437
|
-
else if (unpushedCount > 0) {
|
|
438
|
-
hold(`decomposed parent has ${unpushedCount} unpushed commit(s)`);
|
|
439
|
-
}
|
|
440
|
-
else {
|
|
441
|
-
const beyondBase = await safeExec(runCommand, `git rev-list --count origin/main..${shellEscape(entry.head)}`, { cwd: repoRoot });
|
|
442
|
-
reason = 'issue-decomposed';
|
|
443
|
-
branchReapable = beyondBase !== null && beyondBase.stdout.trim() === '0';
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
if (!reason && entry.branch && !heldThisEntry) {
|
|
450
|
-
const prState = await prStateFor(entry.branch);
|
|
451
|
-
if (prState === 'open') {
|
|
452
|
-
// A live PR is authoritative: the branch is still being worked on — never remove.
|
|
453
|
-
reason = null;
|
|
454
|
-
}
|
|
455
|
-
else if (prState === 'merged') {
|
|
456
|
-
// GitHub decided the branch is merged — authoritative on its own, no ancestry/push requirement.
|
|
457
|
-
if ((await isWorktreeClean(runCommand, entry.path)) && !(await zeroCommitLane()))
|
|
458
|
-
reason = 'merged';
|
|
459
|
-
}
|
|
460
|
-
else if (prState === 'closed') {
|
|
461
|
-
if (await isWorktreeClean(runCommand, entry.path)) {
|
|
462
|
-
const delivered = entry.head !== null &&
|
|
463
|
-
mainTip !== null &&
|
|
464
|
-
(await safeExec(runCommand, `git merge-base --is-ancestor ${shellEscape(entry.head)} origin/main`, {
|
|
465
|
-
cwd: repoRoot,
|
|
466
|
-
})) !== null;
|
|
467
|
-
if (await zeroCommitLane()) {
|
|
468
|
-
// A zero-commit lane is trivially an ancestor of main — not delivered work (#2964).
|
|
469
|
-
}
|
|
470
|
-
else if (delivered) {
|
|
471
|
-
// Closed-not-merged PR whose content reached main — delivered, removable.
|
|
472
|
-
reason = 'merged';
|
|
473
|
-
}
|
|
474
|
-
else {
|
|
475
|
-
const lsRemote = await safeExec(runCommand, `git ls-remote --heads origin ${shellEscape(entry.branch)}`, {
|
|
476
|
-
cwd: repoRoot,
|
|
477
|
-
});
|
|
478
|
-
if (lsRemote !== null && lsRemote.stdout.trim() === '')
|
|
479
|
-
reason = 'remote-gone';
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
else {
|
|
484
|
-
// prState is 'none' or null (no PR / GitHub unreachable / no client) — no GitHub verdict.
|
|
485
|
-
// Fall back to the exact #639 local-evidence rules; every inconclusive probe keeps.
|
|
486
|
-
const clean = await isWorktreeClean(runCommand, entry.path);
|
|
487
|
-
if (clean && entry.head && mainTip !== null && entry.head !== mainTip) {
|
|
488
|
-
const ancestorResult = await safeExec(runCommand, `git merge-base --is-ancestor ${shellEscape(entry.head)} origin/main`, { cwd: repoRoot });
|
|
489
|
-
// An ancestor HEAD alone is not proof of a merge: every lane worktree starts life at
|
|
490
|
-
// origin/main (setupWorktree: `git worktree add -b <branch> <path> origin/main`), so a lane
|
|
491
|
-
// that has not committed yet is trivially an ancestor. Require evidence the branch was
|
|
492
|
-
// actually pushed before calling it merged.
|
|
493
|
-
if (ancestorResult !== null && (await priorPush()) && !(await zeroCommitLane())) {
|
|
494
|
-
reason = 'merged';
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
if (!reason && clean) {
|
|
498
|
-
const lsRemote = await safeExec(runCommand, `git ls-remote --heads origin ${shellEscape(entry.branch)}`, {
|
|
499
|
-
cwd: repoRoot,
|
|
500
|
-
});
|
|
501
|
-
// An empty ls-remote is ambiguous — "merged and deleted upstream" or "never pushed". Only the
|
|
502
|
-
// former is garbage, and only a prior push distinguishes them.
|
|
503
|
-
if (lsRemote !== null && lsRemote.stdout.trim() === '' && (await priorPush()) && !(await zeroCommitLane())) {
|
|
504
|
-
reason = 'remote-gone';
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
// Real-mode-only heuristic quarantine tier (#1355): issue-not-found / no-active-claim carry
|
|
510
|
-
// no merge/ancestry proof, unlike every reason above, so they never ran outside dry-run's
|
|
511
|
-
// report-only diagnostics (ADR-0088/0089) until now. Real mode acts on them here — but by
|
|
512
|
-
// quarantining (see QUARANTINE_REASONS), never by hard-deleting — while dry-run keeps
|
|
513
|
-
// reporting them for every candidate via the unconditional block below, regardless of reason.
|
|
514
|
-
// Gated on cleanliness like every other acting tier above (a dirty worktree is live work,
|
|
515
|
-
// never touched on a heuristic signal alone) and never overriding a live open PR — the same
|
|
516
|
-
// "never remove" rule the hard-evidence tier above already applies to it.
|
|
517
|
-
const openPr = entry.branch !== null && (await prStateFor(entry.branch)) === 'open';
|
|
518
|
-
const claimedDisposition = entryIssue === null ? null : await dispositionFor(entryIssue);
|
|
519
|
-
if (claimedDisposition === 'keep-claimed') {
|
|
520
|
-
// A live claim outranks every reap tier, TTL included (#2964).
|
|
521
|
-
reason = null;
|
|
522
|
-
}
|
|
523
|
-
if (!reason &&
|
|
524
|
-
!heldThisEntry &&
|
|
525
|
-
claimedDisposition !== 'keep-claimed' &&
|
|
526
|
-
!dryRun &&
|
|
527
|
-
!openPr &&
|
|
528
|
-
(await isWorktreeClean(runCommand, entry.path))) {
|
|
529
|
-
const issueNumber = laneIssueNumber(entry, lanePattern);
|
|
530
|
-
if (issueNumber !== null) {
|
|
531
|
-
const existence = await issueExistenceFor(issueNumber);
|
|
532
|
-
if (existence === 'not-found') {
|
|
533
|
-
reason = 'issue-not-found';
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
if (!reason && issueNumber !== null && entry.branch) {
|
|
537
|
-
const prState = await prStateFor(entry.branch);
|
|
538
|
-
if (prState === 'merged' || prState === 'closed') {
|
|
539
|
-
const claim = await claimFor(issueNumber);
|
|
540
|
-
if (claim === 'unclaimed') {
|
|
541
|
-
reason = 'no-active-claim';
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
if (!reason) {
|
|
547
|
-
kept++;
|
|
548
|
-
continue;
|
|
549
|
-
}
|
|
550
|
-
if (keep)
|
|
551
|
-
releasedKeeps.set(entry.path, keep.issue);
|
|
552
|
-
removed.push({
|
|
553
|
-
path: entry.path,
|
|
554
|
-
branch: entry.branch,
|
|
555
|
-
ageDays,
|
|
556
|
-
reason,
|
|
557
|
-
scrubbedFiles: [],
|
|
558
|
-
branchDeleted: false,
|
|
559
|
-
branchReapable,
|
|
560
|
-
action: QUARANTINE_REASONS.has(reason) ? 'quarantine' : 'remove',
|
|
561
|
-
});
|
|
562
|
-
}
|
|
563
|
-
if (dryRun) {
|
|
564
|
-
const issueNotFound = [];
|
|
565
|
-
const issueUnverifiable = [];
|
|
566
|
-
for (const entry of candidates) {
|
|
567
|
-
const issueNumber = laneIssueNumber(entry, lanePattern);
|
|
568
|
-
if (issueNumber === null)
|
|
569
|
-
continue;
|
|
570
|
-
const existence = await issueExistenceFor(issueNumber);
|
|
571
|
-
if (existence === 'not-found') {
|
|
572
|
-
issueNotFound.push({ path: entry.path, branch: entry.branch, issue: issueNumber });
|
|
573
|
-
}
|
|
574
|
-
else if (existence === 'error') {
|
|
575
|
-
issueUnverifiable.push({ path: entry.path, branch: entry.branch, issue: issueNumber });
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
const noActiveClaim = [];
|
|
579
|
-
for (const entry of candidates) {
|
|
580
|
-
if (!entry.branch)
|
|
581
|
-
continue;
|
|
582
|
-
const prState = await prStateFor(entry.branch);
|
|
583
|
-
if (prState !== 'merged' && prState !== 'closed')
|
|
584
|
-
continue;
|
|
585
|
-
const issueNumber = laneIssueNumber(entry, lanePattern);
|
|
586
|
-
if (issueNumber === null)
|
|
587
|
-
continue;
|
|
588
|
-
const claim = await claimFor(issueNumber);
|
|
589
|
-
if (claim === 'unclaimed') {
|
|
590
|
-
noActiveClaim.push({ path: entry.path, branch: entry.branch, issue: issueNumber, prState });
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
return { removed, kept, dryRun: true, issueNotFound, issueUnverifiable, noActiveClaim, held, keptByRecord };
|
|
594
|
-
}
|
|
595
|
-
for (const candidate of removed) {
|
|
596
|
-
const credentialFiles = findCredentialFiles(candidate.path);
|
|
597
|
-
for (const filePath of credentialFiles) {
|
|
598
|
-
try {
|
|
599
|
-
scrubFile(filePath);
|
|
600
|
-
candidate.scrubbedFiles.push(filePath);
|
|
601
|
-
}
|
|
602
|
-
catch (err) {
|
|
603
|
-
log('warn', `failed to scrub ${filePath}: ${err?.message ?? String(err)}`);
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
if (sandbox) {
|
|
607
|
-
await removeMicroVm({ ...sandbox, worktreePath: candidate.path, log });
|
|
608
|
-
}
|
|
609
|
-
if (candidate.action === 'quarantine') {
|
|
610
|
-
const quarantineDir = quarantineRoot(repoRoot);
|
|
611
|
-
const dest = quarantineDestination(quarantineDir, candidate.path);
|
|
612
|
-
try {
|
|
613
|
-
mkdirSync(quarantineDir, { recursive: true });
|
|
614
|
-
await runCommand(`git worktree move ${shellEscape(candidate.path)} ${shellEscape(dest)}`, { cwd: repoRoot });
|
|
615
|
-
candidate.quarantinedTo = dest;
|
|
616
|
-
log('worktree-gc', `quarantined ${candidate.path} to ${dest} — ${candidate.reason}`);
|
|
617
|
-
}
|
|
618
|
-
catch (err) {
|
|
619
|
-
log('warn', `git worktree move failed for ${candidate.path} (${err?.message ?? String(err)}) — falling back to a manual move`);
|
|
620
|
-
try {
|
|
621
|
-
renameSync(candidate.path, dest);
|
|
622
|
-
candidate.quarantinedTo = dest;
|
|
623
|
-
log('worktree-gc', `quarantined ${candidate.path} to ${dest} via manual move — ${candidate.reason}`);
|
|
624
|
-
}
|
|
625
|
-
catch (renameErr) {
|
|
626
|
-
log('warn', `manual move fallback failed for ${candidate.path}: ${renameErr?.message ?? String(renameErr)} — worktree left in place`);
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
continue;
|
|
630
|
-
}
|
|
631
|
-
try {
|
|
632
|
-
await runCommand(`git worktree remove --force ${shellEscape(candidate.path)}`, { cwd: repoRoot });
|
|
633
|
-
log('worktree-gc', `removed ${candidate.path} — ${candidate.reason}`);
|
|
634
|
-
}
|
|
635
|
-
catch (err) {
|
|
636
|
-
log('warn', `git worktree remove failed for ${candidate.path}: ${err?.message ?? String(err)}`);
|
|
637
|
-
try {
|
|
638
|
-
rmSync(candidate.path, { recursive: true, force: true });
|
|
639
|
-
log('worktree-gc', `removed ${candidate.path} via rmSync fallback — ${candidate.reason}`);
|
|
640
|
-
}
|
|
641
|
-
catch (rmErr) {
|
|
642
|
-
log('warn', `rmSync fallback failed for ${candidate.path}: ${rmErr?.message ?? String(rmErr)}`);
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
releaseWorktreeKeeps(keepsFile, releasedKeeps, log);
|
|
647
|
-
await runCommand('git worktree prune', { cwd: repoRoot }).catch((err) => log('warn', `git worktree prune failed in ${repoRoot}: ${err?.message ?? String(err)}`));
|
|
648
|
-
await deleteReapedBranches(removed, repoRoot, runCommand, log);
|
|
649
|
-
return {
|
|
650
|
-
removed,
|
|
651
|
-
kept,
|
|
652
|
-
dryRun: false,
|
|
653
|
-
issueNotFound: [],
|
|
654
|
-
issueUnverifiable: [],
|
|
655
|
-
noActiveClaim: [],
|
|
656
|
-
held,
|
|
657
|
-
keptByRecord,
|
|
658
|
-
};
|
|
659
|
-
}
|
|
660
|
-
async function deleteReapedBranches(candidates, repoRoot, runCommand, log) {
|
|
661
|
-
for (const candidate of candidates) {
|
|
662
|
-
if (candidate.branch === null)
|
|
663
|
-
continue;
|
|
664
|
-
if (!BRANCH_REAPABLE_REASONS.has(candidate.reason) && candidate.branchReapable !== true)
|
|
665
|
-
continue;
|
|
666
|
-
try {
|
|
667
|
-
await runCommand(`git branch -D ${shellEscape(candidate.branch)}`, { cwd: repoRoot });
|
|
668
|
-
candidate.branchDeleted = true;
|
|
669
|
-
}
|
|
670
|
-
catch (err) {
|
|
671
|
-
log('warn', `git branch -D failed for ${candidate.branch}: ${err?.message ?? String(err)}`);
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
function computeAgeDays(worktreePath, now, log) {
|
|
676
|
-
const gitPath = join(worktreePath, '.git');
|
|
677
|
-
try {
|
|
678
|
-
const mtimeMs = statSync(gitPath).mtimeMs;
|
|
679
|
-
return (now() - mtimeMs) / (24 * 60 * 60 * 1000);
|
|
680
|
-
}
|
|
681
|
-
catch (err) {
|
|
682
|
-
// An inconclusive probe must never mean "delete" — this directory may hold the only copy of
|
|
683
|
-
// uncommitted work.
|
|
684
|
-
log('warn', `worktree-gc: cannot stat ${gitPath} (${err?.message ?? String(err)}) — treating as age 0 (keeping)`);
|
|
685
|
-
return 0;
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
export function formatGcReport(report) {
|
|
689
|
-
const lines = [];
|
|
690
|
-
const verb = report.dryRun ? 'would remove' : 'removed';
|
|
691
|
-
for (const candidate of report.removed) {
|
|
692
|
-
const branchLabel = candidate.branch ?? 'detached';
|
|
693
|
-
const age = Number.isFinite(candidate.ageDays) ? Math.floor(candidate.ageDays) : '∞';
|
|
694
|
-
let line = `${candidate.path} (${branchLabel}, ${age}d old) — ${candidate.reason}`;
|
|
695
|
-
if (candidate.scrubbedFiles.length > 0) {
|
|
696
|
-
line += `, scrubbed ${candidate.scrubbedFiles.length} credential file(s)`;
|
|
697
|
-
}
|
|
698
|
-
if (candidate.branchDeleted && candidate.branch !== null) {
|
|
699
|
-
line += `, deleted branch ${candidate.branch}`;
|
|
700
|
-
}
|
|
701
|
-
if (candidate.action === 'quarantine') {
|
|
702
|
-
line += candidate.quarantinedTo ? `, quarantined to ${candidate.quarantinedTo}` : ', quarantined';
|
|
703
|
-
}
|
|
704
|
-
lines.push(line);
|
|
705
|
-
}
|
|
706
|
-
const removedCount = report.removed.filter((c) => c.action !== 'quarantine').length;
|
|
707
|
-
const quarantinedCount = report.removed.length - removedCount;
|
|
708
|
-
lines.push(quarantinedCount > 0
|
|
709
|
-
? `${verb} ${removedCount} worktree(s), quarantined ${quarantinedCount}, kept ${report.kept}`
|
|
710
|
-
: `${verb} ${removedCount} worktree(s), kept ${report.kept}`);
|
|
711
|
-
for (const c of report.keptByRecord ?? []) {
|
|
712
|
-
lines.push(`${c.path} (${c.branch ?? 'detached'}) — kept (${c.reason})`);
|
|
713
|
-
}
|
|
714
|
-
if (report.issueNotFound.length > 0) {
|
|
715
|
-
lines.push(`${report.issueNotFound.length} worktree(s) flagged — owning issue not found (404):`);
|
|
716
|
-
for (const c of report.issueNotFound) {
|
|
717
|
-
lines.push(` ${c.path} (${c.branch ?? 'detached'}) — issue #${c.issue} not found`);
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
if (report.issueUnverifiable.length > 0) {
|
|
721
|
-
lines.push(`${report.issueUnverifiable.length} worktree(s) unverifiable — GitHub issue lookup failed:`);
|
|
722
|
-
for (const c of report.issueUnverifiable) {
|
|
723
|
-
lines.push(` ${c.path} (${c.branch ?? 'detached'}) — issue #${c.issue} unverifiable`);
|
|
724
|
-
}
|
|
725
|
-
}
|
|
726
|
-
if (report.noActiveClaim.length > 0) {
|
|
727
|
-
lines.push(`${report.noActiveClaim.length} worktree(s) flagged — merged/closed PR with no active claim:`);
|
|
728
|
-
for (const c of report.noActiveClaim) {
|
|
729
|
-
lines.push(` ${c.path} (${c.branch ?? 'detached'}) — issue #${c.issue} ${c.prState}, no active claim`);
|
|
730
|
-
}
|
|
731
|
-
}
|
|
732
|
-
if (report.held.length > 0) {
|
|
733
|
-
lines.push(`${report.held.length} worktree(s) kept — decomposed parent with local work:`);
|
|
734
|
-
for (const c of report.held) {
|
|
735
|
-
lines.push(` ${c.path} (${c.branch ?? 'detached'}) — issue #${c.issue}: ${c.why}`);
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
return lines.join('\n');
|
|
739
|
-
}
|
|
1
|
+
// Moved to ../worktree/worktree-gc.ts; kept so existing importers resolve.
|
|
2
|
+
export * from '../worktree/worktree-gc.js';
|
|
740
3
|
//# sourceMappingURL=worktree-gc.js.map
|