fix: make worktree cleanup fail closed (#3385)
* fix: make worktree cleanup fail closed * chore: add changeset for worktree cleanup safety * fix: address worktree cleanup review findings * docs: label remove-workspace failure block * fix: initialize worktree manifest before dispatch
This commit is contained in:
@@ -373,7 +373,7 @@ async function main() {
|
||||
'generate-dev-preferences, generate-slug, graphify, history-digest, init, intel, ' +
|
||||
'learnings, list-todos, milestone, phase, phase-plan-index, phases, profile-questionnaire, ' +
|
||||
'profile-sample, progress, requirements, resolve-model, roadmap, scaffold, state, ' +
|
||||
'template, validate, verify, verify-path-exists, verify-summary, workstream\n\n' +
|
||||
'template, validate, verify, verify-path-exists, verify-summary, workstream, worktree\n\n' +
|
||||
'Global flags:\n' +
|
||||
' --raw Emit raw output without post-processing\n' +
|
||||
' --pick <field> Extract a single field from JSON output (dot/bracket notation)\n' +
|
||||
@@ -418,6 +418,7 @@ async function main() {
|
||||
const SKIP_ROOT_RESOLUTION = new Set([
|
||||
'generate-slug', 'current-timestamp', 'verify-path-exists',
|
||||
'verify-summary', 'template', 'frontmatter', 'detect-custom-files',
|
||||
'worktree',
|
||||
]);
|
||||
if (!SKIP_ROOT_RESOLUTION.has(command)) {
|
||||
cwd = findProjectRoot(cwd);
|
||||
@@ -981,6 +982,17 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
|
||||
break;
|
||||
}
|
||||
|
||||
case 'worktree': {
|
||||
const subcommand = args[1];
|
||||
const worktreeSafety = require('./lib/worktree-safety.cjs');
|
||||
if (subcommand === 'cleanup-wave') {
|
||||
worktreeSafety.cmdWorktreeCleanupWave(cwd, args.slice(2));
|
||||
} else {
|
||||
error('Unknown worktree subcommand. Available: cleanup-wave', ERROR_REASON.SDK_UNKNOWN_COMMAND);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// ─── Intel ────────────────────────────────────────────────────────────
|
||||
|
||||
case 'intel': {
|
||||
|
||||
@@ -921,8 +921,13 @@ function cmdValidateHealth(cwd, options, raw) {
|
||||
'Worktree health check degraded: git worktree list timed out after 10s — orphan/stale worktrees could not be inspected',
|
||||
'Run: git worktree list --porcelain to diagnose; check for .git/index.lock or a hung git process');
|
||||
}
|
||||
// Other non-ok reasons (not_a_git_repo, git_list_failed) are silent — not
|
||||
// meaningful for users who have no git repo or whose git is not configured.
|
||||
if (worktreeHealth.reason === 'git_list_failed') {
|
||||
addIssue('warning', 'W020',
|
||||
'Worktree health check degraded: git worktree list failed — orphan/stale worktrees could not be inspected',
|
||||
'Run: git worktree list --porcelain to diagnose; check git repository state and permissions');
|
||||
}
|
||||
// Other non-ok reasons (not_a_git_repo) are silent — not meaningful for
|
||||
// users who have no git repo.
|
||||
} else {
|
||||
for (const finding of worktreeHealth.findings) {
|
||||
if (finding.kind === 'orphan') {
|
||||
|
||||
@@ -35,6 +35,11 @@ function execGitDefault(cwd, args, options = {}) {
|
||||
stdio: 'pipe',
|
||||
encoding: 'utf-8',
|
||||
timeout,
|
||||
env: {
|
||||
...process.env,
|
||||
GIT_TERMINAL_PROMPT: '0',
|
||||
GCM_INTERACTIVE: 'never',
|
||||
},
|
||||
});
|
||||
// spawnSync sets signal='SIGTERM' and error.code='ETIMEDOUT' when the timeout
|
||||
// fires and the subprocess is killed.
|
||||
@@ -90,9 +95,12 @@ function readWorktreeList(repoRoot, deps = {}) {
|
||||
};
|
||||
}
|
||||
if (listResult.exitCode !== 0) {
|
||||
const stderr = String(listResult.stderr || '');
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'git_list_failed',
|
||||
reason: /not a git repository|not a git repo/i.test(stderr)
|
||||
? 'not_a_git_repo'
|
||||
: 'git_list_failed',
|
||||
porcelain: '',
|
||||
entries: [],
|
||||
};
|
||||
@@ -327,6 +335,244 @@ function snapshotWorktreeInventory(repoRoot, options = {}, deps = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCleanupManifestEntry(entry) {
|
||||
if (!entry || typeof entry !== 'object') return null;
|
||||
const worktreePath = typeof entry.worktree_path === 'string'
|
||||
? entry.worktree_path
|
||||
: (typeof entry.path === 'string' ? entry.path : '');
|
||||
const branch = typeof entry.branch === 'string' ? entry.branch : '';
|
||||
const expectedBase = typeof entry.expected_base === 'string' ? entry.expected_base : '';
|
||||
if (!worktreePath || !branch || !expectedBase) return null;
|
||||
if (!/^worktree-agent-[A-Za-z0-9._/-]+$/.test(branch)) return null;
|
||||
return {
|
||||
agent_id: typeof entry.agent_id === 'string' ? entry.agent_id : null,
|
||||
worktree_path: worktreePath,
|
||||
branch,
|
||||
expected_base: expectedBase,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCleanupManifest(manifest) {
|
||||
let parsed = manifest;
|
||||
if (typeof manifest === 'string') {
|
||||
try {
|
||||
parsed = JSON.parse(manifest);
|
||||
} catch {
|
||||
return { ok: false, reason: 'invalid_manifest_json', entries: [] };
|
||||
}
|
||||
}
|
||||
|
||||
const rawEntries = Array.isArray(parsed)
|
||||
? parsed
|
||||
: (Array.isArray(parsed?.worktrees) ? parsed.worktrees : []);
|
||||
const seen = new Set();
|
||||
const entries = [];
|
||||
for (const raw of rawEntries) {
|
||||
const entry = normalizeCleanupManifestEntry(raw);
|
||||
if (!entry) continue;
|
||||
const key = `${entry.worktree_path}\0${entry.branch}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
entries.push(entry);
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
return { ok: false, reason: 'empty_manifest', entries: [] };
|
||||
}
|
||||
|
||||
return { ok: true, reason: 'ok', entries };
|
||||
}
|
||||
|
||||
function planWorktreeWaveCleanup(repoRoot, manifest) {
|
||||
const normalized = normalizeCleanupManifest(manifest);
|
||||
if (!normalized.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
repoRoot,
|
||||
action: 'skip',
|
||||
discovery: 'manifest',
|
||||
reason: normalized.reason,
|
||||
entries: [],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
repoRoot,
|
||||
action: 'cleanup_wave',
|
||||
discovery: 'manifest',
|
||||
reason: 'manifest_entries_present',
|
||||
entries: normalized.entries,
|
||||
};
|
||||
}
|
||||
|
||||
function gitResultOk(result) {
|
||||
return result && result.exitCode === 0 && !result.timedOut;
|
||||
}
|
||||
|
||||
function executeWorktreeWaveCleanupPlan(plan, deps = {}) {
|
||||
const execGit = deps.execGit || execGitDefault;
|
||||
const entries = Array.isArray(plan?.entries) ? plan.entries : [];
|
||||
if (!plan || plan.action !== 'cleanup_wave' || entries.length === 0) {
|
||||
return {
|
||||
ok: false,
|
||||
action: plan ? plan.action : 'skip',
|
||||
reason: plan ? (plan.reason || 'missing_entries') : 'missing_plan',
|
||||
entries: [],
|
||||
pending: entries,
|
||||
};
|
||||
}
|
||||
|
||||
const results = [];
|
||||
const pending = [];
|
||||
let ok = true;
|
||||
|
||||
for (let i = 0; i < entries.length; i += 1) {
|
||||
const entry = entries[i];
|
||||
const result = {
|
||||
...entry,
|
||||
status: 'pending',
|
||||
reason: null,
|
||||
stderr: '',
|
||||
};
|
||||
|
||||
const branchCheck = execGit(plan.repoRoot, ['-C', entry.worktree_path, 'rev-parse', '--abbrev-ref', 'HEAD']);
|
||||
if (!gitResultOk(branchCheck) || branchCheck.stdout !== entry.branch) {
|
||||
result.status = 'blocked';
|
||||
result.reason = 'branch_mismatch';
|
||||
result.stderr = branchCheck?.stderr || '';
|
||||
results.push(result);
|
||||
pending.push(...entries.slice(i + 1));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const mergeBase = execGit(plan.repoRoot, ['merge-base', 'HEAD', entry.branch]);
|
||||
if (!gitResultOk(mergeBase) || mergeBase.stdout !== entry.expected_base) {
|
||||
result.status = 'blocked';
|
||||
result.reason = 'base_mismatch';
|
||||
result.stderr = mergeBase?.stderr || '';
|
||||
results.push(result);
|
||||
pending.push(...entries.slice(i + 1));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const deletions = execGit(plan.repoRoot, ['diff', '--diff-filter=D', '--name-only', `HEAD...${entry.branch}`]);
|
||||
if (!gitResultOk(deletions)) {
|
||||
result.status = 'blocked';
|
||||
result.reason = 'deletion_check_failed';
|
||||
result.stderr = deletions?.stderr || '';
|
||||
results.push(result);
|
||||
pending.push(...entries.slice(i + 1));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
if (deletions.stdout) {
|
||||
result.status = 'blocked';
|
||||
result.reason = 'branch_contains_deletions';
|
||||
result.stderr = deletions.stdout;
|
||||
results.push(result);
|
||||
pending.push(...entries.slice(i + 1));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const worktreeStatus = execGit(plan.repoRoot, ['-C', entry.worktree_path, 'status', '--porcelain', '--untracked-files=all']);
|
||||
if (!gitResultOk(worktreeStatus) || worktreeStatus.stdout) {
|
||||
result.status = 'blocked';
|
||||
result.reason = 'worktree_dirty';
|
||||
result.stderr = worktreeStatus?.stdout || worktreeStatus?.stderr || '';
|
||||
results.push(result);
|
||||
pending.push(...entries.slice(i + 1));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const merge = execGit(plan.repoRoot, ['merge', entry.branch, '--no-ff', '--no-edit', '-m', `chore: merge executor worktree (${entry.branch})`]);
|
||||
if (!gitResultOk(merge)) {
|
||||
result.status = 'blocked';
|
||||
result.reason = 'merge_failed';
|
||||
result.stderr = merge?.stderr || merge?.stdout || '';
|
||||
results.push(result);
|
||||
pending.push(...entries.slice(i + 1));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const remove = execGit(plan.repoRoot, ['worktree', 'remove', entry.worktree_path, '--force']);
|
||||
if (!gitResultOk(remove)) {
|
||||
result.status = 'blocked';
|
||||
result.reason = 'worktree_remove_failed';
|
||||
result.stderr = remove?.stderr || '';
|
||||
results.push(result);
|
||||
pending.push(...entries.slice(i + 1));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
|
||||
const branchDelete = execGit(plan.repoRoot, ['branch', '-D', entry.branch]);
|
||||
if (!gitResultOk(branchDelete)) {
|
||||
result.status = 'warning';
|
||||
result.reason = 'branch_delete_failed';
|
||||
result.stderr = branchDelete?.stderr || '';
|
||||
ok = false;
|
||||
} else {
|
||||
result.status = 'merged_removed';
|
||||
result.reason = 'ok';
|
||||
}
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
return {
|
||||
ok,
|
||||
action: plan.action,
|
||||
reason: ok ? 'ok' : 'cleanup_blocked',
|
||||
entries: results,
|
||||
pending,
|
||||
};
|
||||
}
|
||||
|
||||
function cmdWorktreeCleanupWave(cwd, args = []) {
|
||||
const manifestFlagIndex = args.indexOf('--manifest');
|
||||
const manifestPath = manifestFlagIndex >= 0 ? args[manifestFlagIndex + 1] : '';
|
||||
if (!manifestPath) {
|
||||
process.stderr.write('Usage: worktree cleanup-wave --manifest <path>\n');
|
||||
process.exitCode = 2;
|
||||
return;
|
||||
}
|
||||
|
||||
let manifest;
|
||||
try {
|
||||
manifest = fs.readFileSync(path.resolve(cwd, manifestPath), 'utf8');
|
||||
} catch (err) {
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
ok: false,
|
||||
reason: 'manifest_read_failed',
|
||||
error: err.message,
|
||||
}, null, 2)}\n`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const plan = planWorktreeWaveCleanup(cwd, manifest);
|
||||
const result = executeWorktreeWaveCleanupPlan(plan);
|
||||
const response = {
|
||||
ok: result.ok,
|
||||
plan: {
|
||||
action: plan.action,
|
||||
discovery: plan.discovery,
|
||||
reason: plan.reason,
|
||||
entries: plan.entries.length,
|
||||
},
|
||||
result,
|
||||
};
|
||||
process.stdout.write(`${JSON.stringify(response, null, 2)}\n`);
|
||||
if (!result.ok) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
resolveWorktreeContext,
|
||||
parseWorktreePorcelain,
|
||||
@@ -335,4 +581,8 @@ module.exports = {
|
||||
listLinkedWorktreePaths,
|
||||
inspectWorktreeHealth,
|
||||
snapshotWorktreeInventory,
|
||||
normalizeCleanupManifest,
|
||||
planWorktreeWaveCleanup,
|
||||
executeWorktreeWaveCleanupPlan,
|
||||
cmdWorktreeCleanupWave,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user