@ornexus/neocortex 4.60.81 → 4.61.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/dist/release-source.json +1 -1
- package/install.ps1 +33 -1
- package/install.sh +35 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/platform-detector.d.ts +1 -1
- package/packages/client/dist/adapters/platform-detector.js +6 -0
- package/packages/client/dist/cli.js +7 -0
- package/packages/client/dist/commands/invoke.d.ts +15 -8
- package/packages/client/dist/commands/invoke.js +69 -0
- package/packages/client/dist/commands/story-checkpoint.d.ts +2 -1
- package/packages/client/dist/commands/story-checkpoint.js +34 -2
- package/packages/client/dist/commands/story-worktree.d.ts +46 -0
- package/packages/client/dist/commands/story-worktree.js +258 -0
- package/packages/client/dist/config.js +1 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +46 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.js +137 -1
- package/packages/client/dist/git/git-lifecycle-store.d.ts +82 -0
- package/packages/client/dist/git/git-lifecycle-store.js +310 -4
- package/packages/client/dist/git/story-worktree-cleanup.d.ts +226 -0
- package/packages/client/dist/git/story-worktree-cleanup.js +1058 -0
- package/packages/client/dist/git/story-worktree-integration.d.ts +91 -0
- package/packages/client/dist/git/story-worktree-integration.js +603 -0
- package/packages/client/dist/git/story-worktree-manager.d.ts +205 -0
- package/packages/client/dist/git/story-worktree-manager.js +843 -0
- package/packages/client/dist/git/story-worktree-paths.d.ts +65 -0
- package/packages/client/dist/git/story-worktree-paths.js +150 -0
- package/packages/client/dist/policy/subagent-approval-policy.js +3 -1
- package/packages/client/dist/runner/headless/continuous-story-workspace.d.ts +49 -1
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +175 -27
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +39 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +71 -0
- package/packages/client/dist/runner-cli.js +0 -0
- package/packages/shared/dist/yoloop/epic-terminal-git.js +27 -3
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +21 -0
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/README.md +17 -0
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +57 -49
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +28 -25
- package/targets-stubs/codex/AGENTS.md +31 -30
- package/targets-stubs/codex/neocortex.toml +10 -0
- package/targets-stubs/cursor/agent.md +13 -2
- package/targets-stubs/deepseek-harness/SKILL.md +13 -0
- package/targets-stubs/gemini-cli/agent.md +23 -2
- package/targets-stubs/grok/SKILL.md +21 -0
- package/targets-stubs/kimi/neocortex.md +21 -0
- package/targets-stubs/openclaw/SKILL.md +21 -0
- package/targets-stubs/opencode/neocortex-root.md +19 -15
- package/targets-stubs/opencode/neocortex.md +10 -0
- package/targets-stubs/vscode/neocortex.agent.md +13 -2
|
@@ -0,0 +1,1058 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license FSL-1.1
|
|
3
|
+
* Copyright (c) 2026 OrNexus AI
|
|
4
|
+
*
|
|
5
|
+
* This file is part of Neocortex CLI, licensed under the
|
|
6
|
+
* Functional Source License, Version 1.1 (FSL-1.1).
|
|
7
|
+
*
|
|
8
|
+
* Change Date: February 20, 2029
|
|
9
|
+
* Change License: MIT
|
|
10
|
+
*
|
|
11
|
+
* See the LICENSE file in the project root for full license text.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* P225.06 -- cleanup guarantees and orphan recovery for story worktrees
|
|
15
|
+
* (P225-REQ-06, P225-CON-WORKTREE, P225-CON-RECEIPTS).
|
|
16
|
+
*
|
|
17
|
+
* State machine (private sidecar next to the lifecycle runtime):
|
|
18
|
+
* active -> integrated -> removed
|
|
19
|
+
* active -> failed | abandoned -> bundled -> removed
|
|
20
|
+
* any removal step that exhausts its bounded retry -> remove-pending
|
|
21
|
+
*
|
|
22
|
+
* Invariants: a resource is touched only with journal + marker + `git worktree
|
|
23
|
+
* list` proof (P225.05 ownership) under a per-lease cleanup claim; unintegrated
|
|
24
|
+
* commits are bundled and the bundle verified before any removal; a verified
|
|
25
|
+
* bundle is never overwritten; no command uses `--force`; a remote temporary
|
|
26
|
+
* branch is deleted only when its push was recorded, its recorded SHA survives
|
|
27
|
+
* locally (integrated or bundled) and the remote still points at that SHA
|
|
28
|
+
* (lease-guarded deletion). Worktrees without a journal entry are manual and
|
|
29
|
+
* are only counted. Public values carry opaque IDs, SHAs, digests, counts and
|
|
30
|
+
* reason codes -- never paths or URLs.
|
|
31
|
+
*/
|
|
32
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
33
|
+
import { existsSync } from 'node:fs';
|
|
34
|
+
import { chmod, lstat, open, readFile, readdir, rename, rm, stat, unlink } from 'node:fs/promises';
|
|
35
|
+
import { hostname } from 'node:os';
|
|
36
|
+
import { join } from 'node:path';
|
|
37
|
+
import { GIT_LIFECYCLE_RUNTIME_DIRECTORY, STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS, assertGitLifecyclePrivateFile, compactStoryWorktreeJournal, ensureGitLifecyclePrivateChildDirectory, ensureStoryWorktreeJournal, gitLifecycleRuntimeDirectory, isStoryWorktreeCleanupReceiptRecord, mutateGitLifecycleRuntime, readGitLifecycleRuntime, } from './git-lifecycle-store.js';
|
|
38
|
+
import { StoryWorktreeManager, digestStoryWorktreeReceiptLocal, runStoryWorktreeGit, } from './story-worktree-manager.js';
|
|
39
|
+
export const STORY_WORKTREE_CLEANUP_FILE = 'story-worktree-cleanup.json';
|
|
40
|
+
export const STORY_WORKTREE_BUNDLE_DIRECTORY = 'story-worktree-bundles';
|
|
41
|
+
export const STORY_WORKTREE_CLEANUP_MAX_RECORDS = 256;
|
|
42
|
+
export const STORY_WORKTREE_CLEANUP_TRIGGERS = Object.freeze(['success', 'failure', 'abandon', 'orphan-recovery']);
|
|
43
|
+
export const STORY_WORKTREE_CLEANUP_STATES = Object.freeze([
|
|
44
|
+
'active', 'integrated', 'failed', 'abandoned', 'bundled', 'remove-pending', 'removed',
|
|
45
|
+
]);
|
|
46
|
+
export const STORY_WORKTREE_CLEANUP_REASON_CODES = Object.freeze({
|
|
47
|
+
MANUAL_PRESERVED: 'manual-worktree-preserved',
|
|
48
|
+
REMOVE_PENDING: 'story-worktree-remove-pending',
|
|
49
|
+
ORPHAN_RECOVERED: 'story-worktree-orphan-recovered',
|
|
50
|
+
ORPHAN_UNPROVEN: 'story-worktree-orphan-unproven',
|
|
51
|
+
OWNER_ALIVE: 'story-worktree-owner-alive',
|
|
52
|
+
LEASE_LIVE: 'story-worktree-lease-live',
|
|
53
|
+
CLAIMED: 'story-worktree-cleanup-claimed',
|
|
54
|
+
IN_PROGRESS: 'story-worktree-cleanup-in-progress',
|
|
55
|
+
DIRTY_PRESERVED: 'story-worktree-dirty-preserved',
|
|
56
|
+
BUNDLE_QUOTA: 'story-worktree-bundle-quota-exceeded',
|
|
57
|
+
BUNDLE_FAILED: 'story-worktree-bundle-failed',
|
|
58
|
+
BUNDLE_UNVERIFIED: 'story-worktree-bundle-unverified',
|
|
59
|
+
REMOTE_DIVERGED: 'story-worktree-remote-sha-diverged',
|
|
60
|
+
REMOTE_UNVERIFIED: 'story-worktree-remote-unverified',
|
|
61
|
+
REMOTE_ABSENT: 'story-worktree-remote-absent',
|
|
62
|
+
REMOTE_UNPRESERVED: 'story-worktree-remote-unpreserved',
|
|
63
|
+
REMOTE_UNKNOWN: 'story-worktree-remote-unknown',
|
|
64
|
+
BRANCH_MOVED: 'story-worktree-branch-moved',
|
|
65
|
+
BRANCH_CHECKED_OUT: 'story-worktree-branch-checked-out',
|
|
66
|
+
ADOPTED_BRANCH: 'story-worktree-adopted-branch-preserved',
|
|
67
|
+
ENTRY_CONFLICT: 'story-worktree-entry-conflict',
|
|
68
|
+
STATE_INVALID: 'story-worktree-cleanup-state-invalid',
|
|
69
|
+
SWEEP_FAILED: 'story-worktree-sweep-failed',
|
|
70
|
+
});
|
|
71
|
+
const R = STORY_WORKTREE_CLEANUP_REASON_CODES;
|
|
72
|
+
const DEFAULT_BUNDLE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
73
|
+
const DEFAULT_CLAIM_TTL_MS = 10 * 60 * 1000;
|
|
74
|
+
const DEFAULT_MAX_BUNDLES = 64;
|
|
75
|
+
const DEFAULT_MAX_BUNDLE_BYTES = 512 * 1024 * 1024;
|
|
76
|
+
const DEFAULT_REMOVE_ATTEMPTS = 3;
|
|
77
|
+
const DEFAULT_REMOVE_DELAY_MS = 50;
|
|
78
|
+
const LEASE_ID = /^swt-[a-f0-9]{24}$/;
|
|
79
|
+
const FULL_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
80
|
+
const SHA256 = /^[a-f0-9]{64}$/;
|
|
81
|
+
const CLAIM_TOKEN = /^[a-f0-9]{16}$/;
|
|
82
|
+
const EPIC_ID = /^P[1-9][0-9]*$/;
|
|
83
|
+
const STORY_ID = /^P[1-9][0-9]*(?:\.[0-9]+)+$/;
|
|
84
|
+
const REMOTE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
85
|
+
/** Only client-managed temporary branches are ever recorded for remote deletion. */
|
|
86
|
+
const MANAGED_BRANCH = /^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/;
|
|
87
|
+
const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;
|
|
88
|
+
const BUNDLE_FILE = /^swt-[a-f0-9]{24}-[a-f0-9]{12}\.bundle$/;
|
|
89
|
+
const IN_PROGRESS_STATES = ['integrated', 'failed', 'abandoned', 'bundled', 'remove-pending'];
|
|
90
|
+
class CleanupRefusal extends Error {
|
|
91
|
+
reasonCode;
|
|
92
|
+
constructor(reasonCode) {
|
|
93
|
+
super(reasonCode);
|
|
94
|
+
this.reasonCode = reasonCode;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function refuse(reasonCode) {
|
|
98
|
+
throw new CleanupRefusal(reasonCode);
|
|
99
|
+
}
|
|
100
|
+
function sha256(value) {
|
|
101
|
+
return createHash('sha256').update(value).digest('hex');
|
|
102
|
+
}
|
|
103
|
+
function sleep(ms) {
|
|
104
|
+
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
105
|
+
}
|
|
106
|
+
function unique(values) {
|
|
107
|
+
return [...new Set(values)];
|
|
108
|
+
}
|
|
109
|
+
function defaultIsProcessAlive(pid) {
|
|
110
|
+
try {
|
|
111
|
+
process.kill(pid, 0);
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
return error.code === 'EPERM';
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Private bundle file name: one immutable file per (lease, verified tip). */
|
|
119
|
+
export function storyWorktreeBundleFileName(leaseId, headSha) {
|
|
120
|
+
return `${leaseId}-${headSha.slice(0, 12)}.bundle`;
|
|
121
|
+
}
|
|
122
|
+
export function storyWorktreeOwnerHostDigest(host = hostname()) {
|
|
123
|
+
return sha256(`neocortex.p225.owner-host|${host}`);
|
|
124
|
+
}
|
|
125
|
+
function asRecord(value) {
|
|
126
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
|
|
127
|
+
}
|
|
128
|
+
const RECORD_REQUIRED = ['schemaVersion', 'leaseId', 'epicId', 'storyId', 'state', 'removeAttempts', 'updatedAt'];
|
|
129
|
+
const RECORD_ALLOWED = new Set([
|
|
130
|
+
...RECORD_REQUIRED, 'trigger', 'headSha', 'bundleDigest', 'bundleBytes', 'bundleExpiresAt',
|
|
131
|
+
'remotePush', 'remoteBranchRemoved', 'ownerPid', 'ownerHostDigest', 'claimToken', 'claimExpiresAt',
|
|
132
|
+
]);
|
|
133
|
+
/** Closed-schema validation of one sidecar record. */
|
|
134
|
+
export function isStoryWorktreeCleanupRecord(leaseId, value) {
|
|
135
|
+
const record = asRecord(value);
|
|
136
|
+
if (!record)
|
|
137
|
+
return false;
|
|
138
|
+
if (Object.keys(record).some((key) => !RECORD_ALLOWED.has(key)) || RECORD_REQUIRED.some((key) => record[key] === undefined))
|
|
139
|
+
return false;
|
|
140
|
+
const push = record.remotePush === undefined ? undefined : asRecord(record.remotePush);
|
|
141
|
+
if (record.remotePush !== undefined && (!push || Object.keys(push).length !== 3
|
|
142
|
+
|| typeof push.remote !== 'string' || !REMOTE_NAME.test(push.remote)
|
|
143
|
+
|| typeof push.branch !== 'string' || !MANAGED_BRANCH.test(push.branch)
|
|
144
|
+
|| !push.branch.startsWith(`nx/${String(record.epicId)}/`)
|
|
145
|
+
|| typeof push.sha !== 'string' || !FULL_SHA.test(push.sha)))
|
|
146
|
+
return false;
|
|
147
|
+
const time = (key) => record[key] === undefined
|
|
148
|
+
|| (typeof record[key] === 'string' && ISO_UTC.test(record[key]) && Number.isFinite(Date.parse(record[key])));
|
|
149
|
+
return record.schemaVersion === 1
|
|
150
|
+
&& record.leaseId === leaseId && LEASE_ID.test(leaseId)
|
|
151
|
+
&& typeof record.epicId === 'string' && EPIC_ID.test(record.epicId)
|
|
152
|
+
&& typeof record.storyId === 'string' && STORY_ID.test(record.storyId) && record.storyId.startsWith(`${record.epicId}.`)
|
|
153
|
+
&& STORY_WORKTREE_CLEANUP_STATES.includes(record.state)
|
|
154
|
+
&& Number.isSafeInteger(record.removeAttempts) && record.removeAttempts >= 0 && record.removeAttempts <= 1000
|
|
155
|
+
&& time('updatedAt') && time('bundleExpiresAt') && time('claimExpiresAt')
|
|
156
|
+
&& (record.claimToken === undefined) === (record.claimExpiresAt === undefined)
|
|
157
|
+
&& (record.claimToken === undefined || (typeof record.claimToken === 'string' && CLAIM_TOKEN.test(record.claimToken)))
|
|
158
|
+
&& (record.trigger === undefined || STORY_WORKTREE_CLEANUP_TRIGGERS.includes(record.trigger))
|
|
159
|
+
&& (record.headSha === undefined || (typeof record.headSha === 'string' && FULL_SHA.test(record.headSha)))
|
|
160
|
+
&& (record.bundleDigest === undefined || (typeof record.bundleDigest === 'string' && SHA256.test(record.bundleDigest)
|
|
161
|
+
&& record.headSha !== undefined && record.bundleExpiresAt !== undefined))
|
|
162
|
+
&& (record.bundleBytes === undefined || (Number.isSafeInteger(record.bundleBytes) && record.bundleBytes > 0))
|
|
163
|
+
&& (record.remoteBranchRemoved === undefined || typeof record.remoteBranchRemoved === 'boolean')
|
|
164
|
+
&& (record.ownerPid === undefined || (Number.isSafeInteger(record.ownerPid) && record.ownerPid > 0))
|
|
165
|
+
&& (record.ownerHostDigest === undefined || (typeof record.ownerHostDigest === 'string' && SHA256.test(record.ownerHostDigest)));
|
|
166
|
+
}
|
|
167
|
+
export function parseStoryWorktreeCleanupDocument(raw) {
|
|
168
|
+
let parsed;
|
|
169
|
+
try {
|
|
170
|
+
parsed = JSON.parse(raw);
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
refuse(R.STATE_INVALID);
|
|
174
|
+
}
|
|
175
|
+
const document = asRecord(parsed);
|
|
176
|
+
const records = asRecord(document?.records);
|
|
177
|
+
if (!document || Object.keys(document).length !== 2 || document.schemaVersion !== 1 || !records
|
|
178
|
+
|| Object.keys(records).length > STORY_WORKTREE_CLEANUP_MAX_RECORDS
|
|
179
|
+
|| !Object.entries(records).every(([leaseId, record]) => isStoryWorktreeCleanupRecord(leaseId, record))) {
|
|
180
|
+
refuse(R.STATE_INVALID);
|
|
181
|
+
}
|
|
182
|
+
return { schemaVersion: 1, records: records };
|
|
183
|
+
}
|
|
184
|
+
async function readCleanupDocumentAt(commonDir) {
|
|
185
|
+
const runtimeDirectory = join(commonDir, GIT_LIFECYCLE_RUNTIME_DIRECTORY);
|
|
186
|
+
const path = join(runtimeDirectory, STORY_WORKTREE_CLEANUP_FILE);
|
|
187
|
+
if (!existsSync(path))
|
|
188
|
+
return { schemaVersion: 1, records: {} };
|
|
189
|
+
try {
|
|
190
|
+
await assertGitLifecyclePrivateFile(path, runtimeDirectory);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
refuse(R.STATE_INVALID);
|
|
194
|
+
}
|
|
195
|
+
return parseStoryWorktreeCleanupDocument(await readFile(path, 'utf8'));
|
|
196
|
+
}
|
|
197
|
+
function liveClaim(record, nowMs) {
|
|
198
|
+
return record?.claimToken !== undefined && record.claimExpiresAt !== undefined && Date.parse(record.claimExpiresAt) > nowMs;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* True when a cleanup for this lease is in progress (or the sidecar cannot be
|
|
202
|
+
* trusted): P225.05 `create`/`adopt` must not hand the worktree to a new child.
|
|
203
|
+
*/
|
|
204
|
+
export async function storyWorktreeCleanupInProgress(commonDir, leaseId, nowMs = Date.now()) {
|
|
205
|
+
try {
|
|
206
|
+
const record = (await readCleanupDocumentAt(commonDir)).records[leaseId];
|
|
207
|
+
return record !== undefined && (IN_PROGRESS_STATES.includes(record.state) || liveClaim(record, nowMs));
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
export class StoryWorktreeCleanup {
|
|
214
|
+
options;
|
|
215
|
+
manager;
|
|
216
|
+
now;
|
|
217
|
+
isProcessAlive;
|
|
218
|
+
constructor(options) {
|
|
219
|
+
this.options = options;
|
|
220
|
+
this.manager = options.manager ?? new StoryWorktreeManager({
|
|
221
|
+
projectRoot: options.projectRoot,
|
|
222
|
+
...(options.worktreeRoot ? { worktreeRoot: options.worktreeRoot } : {}),
|
|
223
|
+
...(options.now ? { now: options.now } : {}),
|
|
224
|
+
});
|
|
225
|
+
this.now = options.now ?? (() => new Date());
|
|
226
|
+
this.isProcessAlive = options.isProcessAlive ?? defaultIsProcessAlive;
|
|
227
|
+
}
|
|
228
|
+
/** Read the sidecar without creating anything (absent = empty). */
|
|
229
|
+
async readState(facts) {
|
|
230
|
+
return readCleanupDocumentAt(facts?.commonDir ?? (await this.facts()).commonDir);
|
|
231
|
+
}
|
|
232
|
+
/** Record a pushed temporary branch; only a recorded push is ever deleted. */
|
|
233
|
+
async recordPush(input) {
|
|
234
|
+
return this.guard(async () => {
|
|
235
|
+
if (typeof input.remote !== 'string' || !REMOTE_NAME.test(input.remote))
|
|
236
|
+
refuse('story-worktree-remote-invalid');
|
|
237
|
+
const probe = await this.probe(input.leaseId);
|
|
238
|
+
if (probe.ownership !== 'proven' || !probe.headSha)
|
|
239
|
+
refuse('story-worktree-ownership-unproven');
|
|
240
|
+
// Remote branches of adopted (native) worktrees are never this tool's to delete.
|
|
241
|
+
if (probe.entry.workspaceMechanism !== 'client_managed_worktree' || !MANAGED_BRANCH.test(probe.entry.temporaryBranch)) {
|
|
242
|
+
refuse(R.ADOPTED_BRANCH);
|
|
243
|
+
}
|
|
244
|
+
// A configured remote only: an unknown name would be resolved as a local path.
|
|
245
|
+
if (!await this.gitOk(probe.facts.mainRoot, ['config', '--get', `remote.${input.remote}.url`]))
|
|
246
|
+
refuse(R.REMOTE_UNKNOWN);
|
|
247
|
+
const remoteSha = await this.lsRemote(probe.facts.mainRoot, input.remote, probe.entry.temporaryBranch);
|
|
248
|
+
if (remoteSha === null)
|
|
249
|
+
refuse(R.REMOTE_UNVERIFIED);
|
|
250
|
+
if (remoteSha === undefined)
|
|
251
|
+
refuse(R.REMOTE_ABSENT);
|
|
252
|
+
if (remoteSha !== probe.headSha)
|
|
253
|
+
refuse(R.REMOTE_DIVERGED);
|
|
254
|
+
const push = { remote: input.remote, branch: probe.entry.temporaryBranch, sha: remoteSha };
|
|
255
|
+
await this.update(probe.entry, undefined, (current) => {
|
|
256
|
+
const next = { ...current, remotePush: push };
|
|
257
|
+
delete next.remoteBranchRemoved;
|
|
258
|
+
return next;
|
|
259
|
+
});
|
|
260
|
+
return { ok: true, value: { leaseId: probe.entry.leaseId, ...push } };
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
/** Optional liveness evidence: a live owner on this host is never swept. */
|
|
264
|
+
async registerOwnerProcess(input) {
|
|
265
|
+
return this.guard(async () => {
|
|
266
|
+
if (!Number.isSafeInteger(input.pid) || input.pid <= 0)
|
|
267
|
+
refuse('story-worktree-owner-pid-invalid');
|
|
268
|
+
const probe = await this.probe(input.leaseId);
|
|
269
|
+
await this.update(probe.entry, undefined, (current) => ({
|
|
270
|
+
...current, ownerPid: input.pid, ownerHostDigest: storyWorktreeOwnerHostDigest(),
|
|
271
|
+
}));
|
|
272
|
+
return { ok: true, value: { leaseId: probe.entry.leaseId } };
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
async cleanup(input) {
|
|
276
|
+
return this.guard(async () => ({ ok: true, value: await this.cleanupUnguarded(input) }));
|
|
277
|
+
}
|
|
278
|
+
async sweep(input = {}) {
|
|
279
|
+
return this.guard(async () => {
|
|
280
|
+
if (input.epicId !== undefined && !EPIC_ID.test(input.epicId))
|
|
281
|
+
refuse('story-worktree-identity-invalid');
|
|
282
|
+
const dryRun = input.dryRun === true;
|
|
283
|
+
const facts = await this.facts();
|
|
284
|
+
const document = await readGitLifecycleRuntime(this.options.projectRoot);
|
|
285
|
+
const allEntries = Object.values(document.storyWorktrees?.entries ?? {});
|
|
286
|
+
const entries = allEntries
|
|
287
|
+
.filter((entry) => input.epicId === undefined || entry.epicId === input.epicId)
|
|
288
|
+
.sort((left, right) => left.leaseId.localeCompare(right.leaseId));
|
|
289
|
+
const state = await this.readState(facts);
|
|
290
|
+
const nowMs = this.now().getTime();
|
|
291
|
+
const host = storyWorktreeOwnerHostDigest();
|
|
292
|
+
const items = [];
|
|
293
|
+
const reasonCodes = [];
|
|
294
|
+
for (const entry of entries) {
|
|
295
|
+
const record = state.records[entry.leaseId];
|
|
296
|
+
const resume = record !== undefined && IN_PROGRESS_STATES.includes(record.state);
|
|
297
|
+
const expired = Date.parse(entry.expiresAt) <= nowMs;
|
|
298
|
+
const alive = record?.ownerPid !== undefined && record.ownerHostDigest === host && this.isProcessAlive(record.ownerPid);
|
|
299
|
+
if (alive || liveClaim(record, nowMs) || (!resume && !expired)) {
|
|
300
|
+
const reasonCode = alive ? R.OWNER_ALIVE : liveClaim(record, nowMs) ? R.CLAIMED : R.LEASE_LIVE;
|
|
301
|
+
items.push({ leaseId: entry.leaseId, action: 'skipped', reasonCode });
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
// A resumed `success` that can no longer prove integration falls back
|
|
305
|
+
// to orphan handling once the lease expired (bundle instead of loop).
|
|
306
|
+
const trigger = !resume ? 'orphan-recovery'
|
|
307
|
+
: record?.trigger === 'success' && expired ? 'orphan-recovery'
|
|
308
|
+
: record?.trigger ?? 'orphan-recovery';
|
|
309
|
+
let result;
|
|
310
|
+
try {
|
|
311
|
+
result = { ok: true, value: await this.cleanupUnguarded({ leaseId: entry.leaseId, trigger, dryRun }) };
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
result = { ok: false, reasonCode: error instanceof CleanupRefusal ? error.reasonCode : R.SWEEP_FAILED };
|
|
315
|
+
}
|
|
316
|
+
if (!result.ok) {
|
|
317
|
+
items.push({ leaseId: entry.leaseId, action: 'preserved', reasonCode: result.reasonCode });
|
|
318
|
+
reasonCodes.push(result.reasonCode);
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
const value = result.value;
|
|
322
|
+
if (value.outcome === 'dry-run') {
|
|
323
|
+
items.push({ leaseId: entry.leaseId, action: 'planned', plannedActions: value.plannedActions ?? [] });
|
|
324
|
+
}
|
|
325
|
+
else if (value.outcome === 'remove-pending') {
|
|
326
|
+
items.push({ leaseId: entry.leaseId, action: 'remove-pending', reasonCode: R.REMOVE_PENDING,
|
|
327
|
+
...(value.bundleDigest ? { bundleDigest: value.bundleDigest } : {}) });
|
|
328
|
+
reasonCodes.push(R.REMOVE_PENDING);
|
|
329
|
+
}
|
|
330
|
+
else {
|
|
331
|
+
items.push({ leaseId: entry.leaseId, action: 'recovered', reasonCode: R.ORPHAN_RECOVERED,
|
|
332
|
+
...(value.bundleDigest ? { bundleDigest: value.bundleDigest } : {}) });
|
|
333
|
+
reasonCodes.push(R.ORPHAN_RECOVERED);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// Records whose journal entry is already gone (e.g. P225.05 `release`):
|
|
337
|
+
// close them, deleting a recorded remote branch only with integration proof.
|
|
338
|
+
const journaled = new Set(allEntries.map((entry) => entry.leaseId));
|
|
339
|
+
for (const record of Object.values(state.records).sort((left, right) => left.leaseId.localeCompare(right.leaseId))) {
|
|
340
|
+
if (journaled.has(record.leaseId) || record.state === 'removed' || liveClaim(record, nowMs))
|
|
341
|
+
continue;
|
|
342
|
+
if (input.epicId !== undefined && record.epicId !== input.epicId)
|
|
343
|
+
continue;
|
|
344
|
+
const reason = await this.closeDetachedRecord(record, facts, dryRun);
|
|
345
|
+
items.push({ leaseId: record.leaseId, action: dryRun ? 'planned' : 'record-closed', ...(reason ? { reasonCode: reason } : {}) });
|
|
346
|
+
if (reason)
|
|
347
|
+
reasonCodes.push(reason);
|
|
348
|
+
}
|
|
349
|
+
const bundlesExpired = await this.expireBundles(state, facts, nowMs, dryRun);
|
|
350
|
+
// Manual worktrees: registered, not journaled. Counted, never touched.
|
|
351
|
+
const listed = await this.manager.registeredWorktrees();
|
|
352
|
+
if (!listed.ok)
|
|
353
|
+
refuse(listed.reasonCode);
|
|
354
|
+
const manual = listed.value.worktrees.filter((worktree) => !allEntries.some((entry) => this.manager.sameWorktreePath(entry.worktreePath, worktree.path))).length;
|
|
355
|
+
if (manual > 0)
|
|
356
|
+
reasonCodes.push(R.MANUAL_PRESERVED);
|
|
357
|
+
return {
|
|
358
|
+
ok: true,
|
|
359
|
+
value: {
|
|
360
|
+
dryRun,
|
|
361
|
+
entriesScanned: entries.length,
|
|
362
|
+
recovered: items.filter((item) => item.action === 'recovered').length,
|
|
363
|
+
removePending: items.filter((item) => item.action === 'remove-pending').length,
|
|
364
|
+
preserved: items.filter((item) => item.action === 'preserved').length,
|
|
365
|
+
skipped: items.filter((item) => item.action === 'skipped').length,
|
|
366
|
+
manualWorktreesPreserved: manual,
|
|
367
|
+
bundlesExpired,
|
|
368
|
+
items,
|
|
369
|
+
reasonCodes: unique(reasonCodes),
|
|
370
|
+
},
|
|
371
|
+
};
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
// ---------------------------------------------------------------- internals
|
|
375
|
+
async cleanupUnguarded(input) {
|
|
376
|
+
if (!STORY_WORKTREE_CLEANUP_TRIGGERS.includes(input.trigger))
|
|
377
|
+
refuse('story-worktree-trigger-invalid');
|
|
378
|
+
const probe = await this.probe(input.leaseId);
|
|
379
|
+
const { entry, facts } = probe;
|
|
380
|
+
const state = await this.readState(facts);
|
|
381
|
+
const record = state.records[entry.leaseId];
|
|
382
|
+
if (entry.state === 'creating') {
|
|
383
|
+
if (input.trigger !== 'orphan-recovery')
|
|
384
|
+
refuse('story-worktree-ownership-unproven');
|
|
385
|
+
return this.recoverCreating(probe, input.dryRun === true);
|
|
386
|
+
}
|
|
387
|
+
const resuming = record !== undefined && IN_PROGRESS_STATES.includes(record.state);
|
|
388
|
+
let vanished = false;
|
|
389
|
+
if (!probe.pathExists) {
|
|
390
|
+
// Only a definitely missing directory (ENOENT) is "vanished"; EACCES or an
|
|
391
|
+
// unmounted volume is unproven. Without the marker it can no longer be
|
|
392
|
+
// proven, so only orphan recovery or our own resumed cleanup may proceed.
|
|
393
|
+
if (!await this.definitelyMissing(entry.worktreePath))
|
|
394
|
+
refuse(R.ORPHAN_UNPROVEN);
|
|
395
|
+
if (input.trigger !== 'orphan-recovery' && !resuming)
|
|
396
|
+
refuse('story-worktree-ownership-unproven');
|
|
397
|
+
vanished = true;
|
|
398
|
+
}
|
|
399
|
+
if (!vanished && probe.ownership !== 'proven')
|
|
400
|
+
refuse('story-worktree-ownership-unproven');
|
|
401
|
+
if (!vanished && probe.clean !== true)
|
|
402
|
+
refuse(input.trigger === 'success' ? 'story-worktree-dirty' : R.DIRTY_PRESERVED);
|
|
403
|
+
if (!probe.epicHead)
|
|
404
|
+
refuse('story-worktree-epic-branch-missing');
|
|
405
|
+
const epicHead = probe.epicHead;
|
|
406
|
+
const tip = vanished ? probe.branchSha : probe.headSha;
|
|
407
|
+
if (!vanished && !tip)
|
|
408
|
+
refuse('story-worktree-git-failed');
|
|
409
|
+
const integrated = probe.integrated === true;
|
|
410
|
+
if (input.trigger === 'success' && !integrated)
|
|
411
|
+
refuse('story-worktree-not-integrated');
|
|
412
|
+
const ownBranch = entry.workspaceMechanism === 'client_managed_worktree';
|
|
413
|
+
const reusableBundle = record?.bundleDigest !== undefined && record.headSha !== undefined && record.headSha === tip
|
|
414
|
+
&& await this.bundleMatches(facts, entry.leaseId, record.headSha, record.bundleDigest);
|
|
415
|
+
const needBundle = !integrated && tip !== undefined && ownBranch && !reusableBundle;
|
|
416
|
+
const remotePending = record?.remotePush !== undefined && record.remoteBranchRemoved !== true;
|
|
417
|
+
if (input.dryRun === true) {
|
|
418
|
+
const plannedActions = [
|
|
419
|
+
...(needBundle ? ['bundle-unintegrated-range'] : []),
|
|
420
|
+
vanished ? 'drop-worktree-metadata' : 'remove-worktree',
|
|
421
|
+
...(ownBranch && probe.branchSha ? ['delete-local-branch'] : []),
|
|
422
|
+
...(remotePending ? ['delete-remote-branch'] : []),
|
|
423
|
+
];
|
|
424
|
+
return {
|
|
425
|
+
leaseId: entry.leaseId, outcome: 'dry-run', trigger: input.trigger, state: record?.state ?? 'active',
|
|
426
|
+
plannedActions, preservedReasonCodes: [],
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
const token = await this.claim(entry);
|
|
430
|
+
let finalized = false;
|
|
431
|
+
try {
|
|
432
|
+
// Intent is persisted only once its preconditions hold: a refused bundle
|
|
433
|
+
// (quota, verification) leaves no in-progress state behind.
|
|
434
|
+
let bundleDigest = reusableBundle ? record?.bundleDigest : undefined;
|
|
435
|
+
if (needBundle) {
|
|
436
|
+
const bundle = await this.createBundle(probe, tip, epicHead);
|
|
437
|
+
bundleDigest = bundle.digest;
|
|
438
|
+
await this.update(entry, token, (current) => ({
|
|
439
|
+
...current, state: 'bundled', trigger: input.trigger, headSha: tip, bundleDigest: bundle.digest, bundleBytes: bundle.bytes,
|
|
440
|
+
bundleExpiresAt: new Date(this.now().getTime() + (this.options.bundleTtlMs ?? DEFAULT_BUNDLE_TTL_MS)).toISOString(),
|
|
441
|
+
}));
|
|
442
|
+
}
|
|
443
|
+
else if (!reusableBundle) {
|
|
444
|
+
const intent = integrated ? 'integrated' : input.trigger === 'failure' ? 'failed' : 'abandoned';
|
|
445
|
+
await this.update(entry, token, (current) => ({
|
|
446
|
+
...current, state: current.state === 'remove-pending' ? 'remove-pending' : intent,
|
|
447
|
+
trigger: input.trigger, ...(tip ? { headSha: tip } : {}),
|
|
448
|
+
}));
|
|
449
|
+
}
|
|
450
|
+
if (!vanished) {
|
|
451
|
+
const attempts = this.options.removeAttempts ?? DEFAULT_REMOVE_ATTEMPTS;
|
|
452
|
+
if (!await this.removeWithRetry(facts.mainRoot, entry.worktreePath, attempts)) {
|
|
453
|
+
await this.update(entry, token, (current) => ({
|
|
454
|
+
...current, state: 'remove-pending', trigger: input.trigger,
|
|
455
|
+
removeAttempts: Math.min(1000, current.removeAttempts + attempts),
|
|
456
|
+
}));
|
|
457
|
+
return {
|
|
458
|
+
leaseId: entry.leaseId, outcome: 'remove-pending', trigger: input.trigger, state: 'remove-pending',
|
|
459
|
+
...(bundleDigest ? { bundleDigest } : {}), preservedReasonCodes: [R.REMOVE_PENDING],
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
else {
|
|
464
|
+
// Targeted metadata removal for the vanished directory only.
|
|
465
|
+
await runStoryWorktreeGit(facts.mainRoot, ['worktree', 'remove', entry.worktreePath]);
|
|
466
|
+
}
|
|
467
|
+
await runStoryWorktreeGit(facts.mainRoot, ['worktree', 'prune']);
|
|
468
|
+
// Removal proof: the journaled path is no longer a registered worktree
|
|
469
|
+
// (a locked or moved worktree survives prune and stays journaled).
|
|
470
|
+
const list = await this.manager.registeredWorktrees();
|
|
471
|
+
if (!list.ok)
|
|
472
|
+
refuse(list.reasonCode);
|
|
473
|
+
if (list.value.worktrees.some((worktree) => this.manager.sameWorktreePath(worktree.path, entry.worktreePath))) {
|
|
474
|
+
refuse(R.ORPHAN_UNPROVEN);
|
|
475
|
+
}
|
|
476
|
+
const preserved = [];
|
|
477
|
+
let localBranchRemoved = false;
|
|
478
|
+
if (!ownBranch) {
|
|
479
|
+
preserved.push(R.ADOPTED_BRANCH);
|
|
480
|
+
}
|
|
481
|
+
else if (probe.branchSha) {
|
|
482
|
+
const expected = tip ?? probe.branchSha;
|
|
483
|
+
const safeToDelete = integrated || bundleDigest !== undefined;
|
|
484
|
+
const checkedOut = list.value.worktrees.some((worktree) => worktree.branch === entry.temporaryBranch);
|
|
485
|
+
if (!safeToDelete) {
|
|
486
|
+
preserved.push(R.ORPHAN_UNPROVEN);
|
|
487
|
+
}
|
|
488
|
+
else if (checkedOut) {
|
|
489
|
+
preserved.push(R.BRANCH_CHECKED_OUT);
|
|
490
|
+
}
|
|
491
|
+
else if (await this.gitOk(facts.mainRoot, ['update-ref', '-d', `refs/heads/${entry.temporaryBranch}`, expected])) {
|
|
492
|
+
localBranchRemoved = true;
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
preserved.push(R.BRANCH_MOVED);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
// Re-read under the claim: a `record-push` that landed after the first
|
|
499
|
+
// read must not be ignored (and later erased) by this cleanup.
|
|
500
|
+
const claimedRecord = (await this.readState(facts)).records[entry.leaseId] ?? record;
|
|
501
|
+
const remote = await this.deleteRemote(entry, facts, claimedRecord, token, { epicHead, ...(tip ? { tip } : {}), bundled: bundleDigest !== undefined });
|
|
502
|
+
if (remote.reasonCode)
|
|
503
|
+
preserved.push(remote.reasonCode);
|
|
504
|
+
// A recorded remote branch whose deletion is still unproven stays as a
|
|
505
|
+
// detached record so the next sweep retries it (closeDetachedRecord).
|
|
506
|
+
const remoteRetry = claimedRecord?.remotePush !== undefined && !remote.removed
|
|
507
|
+
&& (remote.reasonCode === R.REMOTE_UNVERIFIED || remote.reasonCode === R.REMOTE_UNPRESERVED);
|
|
508
|
+
const cleanedAt = this.now().toISOString();
|
|
509
|
+
const receipt = {
|
|
510
|
+
schemaVersion: 1,
|
|
511
|
+
kind: 'cleanup-receipt',
|
|
512
|
+
receiptId: `swc-${sha256(`${entry.leaseId}|${entry.nonceDigest}|${input.trigger}|${cleanedAt}`).slice(0, 24)}`,
|
|
513
|
+
epicId: entry.epicId,
|
|
514
|
+
storyId: entry.storyId,
|
|
515
|
+
leaseId: entry.leaseId,
|
|
516
|
+
trigger: input.trigger,
|
|
517
|
+
worktreeRemoved: true,
|
|
518
|
+
localBranchRemoved,
|
|
519
|
+
remoteBranchRemoved: remote.removed,
|
|
520
|
+
...(preserved[0] ? { preservedReasonCode: preserved[0] } : {}),
|
|
521
|
+
cleanedAt,
|
|
522
|
+
};
|
|
523
|
+
if (!isStoryWorktreeCleanupReceiptRecord(receipt))
|
|
524
|
+
refuse('story-worktree-receipt-invalid');
|
|
525
|
+
await this.mutate((document) => {
|
|
526
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
527
|
+
const current = journal.entries[entry.leaseId];
|
|
528
|
+
if (!current || current.nonceDigest !== entry.nonceDigest)
|
|
529
|
+
refuse(R.ENTRY_CONFLICT);
|
|
530
|
+
delete journal.entries[entry.leaseId];
|
|
531
|
+
journal.cleanupReceipts.push({ ...receipt });
|
|
532
|
+
while (journal.cleanupReceipts.length > STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS)
|
|
533
|
+
journal.cleanupReceipts.shift();
|
|
534
|
+
}, (sidecar) => {
|
|
535
|
+
const current = sidecar.records[entry.leaseId];
|
|
536
|
+
if (!current)
|
|
537
|
+
return;
|
|
538
|
+
if (remoteRetry && current.remotePush !== undefined) {
|
|
539
|
+
const pendingState = current.state === 'removed' || current.state === 'remove-pending' || current.state === 'active'
|
|
540
|
+
? (current.bundleDigest ? 'bundled' : 'integrated') : current.state;
|
|
541
|
+
const next = { ...current, state: pendingState, updatedAt: cleanedAt, remoteBranchRemoved: false };
|
|
542
|
+
delete next.claimToken;
|
|
543
|
+
delete next.claimExpiresAt;
|
|
544
|
+
sidecar.records[entry.leaseId] = next;
|
|
545
|
+
}
|
|
546
|
+
else if (current.bundleDigest) {
|
|
547
|
+
const next = { ...current, state: 'removed', updatedAt: cleanedAt, remoteBranchRemoved: remote.removed };
|
|
548
|
+
delete next.claimToken;
|
|
549
|
+
delete next.claimExpiresAt;
|
|
550
|
+
sidecar.records[entry.leaseId] = next;
|
|
551
|
+
}
|
|
552
|
+
else {
|
|
553
|
+
delete sidecar.records[entry.leaseId];
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
finalized = true;
|
|
557
|
+
return {
|
|
558
|
+
leaseId: entry.leaseId, outcome: 'removed', trigger: input.trigger, state: 'removed',
|
|
559
|
+
receipt, receiptDigest: digestStoryWorktreeReceiptLocal(receipt),
|
|
560
|
+
...(bundleDigest ? { bundleDigest } : {}), preservedReasonCodes: unique(preserved),
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
finally {
|
|
564
|
+
if (!finalized)
|
|
565
|
+
await this.releaseClaim(entry, token).catch(() => undefined);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Expired `creating` reservation (crash between reserve and activate). Only
|
|
570
|
+
* a provably empty worktree at `baseSha` on its own branch is removed.
|
|
571
|
+
*/
|
|
572
|
+
async recoverCreating(probe, dryRun) {
|
|
573
|
+
const { entry, facts } = probe;
|
|
574
|
+
const base = { leaseId: entry.leaseId, trigger: 'orphan-recovery', preservedReasonCodes: [] };
|
|
575
|
+
let removeTree = false;
|
|
576
|
+
if (probe.pathExists) {
|
|
577
|
+
const head = await runStoryWorktreeGit(entry.worktreePath, ['rev-parse', 'HEAD']);
|
|
578
|
+
const branch = await runStoryWorktreeGit(entry.worktreePath, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
579
|
+
const status = await runStoryWorktreeGit(entry.worktreePath, ['status', '--porcelain=v1', '--untracked-files=all', '-z']);
|
|
580
|
+
const empty = probe.registered && head.ok && head.stdout.trim() === entry.baseSha
|
|
581
|
+
&& branch.ok && branch.stdout.trim() === entry.temporaryBranch && status.ok && status.stdout.length === 0;
|
|
582
|
+
if (!empty)
|
|
583
|
+
refuse(R.ORPHAN_UNPROVEN);
|
|
584
|
+
removeTree = true;
|
|
585
|
+
}
|
|
586
|
+
else {
|
|
587
|
+
if (!await this.definitelyMissing(entry.worktreePath))
|
|
588
|
+
refuse(R.ORPHAN_UNPROVEN);
|
|
589
|
+
// The branch may be checked out by another (manual) worktree: never pull it away.
|
|
590
|
+
if (probe.branchCheckedOut)
|
|
591
|
+
refuse(R.ORPHAN_UNPROVEN);
|
|
592
|
+
}
|
|
593
|
+
if (probe.branchSha !== undefined && probe.branchSha !== entry.baseSha)
|
|
594
|
+
refuse(R.ORPHAN_UNPROVEN);
|
|
595
|
+
if (dryRun) {
|
|
596
|
+
return {
|
|
597
|
+
...base, outcome: 'dry-run', state: 'active',
|
|
598
|
+
plannedActions: [...(removeTree ? ['remove-worktree'] : []), ...(probe.branchSha ? ['delete-local-branch'] : []), 'drop-reservation'],
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
const token = await this.claim(entry);
|
|
602
|
+
let finalized = false;
|
|
603
|
+
try {
|
|
604
|
+
if (removeTree && !await this.removeWithRetry(facts.mainRoot, entry.worktreePath, this.options.removeAttempts ?? DEFAULT_REMOVE_ATTEMPTS)) {
|
|
605
|
+
refuse(R.REMOVE_PENDING);
|
|
606
|
+
}
|
|
607
|
+
if (removeTree)
|
|
608
|
+
await runStoryWorktreeGit(facts.mainRoot, ['worktree', 'prune']);
|
|
609
|
+
let localBranchRemoved = false;
|
|
610
|
+
if (probe.branchSha) {
|
|
611
|
+
localBranchRemoved = await this.gitOk(facts.mainRoot, ['update-ref', '-d', `refs/heads/${entry.temporaryBranch}`, entry.baseSha]);
|
|
612
|
+
}
|
|
613
|
+
const cleanedAt = this.now().toISOString();
|
|
614
|
+
const receipt = {
|
|
615
|
+
schemaVersion: 1, kind: 'cleanup-receipt',
|
|
616
|
+
receiptId: `swc-${sha256(`${entry.leaseId}|${entry.nonceDigest}|creating|${cleanedAt}`).slice(0, 24)}`,
|
|
617
|
+
epicId: entry.epicId, storyId: entry.storyId, leaseId: entry.leaseId, trigger: 'orphan-recovery',
|
|
618
|
+
worktreeRemoved: removeTree, localBranchRemoved, remoteBranchRemoved: false,
|
|
619
|
+
...(probe.branchSha && !localBranchRemoved ? { preservedReasonCode: R.BRANCH_MOVED } : {}),
|
|
620
|
+
cleanedAt,
|
|
621
|
+
};
|
|
622
|
+
if (!isStoryWorktreeCleanupReceiptRecord(receipt))
|
|
623
|
+
refuse('story-worktree-receipt-invalid');
|
|
624
|
+
await this.mutate((document) => {
|
|
625
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
626
|
+
const current = journal.entries[entry.leaseId];
|
|
627
|
+
if (!current || current.state !== 'creating' || current.nonceDigest !== entry.nonceDigest)
|
|
628
|
+
refuse(R.ENTRY_CONFLICT);
|
|
629
|
+
delete journal.entries[entry.leaseId];
|
|
630
|
+
journal.cleanupReceipts.push({ ...receipt });
|
|
631
|
+
while (journal.cleanupReceipts.length > STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS)
|
|
632
|
+
journal.cleanupReceipts.shift();
|
|
633
|
+
}, (sidecar) => {
|
|
634
|
+
delete sidecar.records[entry.leaseId];
|
|
635
|
+
});
|
|
636
|
+
finalized = true;
|
|
637
|
+
return {
|
|
638
|
+
...base, outcome: 'reclaimed', state: 'removed', receipt, receiptDigest: digestStoryWorktreeReceiptLocal(receipt),
|
|
639
|
+
preservedReasonCodes: receipt.preservedReasonCode ? [receipt.preservedReasonCode] : [],
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
finally {
|
|
643
|
+
if (!finalized)
|
|
644
|
+
await this.releaseClaim(entry, token).catch(() => undefined);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
async closeDetachedRecord(record, facts, dryRun) {
|
|
648
|
+
let reason;
|
|
649
|
+
let remoteRemoved = record.remoteBranchRemoved === true;
|
|
650
|
+
if (record.remotePush && !remoteRemoved) {
|
|
651
|
+
const epic = await runStoryWorktreeGit(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/epic/${record.epicId}^{commit}`]);
|
|
652
|
+
const integrated = epic.ok && await this.gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', record.remotePush.sha, epic.stdout.trim()]);
|
|
653
|
+
if (!integrated) {
|
|
654
|
+
reason = R.REMOTE_UNPRESERVED;
|
|
655
|
+
}
|
|
656
|
+
else if (!dryRun) {
|
|
657
|
+
const outcome = await this.deleteRecordedRemote(facts.mainRoot, record.remotePush);
|
|
658
|
+
remoteRemoved = outcome.removed;
|
|
659
|
+
reason = outcome.reasonCode;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (dryRun)
|
|
663
|
+
return reason;
|
|
664
|
+
// Keep the record while a recorded remote branch still needs proof.
|
|
665
|
+
if (reason === R.REMOTE_UNPRESERVED || reason === R.REMOTE_UNVERIFIED)
|
|
666
|
+
return reason;
|
|
667
|
+
await this.mutate(undefined, (sidecar) => {
|
|
668
|
+
const current = sidecar.records[record.leaseId];
|
|
669
|
+
if (!current || current.state === 'removed')
|
|
670
|
+
return;
|
|
671
|
+
if (current.bundleDigest) {
|
|
672
|
+
sidecar.records[record.leaseId] = { ...current, state: 'removed', remoteBranchRemoved: remoteRemoved, updatedAt: this.now().toISOString() };
|
|
673
|
+
}
|
|
674
|
+
else {
|
|
675
|
+
delete sidecar.records[record.leaseId];
|
|
676
|
+
}
|
|
677
|
+
});
|
|
678
|
+
return reason;
|
|
679
|
+
}
|
|
680
|
+
async deleteRemote(entry, facts, record, token, proof) {
|
|
681
|
+
const push = record?.remotePush;
|
|
682
|
+
if (!push)
|
|
683
|
+
return { removed: false };
|
|
684
|
+
if (record?.remoteBranchRemoved === true)
|
|
685
|
+
return { removed: true };
|
|
686
|
+
if (entry.workspaceMechanism !== 'client_managed_worktree' || push.branch !== entry.temporaryBranch) {
|
|
687
|
+
return { removed: false, reasonCode: R.ADOPTED_BRANCH };
|
|
688
|
+
}
|
|
689
|
+
// The recorded remote SHA itself must survive locally: contained in the
|
|
690
|
+
// epic branch, or in the verified bundle's tip. Tip integration alone is not
|
|
691
|
+
// enough (the branch may have been rewritten after the push was recorded).
|
|
692
|
+
const inEpic = await this.gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', push.sha, proof.epicHead]);
|
|
693
|
+
const inBundle = !inEpic && proof.bundled && proof.tip !== undefined
|
|
694
|
+
&& await this.gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', push.sha, proof.tip]);
|
|
695
|
+
if (!inEpic && !inBundle)
|
|
696
|
+
return { removed: false, reasonCode: R.REMOTE_UNPRESERVED };
|
|
697
|
+
const outcome = await this.deleteRecordedRemote(facts.mainRoot, push);
|
|
698
|
+
if (outcome.removed)
|
|
699
|
+
await this.update(entry, token, (current) => ({ ...current, remoteBranchRemoved: true }));
|
|
700
|
+
return outcome;
|
|
701
|
+
}
|
|
702
|
+
async deleteRecordedRemote(mainRoot, push) {
|
|
703
|
+
if (!await this.gitOk(mainRoot, ['config', '--get', `remote.${push.remote}.url`]))
|
|
704
|
+
return { removed: false, reasonCode: R.REMOTE_UNKNOWN };
|
|
705
|
+
const remoteSha = await this.lsRemote(mainRoot, push.remote, push.branch);
|
|
706
|
+
if (remoteSha === null)
|
|
707
|
+
return { removed: false, reasonCode: R.REMOTE_UNVERIFIED };
|
|
708
|
+
if (remoteSha === undefined)
|
|
709
|
+
return { removed: false, reasonCode: R.REMOTE_ABSENT };
|
|
710
|
+
if (remoteSha !== push.sha)
|
|
711
|
+
return { removed: false, reasonCode: R.REMOTE_DIVERGED };
|
|
712
|
+
// Compare-and-swap deletion: refused unless the remote is still at the recorded SHA.
|
|
713
|
+
const pushed = await this.gitOk(mainRoot, [
|
|
714
|
+
'push', '--porcelain', `--force-with-lease=refs/heads/${push.branch}:${push.sha}`,
|
|
715
|
+
push.remote, '--delete', `refs/heads/${push.branch}`,
|
|
716
|
+
]);
|
|
717
|
+
if (!pushed)
|
|
718
|
+
return { removed: false, reasonCode: R.REMOTE_UNVERIFIED };
|
|
719
|
+
// Physical proof: the remote no longer lists the branch.
|
|
720
|
+
const after = await this.lsRemote(mainRoot, push.remote, push.branch);
|
|
721
|
+
return after === undefined ? { removed: true } : { removed: false, reasonCode: R.REMOTE_UNVERIFIED };
|
|
722
|
+
}
|
|
723
|
+
/** `undefined` = branch absent, `null` = remote unverifiable. */
|
|
724
|
+
async lsRemote(mainRoot, remote, branch) {
|
|
725
|
+
const listed = await runStoryWorktreeGit(mainRoot, ['ls-remote', '--heads', remote, `refs/heads/${branch}`]);
|
|
726
|
+
if (!listed.ok)
|
|
727
|
+
return null;
|
|
728
|
+
const line = listed.stdout.split('\n').map((item) => item.trim()).find((item) => item.endsWith(`\trefs/heads/${branch}`));
|
|
729
|
+
if (!line)
|
|
730
|
+
return undefined;
|
|
731
|
+
const sha = line.split('\t')[0] ?? '';
|
|
732
|
+
return FULL_SHA.test(sha) ? sha : null;
|
|
733
|
+
}
|
|
734
|
+
async createBundle(probe, tip, epicHead) {
|
|
735
|
+
const { entry, facts } = probe;
|
|
736
|
+
const directory = await ensureGitLifecyclePrivateChildDirectory(await gitLifecycleRuntimeDirectory(this.options.projectRoot), STORY_WORKTREE_BUNDLE_DIRECTORY);
|
|
737
|
+
const own = storyWorktreeBundleFileName(entry.leaseId, tip);
|
|
738
|
+
const existing = (await readdir(directory)).filter((name) => BUNDLE_FILE.test(name));
|
|
739
|
+
const others = existing.filter((name) => name !== own);
|
|
740
|
+
if (others.length >= (this.options.maxBundles ?? DEFAULT_MAX_BUNDLES))
|
|
741
|
+
refuse(R.BUNDLE_QUOTA);
|
|
742
|
+
let used = 0;
|
|
743
|
+
for (const name of others)
|
|
744
|
+
used += (await stat(join(directory, name))).size;
|
|
745
|
+
const target = join(directory, own);
|
|
746
|
+
// A file for this exact tip is an unverified leftover of a crashed attempt
|
|
747
|
+
// (a verified one would have been reused). Earlier tips are never touched.
|
|
748
|
+
await rm(target, { force: true });
|
|
749
|
+
const ref = `refs/heads/${entry.temporaryBranch}`;
|
|
750
|
+
if (!await this.gitOk(facts.mainRoot, ['bundle', 'create', target, ref, `^${epicHead}`])) {
|
|
751
|
+
await rm(target, { force: true });
|
|
752
|
+
refuse(R.BUNDLE_FAILED);
|
|
753
|
+
}
|
|
754
|
+
if (process.platform !== 'win32')
|
|
755
|
+
await chmod(target, 0o600);
|
|
756
|
+
const bytes = (await stat(target)).size;
|
|
757
|
+
if (used + bytes > (this.options.maxBundleBytes ?? DEFAULT_MAX_BUNDLE_BYTES)) {
|
|
758
|
+
await rm(target, { force: true });
|
|
759
|
+
refuse(R.BUNDLE_QUOTA);
|
|
760
|
+
}
|
|
761
|
+
const heads = await runStoryWorktreeGit(facts.mainRoot, ['bundle', 'list-heads', target]);
|
|
762
|
+
const verified = await this.gitOk(facts.mainRoot, ['bundle', 'verify', '--quiet', target]);
|
|
763
|
+
if (!verified || !heads.ok || !heads.stdout.split('\n').some((line) => line.trim() === `${tip} ${ref}`)) {
|
|
764
|
+
await rm(target, { force: true });
|
|
765
|
+
refuse(R.BUNDLE_UNVERIFIED);
|
|
766
|
+
}
|
|
767
|
+
return { digest: sha256(await readFile(target)), bytes };
|
|
768
|
+
}
|
|
769
|
+
/** Read-only digest check (never creates directories; safe in dry-run). */
|
|
770
|
+
async bundleMatches(facts, leaseId, headSha, digest) {
|
|
771
|
+
try {
|
|
772
|
+
const path = join(facts.commonDir, GIT_LIFECYCLE_RUNTIME_DIRECTORY, STORY_WORKTREE_BUNDLE_DIRECTORY, storyWorktreeBundleFileName(leaseId, headSha));
|
|
773
|
+
return sha256(await readFile(path)) === digest;
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
return false;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* TTL: expired bundles of finished records, plus unreferenced bundle files
|
|
781
|
+
* (crash between `bundle create` and its record) older than the TTL.
|
|
782
|
+
*/
|
|
783
|
+
async expireBundles(state, facts, nowMs, dryRun) {
|
|
784
|
+
const directory = join(facts.commonDir, GIT_LIFECYCLE_RUNTIME_DIRECTORY, STORY_WORKTREE_BUNDLE_DIRECTORY);
|
|
785
|
+
const expiredRecords = Object.values(state.records).filter((record) => record.state === 'removed'
|
|
786
|
+
&& record.bundleExpiresAt !== undefined && Date.parse(record.bundleExpiresAt) <= nowMs);
|
|
787
|
+
const referenced = new Set(Object.values(state.records)
|
|
788
|
+
.filter((record) => record.bundleDigest !== undefined && record.headSha !== undefined
|
|
789
|
+
&& !expiredRecords.some((expired) => expired.leaseId === record.leaseId))
|
|
790
|
+
.map((record) => storyWorktreeBundleFileName(record.leaseId, record.headSha)));
|
|
791
|
+
const ttl = this.options.bundleTtlMs ?? DEFAULT_BUNDLE_TTL_MS;
|
|
792
|
+
const unreferenced = [];
|
|
793
|
+
if (existsSync(directory)) {
|
|
794
|
+
for (const name of (await readdir(directory)).filter((item) => BUNDLE_FILE.test(item) && !referenced.has(item))) {
|
|
795
|
+
const leaseId = name.slice(0, 28);
|
|
796
|
+
const live = state.records[leaseId];
|
|
797
|
+
// Files of an expired record go; other unreferenced files only after TTL.
|
|
798
|
+
if (expiredRecords.some((record) => record.leaseId === leaseId)
|
|
799
|
+
|| (!live && nowMs - (await stat(join(directory, name))).mtimeMs >= ttl)) {
|
|
800
|
+
unreferenced.push(name);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
if (dryRun || (unreferenced.length === 0 && expiredRecords.length === 0))
|
|
805
|
+
return unreferenced.length;
|
|
806
|
+
await this.mutate(undefined, (sidecar) => {
|
|
807
|
+
for (const record of expiredRecords) {
|
|
808
|
+
const current = sidecar.records[record.leaseId];
|
|
809
|
+
if (current?.state === 'removed' && current.bundleExpiresAt === record.bundleExpiresAt)
|
|
810
|
+
delete sidecar.records[record.leaseId];
|
|
811
|
+
}
|
|
812
|
+
});
|
|
813
|
+
for (const name of unreferenced)
|
|
814
|
+
await rm(join(directory, name), { force: true });
|
|
815
|
+
return unreferenced.length;
|
|
816
|
+
}
|
|
817
|
+
async definitelyMissing(path) {
|
|
818
|
+
try {
|
|
819
|
+
await lstat(path);
|
|
820
|
+
return false;
|
|
821
|
+
}
|
|
822
|
+
catch (error) {
|
|
823
|
+
return error.code === 'ENOENT';
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
async removeWithRetry(mainRoot, worktreePath, attempts) {
|
|
827
|
+
const remover = this.options.removeWorktree
|
|
828
|
+
?? ((root, path) => this.gitOk(root, ['worktree', 'remove', path]));
|
|
829
|
+
const delay = this.options.removeDelayMs ?? DEFAULT_REMOVE_DELAY_MS;
|
|
830
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
831
|
+
if (await remover(mainRoot, worktreePath))
|
|
832
|
+
return true;
|
|
833
|
+
if (attempt < attempts)
|
|
834
|
+
await sleep(delay * attempt);
|
|
835
|
+
}
|
|
836
|
+
return false;
|
|
837
|
+
}
|
|
838
|
+
async probe(leaseId) {
|
|
839
|
+
const result = await this.manager.probe(leaseId);
|
|
840
|
+
if (!result.ok)
|
|
841
|
+
refuse(result.reasonCode);
|
|
842
|
+
return result.value;
|
|
843
|
+
}
|
|
844
|
+
async facts() {
|
|
845
|
+
const listed = await this.manager.registeredWorktrees();
|
|
846
|
+
if (!listed.ok)
|
|
847
|
+
refuse(listed.reasonCode);
|
|
848
|
+
return listed.value.facts;
|
|
849
|
+
}
|
|
850
|
+
async gitOk(cwd, args) {
|
|
851
|
+
return (await runStoryWorktreeGit(cwd, args)).ok;
|
|
852
|
+
}
|
|
853
|
+
/** Per-lease cleanup claim (compare-and-set under the runtime lock). */
|
|
854
|
+
async claim(entry) {
|
|
855
|
+
const token = randomBytes(8).toString('hex');
|
|
856
|
+
await this.mutate((document) => {
|
|
857
|
+
const current = document.storyWorktrees?.entries[entry.leaseId];
|
|
858
|
+
if (!current || current.nonceDigest !== entry.nonceDigest)
|
|
859
|
+
refuse(R.ENTRY_CONFLICT);
|
|
860
|
+
}, (sidecar) => {
|
|
861
|
+
const nowMs = this.now().getTime();
|
|
862
|
+
const current = sidecar.records[entry.leaseId] ?? this.emptyRecord(entry);
|
|
863
|
+
if (liveClaim(current, nowMs))
|
|
864
|
+
refuse(R.CLAIMED);
|
|
865
|
+
sidecar.records[entry.leaseId] = {
|
|
866
|
+
...current, claimToken: token,
|
|
867
|
+
claimExpiresAt: new Date(nowMs + (this.options.claimTtlMs ?? DEFAULT_CLAIM_TTL_MS)).toISOString(),
|
|
868
|
+
updatedAt: new Date(nowMs).toISOString(),
|
|
869
|
+
};
|
|
870
|
+
});
|
|
871
|
+
return token;
|
|
872
|
+
}
|
|
873
|
+
/** Drop our claim; a record that carries nothing else returns to absence. */
|
|
874
|
+
async releaseClaim(entry, token) {
|
|
875
|
+
await this.mutate(undefined, (sidecar) => {
|
|
876
|
+
const current = sidecar.records[entry.leaseId];
|
|
877
|
+
if (!current || current.claimToken !== token)
|
|
878
|
+
return;
|
|
879
|
+
const next = { ...current };
|
|
880
|
+
delete next.claimToken;
|
|
881
|
+
delete next.claimExpiresAt;
|
|
882
|
+
const meaningful = current.state !== 'active' || current.remotePush !== undefined || current.ownerPid !== undefined
|
|
883
|
+
|| current.bundleDigest !== undefined || current.removeAttempts > 0;
|
|
884
|
+
if (meaningful)
|
|
885
|
+
sidecar.records[entry.leaseId] = next;
|
|
886
|
+
else
|
|
887
|
+
delete sidecar.records[entry.leaseId];
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
emptyRecord(entry) {
|
|
891
|
+
return {
|
|
892
|
+
schemaVersion: 1, leaseId: entry.leaseId, epicId: entry.epicId, storyId: entry.storyId,
|
|
893
|
+
state: 'active', removeAttempts: 0, updatedAt: this.now().toISOString(),
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Create-or-update one sidecar record bound to a live journal entry (same
|
|
898
|
+
* nonce). A foreign live claim refuses; `token` identifies our own claim.
|
|
899
|
+
*/
|
|
900
|
+
async update(entry, token, change) {
|
|
901
|
+
await this.mutate((document) => {
|
|
902
|
+
const current = document.storyWorktrees?.entries[entry.leaseId];
|
|
903
|
+
if (!current || current.nonceDigest !== entry.nonceDigest)
|
|
904
|
+
refuse(R.ENTRY_CONFLICT);
|
|
905
|
+
}, (sidecar) => {
|
|
906
|
+
const current = sidecar.records[entry.leaseId] ?? this.emptyRecord(entry);
|
|
907
|
+
if (liveClaim(current, this.now().getTime()) && current.claimToken !== token)
|
|
908
|
+
refuse(R.CLAIMED);
|
|
909
|
+
const next = { ...change(current), updatedAt: this.now().toISOString() };
|
|
910
|
+
if (!isStoryWorktreeCleanupRecord(entry.leaseId, next))
|
|
911
|
+
refuse(R.STATE_INVALID);
|
|
912
|
+
sidecar.records[entry.leaseId] = next;
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* One serialized write: journal mutation (optional) and sidecar mutation run
|
|
917
|
+
* under the lifecycle runtime's exclusive lock; the sidecar is validated and
|
|
918
|
+
* written atomically in `preCommit`, before the runtime document itself.
|
|
919
|
+
*/
|
|
920
|
+
async mutate(applyJournal, applySidecar) {
|
|
921
|
+
const attempts = this.options.lockRetry?.attempts ?? 40;
|
|
922
|
+
const delayMs = this.options.lockRetry?.delayMs ?? 25;
|
|
923
|
+
for (let attempt = 1;; attempt++) {
|
|
924
|
+
try {
|
|
925
|
+
await mutateGitLifecycleRuntime(this.options.projectRoot, (document) => {
|
|
926
|
+
applyJournal?.(document);
|
|
927
|
+
compactStoryWorktreeJournal(document);
|
|
928
|
+
}, {
|
|
929
|
+
preCommit: async () => {
|
|
930
|
+
const runtimeDirectory = await gitLifecycleRuntimeDirectory(this.options.projectRoot);
|
|
931
|
+
const path = join(runtimeDirectory, STORY_WORKTREE_CLEANUP_FILE);
|
|
932
|
+
let sidecar = { schemaVersion: 1, records: {} };
|
|
933
|
+
if (existsSync(path)) {
|
|
934
|
+
await assertGitLifecyclePrivateFile(path, runtimeDirectory);
|
|
935
|
+
const parsed = parseStoryWorktreeCleanupDocument(await readFile(path, 'utf8'));
|
|
936
|
+
sidecar = { schemaVersion: 1, records: { ...parsed.records } };
|
|
937
|
+
}
|
|
938
|
+
applySidecar(sidecar);
|
|
939
|
+
if (Object.keys(sidecar.records).length === 0) {
|
|
940
|
+
if (existsSync(path))
|
|
941
|
+
await unlink(path);
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
const serialized = `${JSON.stringify(sidecar, null, 2)}\n`;
|
|
945
|
+
// Refuse before writing anything the reader would reject (size/schema).
|
|
946
|
+
parseStoryWorktreeCleanupDocument(serialized);
|
|
947
|
+
await atomicWrite(runtimeDirectory, STORY_WORKTREE_CLEANUP_FILE, serialized);
|
|
948
|
+
},
|
|
949
|
+
});
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
catch (error) {
|
|
953
|
+
const busy = error instanceof Error && (error.message === 'git-lifecycle-runtime-lock-active'
|
|
954
|
+
|| (error.code === 'ENOENT' && error.message.includes('runtime.lock')));
|
|
955
|
+
if (!busy || attempt >= attempts)
|
|
956
|
+
throw error;
|
|
957
|
+
await sleep(delayMs * Math.min(attempt, 8) + Math.floor(Math.random() * delayMs));
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
async guard(run) {
|
|
962
|
+
try {
|
|
963
|
+
return await run();
|
|
964
|
+
}
|
|
965
|
+
catch (error) {
|
|
966
|
+
if (error instanceof CleanupRefusal)
|
|
967
|
+
return { ok: false, reasonCode: error.reasonCode };
|
|
968
|
+
const message = error instanceof Error ? error.message : '';
|
|
969
|
+
if (/^git-lifecycle-[a-z0-9-]{1,80}$/.test(message))
|
|
970
|
+
return { ok: false, reasonCode: message };
|
|
971
|
+
return { ok: false, reasonCode: 'story-worktree-internal-error' };
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
async function atomicWrite(directory, name, content) {
|
|
976
|
+
const temporary = join(directory, `.${name}.${randomBytes(6).toString('hex')}.tmp`);
|
|
977
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
978
|
+
try {
|
|
979
|
+
await handle.writeFile(content, 'utf8');
|
|
980
|
+
await handle.sync();
|
|
981
|
+
}
|
|
982
|
+
finally {
|
|
983
|
+
await handle.close();
|
|
984
|
+
}
|
|
985
|
+
try {
|
|
986
|
+
await rename(temporary, join(directory, name));
|
|
987
|
+
}
|
|
988
|
+
catch (error) {
|
|
989
|
+
await rm(temporary, { force: true });
|
|
990
|
+
throw error;
|
|
991
|
+
}
|
|
992
|
+
try {
|
|
993
|
+
const dir = await open(directory, 'r');
|
|
994
|
+
try {
|
|
995
|
+
await dir.sync();
|
|
996
|
+
}
|
|
997
|
+
finally {
|
|
998
|
+
await dir.close();
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
catch (error) {
|
|
1002
|
+
if (process.platform !== 'win32')
|
|
1003
|
+
throw error;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
/** Reason codes that are informational on every runner tick (not actionable). */
|
|
1007
|
+
const INFORMATIONAL_SWEEP_CODES = new Set([R.MANUAL_PRESERVED]);
|
|
1008
|
+
/**
|
|
1009
|
+
* Best-effort sweep used by `run-yoloop` and signal handlers. A repository
|
|
1010
|
+
* without journaled story worktrees or cleanup records is never written.
|
|
1011
|
+
* Only actionable reason codes are returned.
|
|
1012
|
+
*/
|
|
1013
|
+
export async function sweepStoryWorktreeOrphans(projectRoot, options = {}) {
|
|
1014
|
+
let cleanup;
|
|
1015
|
+
try {
|
|
1016
|
+
const document = await readGitLifecycleRuntime(projectRoot);
|
|
1017
|
+
cleanup = new StoryWorktreeCleanup({ ...options, projectRoot });
|
|
1018
|
+
const hasEntries = Object.keys(document.storyWorktrees?.entries ?? {}).length > 0;
|
|
1019
|
+
if (!hasEntries && Object.keys((await cleanup.readState()).records).length === 0)
|
|
1020
|
+
return { reasonCodes: [] };
|
|
1021
|
+
}
|
|
1022
|
+
catch (error) {
|
|
1023
|
+
// A corrupt sidecar is actionable; a non-repository / missing runtime is not managed.
|
|
1024
|
+
return { reasonCodes: error instanceof CleanupRefusal ? [error.reasonCode] : [] };
|
|
1025
|
+
}
|
|
1026
|
+
const result = await cleanup.sweep({
|
|
1027
|
+
...(options.epicId ? { epicId: options.epicId } : {}), ...(options.dryRun ? { dryRun: true } : {}),
|
|
1028
|
+
});
|
|
1029
|
+
if (!result.ok)
|
|
1030
|
+
return { reasonCodes: [result.reasonCode] };
|
|
1031
|
+
return {
|
|
1032
|
+
reasonCodes: result.value.reasonCodes.filter((code) => !INFORMATIONAL_SWEEP_CODES.has(code)),
|
|
1033
|
+
value: result.value,
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Opt-in signal sweep: on SIGINT/SIGTERM run one bounded sweep, remove the
|
|
1038
|
+
* listeners and re-raise the signal so default termination still applies.
|
|
1039
|
+
*/
|
|
1040
|
+
export function installStoryWorktreeSignalSweep(projectRoot, sweep = (root) => sweepStoryWorktreeOrphans(root), raise = (signal) => {
|
|
1041
|
+
process.kill(process.pid, signal);
|
|
1042
|
+
}) {
|
|
1043
|
+
let running = false;
|
|
1044
|
+
const handler = (signal) => {
|
|
1045
|
+
if (running)
|
|
1046
|
+
return;
|
|
1047
|
+
running = true;
|
|
1048
|
+
dispose();
|
|
1049
|
+
void Promise.race([sweep(projectRoot), sleep(25_000)]).catch(() => undefined).finally(() => raise(signal));
|
|
1050
|
+
};
|
|
1051
|
+
const dispose = () => {
|
|
1052
|
+
process.removeListener('SIGINT', handler);
|
|
1053
|
+
process.removeListener('SIGTERM', handler);
|
|
1054
|
+
};
|
|
1055
|
+
process.once('SIGINT', handler);
|
|
1056
|
+
process.once('SIGTERM', handler);
|
|
1057
|
+
return dispose;
|
|
1058
|
+
}
|