@ornexus/neocortex 4.60.81 → 4.61.2
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 +75 -1
- 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 +84 -0
- package/packages/client/dist/git/git-lifecycle-store.js +314 -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/client/dist/state/project-state-snapshot.js +3 -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,843 @@
|
|
|
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.05 -- client-managed story worktree lifecycle (P225-CON-WORKTREE).
|
|
15
|
+
*
|
|
16
|
+
* create | adopt | sync | status | release for one story's temporary worktree.
|
|
17
|
+
* Ownership is proven by two independent facts before any effect: a journal
|
|
18
|
+
* entry in the private Git lifecycle runtime (lock + revision CAS) and a nonce
|
|
19
|
+
* marker inside the worktree's private Git directory. Anything else is manual
|
|
20
|
+
* and is never touched. No command uses `--force`, resolves conflicts, writes
|
|
21
|
+
* tracked state or takes the P207 writer lease of the root checkout.
|
|
22
|
+
*
|
|
23
|
+
* Public values carry opaque IDs, SHAs, repository-relative paths and reason
|
|
24
|
+
* codes only. The private absolute path is returned separately (`privatePath`)
|
|
25
|
+
* for the local caller and is never part of `value`.
|
|
26
|
+
*/
|
|
27
|
+
import { execFile } from 'node:child_process';
|
|
28
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
29
|
+
import { chmod, lstat, readFile, realpath, unlink, writeFile } from 'node:fs/promises';
|
|
30
|
+
import { homedir as osHomedir } from 'node:os';
|
|
31
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
32
|
+
import { yoloopDomainHash } from '../../../shared/dist/yoloop/canonical.js';
|
|
33
|
+
import { STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS, compactStoryWorktreeJournal, ensureStoryWorktreeJournal, isStoryWorktreeCleanupReceiptRecord, mutateGitLifecycleRuntime, readGitLifecycleRuntime, } from './git-lifecycle-store.js';
|
|
34
|
+
import { STORY_WORKTREE_ID_ENV, ensurePrivateStoryWorktreeRoot, resolveStoryWorktreePath, resolveStoryWorktreeRoot, storyWorktreeIdentity, } from './story-worktree-paths.js';
|
|
35
|
+
export const STORY_WORKTREE_MARKER_FILE = 'nx-owner';
|
|
36
|
+
/** Same domain as shared `digestStoryWorktreeReceipt` (P225-CON-RECEIPTS). */
|
|
37
|
+
export const STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN = 'neocortex.p225.story-worktree-receipt.v1';
|
|
38
|
+
/** Receipt digest computed with the packaged canonical hash (parity-tested). */
|
|
39
|
+
export function digestStoryWorktreeReceiptLocal(receipt) {
|
|
40
|
+
return yoloopDomainHash(STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN, receipt);
|
|
41
|
+
}
|
|
42
|
+
const DIRECTIVE_KEYS = Object.freeze([
|
|
43
|
+
'schemaVersion', 'kind', 'directiveId', 'epicId', 'storyId', 'releasedStepId',
|
|
44
|
+
'dependsOn', 'integratedEpicHeadSha', 'graphRevision', 'issuedAt',
|
|
45
|
+
]);
|
|
46
|
+
const DIRECTIVE_STEP = /^step-c-[0-9]+-[a-z0-9-]{1,60}$/;
|
|
47
|
+
const STORY_REF = /^P[1-9][0-9]*(?:\.[0-9]+)+$/;
|
|
48
|
+
const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
49
|
+
/** Closed `dependency-release-directive` shape (parity-tested with the shared validator). */
|
|
50
|
+
function isDependencyReleaseDirective(value) {
|
|
51
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
52
|
+
return false;
|
|
53
|
+
const directive = value;
|
|
54
|
+
const keys = Object.keys(directive);
|
|
55
|
+
if (keys.length !== DIRECTIVE_KEYS.length || !keys.every((key) => DIRECTIVE_KEYS.includes(key)))
|
|
56
|
+
return false;
|
|
57
|
+
const dependsOn = directive.dependsOn;
|
|
58
|
+
return directive.schemaVersion === 1 && directive.kind === 'dependency-release-directive'
|
|
59
|
+
&& typeof directive.directiveId === 'string' && OPAQUE_ID.test(directive.directiveId)
|
|
60
|
+
&& typeof directive.epicId === 'string' && EPIC_ID.test(directive.epicId)
|
|
61
|
+
&& typeof directive.storyId === 'string' && STORY_REF.test(directive.storyId)
|
|
62
|
+
&& typeof directive.releasedStepId === 'string' && DIRECTIVE_STEP.test(directive.releasedStepId)
|
|
63
|
+
&& Array.isArray(dependsOn) && dependsOn.length > 0 && new Set(dependsOn).size === dependsOn.length
|
|
64
|
+
&& dependsOn.every((item) => typeof item === 'string' && STORY_REF.test(item))
|
|
65
|
+
&& typeof directive.integratedEpicHeadSha === 'string' && FULL_SHA.test(directive.integratedEpicHeadSha)
|
|
66
|
+
&& typeof directive.graphRevision === 'string' && SHA256.test(directive.graphRevision)
|
|
67
|
+
&& typeof directive.issuedAt === 'string' && ISO_UTC.test(directive.issuedAt) && Number.isFinite(Date.parse(directive.issuedAt));
|
|
68
|
+
}
|
|
69
|
+
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
|
|
70
|
+
const GIT_TIMEOUT_MS = 30_000;
|
|
71
|
+
const MAX_CONFLICT_PATHS = 200;
|
|
72
|
+
const FULL_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
73
|
+
const SHA256 = /^[a-f0-9]{64}$/;
|
|
74
|
+
const LEASE_ID = /^swt-[a-f0-9]{24}$/;
|
|
75
|
+
const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;
|
|
76
|
+
const EPIC_ID = /^P[1-9][0-9]*$/;
|
|
77
|
+
/** Branches that adopt never registers: release could otherwise delete them. */
|
|
78
|
+
const PROTECTED_BRANCH = /^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/;
|
|
79
|
+
class StoryWorktreeRefusal extends Error {
|
|
80
|
+
reasonCode;
|
|
81
|
+
constructor(reasonCode) {
|
|
82
|
+
super(reasonCode);
|
|
83
|
+
this.reasonCode = reasonCode;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function refuse(reasonCode) {
|
|
87
|
+
throw new StoryWorktreeRefusal(reasonCode);
|
|
88
|
+
}
|
|
89
|
+
function sanitizedGitEnv() {
|
|
90
|
+
const env = { ...process.env };
|
|
91
|
+
for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY'])
|
|
92
|
+
delete env[key];
|
|
93
|
+
env.GIT_TERMINAL_PROMPT = '0';
|
|
94
|
+
return env;
|
|
95
|
+
}
|
|
96
|
+
/** Bounded Git execution shared with the P225.06 cleanup module (exit code + stdout only). */
|
|
97
|
+
export function runStoryWorktreeGit(cwd, args) {
|
|
98
|
+
return git(cwd, args);
|
|
99
|
+
}
|
|
100
|
+
function git(cwd, args) {
|
|
101
|
+
return new Promise((resolvePromise) => {
|
|
102
|
+
execFile('git', [...args], {
|
|
103
|
+
cwd,
|
|
104
|
+
encoding: 'utf8',
|
|
105
|
+
env: sanitizedGitEnv(),
|
|
106
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
107
|
+
timeout: GIT_TIMEOUT_MS,
|
|
108
|
+
windowsHide: true,
|
|
109
|
+
}, (error, stdout) => resolvePromise({ ok: !error, stdout: String(stdout ?? '') }));
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async function gitOk(cwd, args) {
|
|
113
|
+
return (await git(cwd, args)).ok;
|
|
114
|
+
}
|
|
115
|
+
async function gitValue(cwd, args, reasonCode) {
|
|
116
|
+
const outcome = await git(cwd, args);
|
|
117
|
+
if (!outcome.ok)
|
|
118
|
+
refuse(reasonCode);
|
|
119
|
+
return outcome.stdout.trim();
|
|
120
|
+
}
|
|
121
|
+
function sha256(value) {
|
|
122
|
+
return createHash('sha256').update(value).digest('hex');
|
|
123
|
+
}
|
|
124
|
+
async function pathExists(path) {
|
|
125
|
+
try {
|
|
126
|
+
await lstat(path);
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function sleep(ms) {
|
|
134
|
+
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
135
|
+
}
|
|
136
|
+
export function parseWorktreeList(output) {
|
|
137
|
+
const result = [];
|
|
138
|
+
for (const block of output.split('\0\0')) {
|
|
139
|
+
const fields = block.split('\0').filter(Boolean);
|
|
140
|
+
const path = fields.find((field) => field.startsWith('worktree '))?.slice('worktree '.length);
|
|
141
|
+
if (!path)
|
|
142
|
+
continue;
|
|
143
|
+
const head = fields.find((field) => field.startsWith('HEAD '))?.slice('HEAD '.length);
|
|
144
|
+
const branchRef = fields.find((field) => field.startsWith('branch '))?.slice('branch '.length);
|
|
145
|
+
result.push({
|
|
146
|
+
path,
|
|
147
|
+
...(head ? { head } : {}),
|
|
148
|
+
...(branchRef?.startsWith('refs/heads/') ? { branch: branchRef.slice('refs/heads/'.length) } : {}),
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
function safeConflictPath(value) {
|
|
154
|
+
return value.length > 0 && value.length <= 512 && !isAbsolute(value) && !/^[A-Za-z]:/.test(value)
|
|
155
|
+
&& !value.includes('\\') && !value.split('/').some((segment) => segment === '..' || segment === '');
|
|
156
|
+
}
|
|
157
|
+
export class StoryWorktreeManager {
|
|
158
|
+
options;
|
|
159
|
+
projectRoot;
|
|
160
|
+
now;
|
|
161
|
+
randomNonce;
|
|
162
|
+
platform;
|
|
163
|
+
constructor(options) {
|
|
164
|
+
this.options = options;
|
|
165
|
+
this.projectRoot = resolve(options.projectRoot);
|
|
166
|
+
this.now = options.now ?? (() => new Date());
|
|
167
|
+
this.randomNonce = options.randomNonce ?? (() => randomBytes(32).toString('hex'));
|
|
168
|
+
this.platform = options.platform ?? process.platform;
|
|
169
|
+
}
|
|
170
|
+
async create(input) {
|
|
171
|
+
return this.guard(async () => {
|
|
172
|
+
const identity = this.identity(input);
|
|
173
|
+
const facts = await this.repository();
|
|
174
|
+
await this.assertAuthorizedBase(facts, identity.executionBranch, input.baseSha, input.graphRevision);
|
|
175
|
+
const rootResult = resolveStoryWorktreeRoot({
|
|
176
|
+
platform: this.platform,
|
|
177
|
+
env: this.options.env ?? process.env,
|
|
178
|
+
homedir: this.options.homedir ?? osHomedir(),
|
|
179
|
+
...(this.options.worktreeRoot ? { override: this.options.worktreeRoot } : {}),
|
|
180
|
+
});
|
|
181
|
+
if (!rootResult.ok)
|
|
182
|
+
refuse(rootResult.reasonCode);
|
|
183
|
+
const pathResult = resolveStoryWorktreePath({
|
|
184
|
+
root: rootResult.value, hash8: identity.hash8, repositoryRoot: facts.mainRoot, platform: this.platform,
|
|
185
|
+
});
|
|
186
|
+
if (!pathResult.ok)
|
|
187
|
+
refuse(pathResult.reasonCode);
|
|
188
|
+
const ensured = await ensurePrivateStoryWorktreeRoot(rootResult.value, this.platform);
|
|
189
|
+
if (!ensured.ok)
|
|
190
|
+
refuse(ensured.reasonCode);
|
|
191
|
+
// Re-check length and repository containment on the canonical root: a
|
|
192
|
+
// symlinked ancestor (or a win32 short-name expansion) must not move the
|
|
193
|
+
// worktree inside the repository or past the length limit.
|
|
194
|
+
const canonicalPath = resolveStoryWorktreePath({
|
|
195
|
+
root: await realpath(rootResult.value), hash8: identity.hash8, repositoryRoot: facts.mainRoot, platform: this.platform,
|
|
196
|
+
});
|
|
197
|
+
if (!canonicalPath.ok)
|
|
198
|
+
refuse(canonicalPath.reasonCode);
|
|
199
|
+
const worktreePath = canonicalPath.value;
|
|
200
|
+
const existing = (await this.readDocument()).storyWorktrees?.entries[identity.leaseId];
|
|
201
|
+
if (existing) {
|
|
202
|
+
if (existing.state === 'active' && existing.baseSha === input.baseSha
|
|
203
|
+
&& existing.graphRevision === input.graphRevision && await this.ownershipProven(existing, facts)) {
|
|
204
|
+
await this.assertNoCleanupInProgress(facts, existing.leaseId);
|
|
205
|
+
return { ok: true, value: this.leaseValue(existing, true), privatePath: existing.worktreePath };
|
|
206
|
+
}
|
|
207
|
+
if (!await this.reclaimStaleReservation(existing, facts))
|
|
208
|
+
refuse('story-worktree-entry-conflict');
|
|
209
|
+
}
|
|
210
|
+
if (await pathExists(worktreePath))
|
|
211
|
+
refuse('story-worktree-path-occupied');
|
|
212
|
+
if (await gitOk(facts.mainRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${identity.temporaryBranch}`])) {
|
|
213
|
+
refuse('story-worktree-branch-exists');
|
|
214
|
+
}
|
|
215
|
+
const nonce = this.randomNonce();
|
|
216
|
+
const acquired = this.now();
|
|
217
|
+
const entry = {
|
|
218
|
+
schemaVersion: 1,
|
|
219
|
+
leaseId: identity.leaseId,
|
|
220
|
+
epicId: identity.epicId,
|
|
221
|
+
storyId: identity.storyId,
|
|
222
|
+
dispatchDigest: sha256(identity.dispatchId),
|
|
223
|
+
hash8: identity.hash8,
|
|
224
|
+
executionBranch: identity.executionBranch,
|
|
225
|
+
temporaryBranch: identity.temporaryBranch,
|
|
226
|
+
worktreeRef: identity.worktreeRef,
|
|
227
|
+
worktreePath,
|
|
228
|
+
workspaceMechanism: 'client_managed_worktree',
|
|
229
|
+
ownerId: this.ownerId(input.ownerId, nonce),
|
|
230
|
+
nonceDigest: sha256(nonce),
|
|
231
|
+
baseSha: input.baseSha,
|
|
232
|
+
graphRevision: input.graphRevision,
|
|
233
|
+
state: 'creating',
|
|
234
|
+
acquiredAt: acquired.toISOString(),
|
|
235
|
+
expiresAt: new Date(acquired.getTime() + (this.options.ttlMs ?? DEFAULT_TTL_MS)).toISOString(),
|
|
236
|
+
};
|
|
237
|
+
await this.mutate((document) => {
|
|
238
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
239
|
+
if (journal.entries[entry.leaseId]
|
|
240
|
+
|| Object.values(journal.entries).some((item) => item.worktreePath === worktreePath)) {
|
|
241
|
+
refuse('story-worktree-entry-conflict');
|
|
242
|
+
}
|
|
243
|
+
journal.entries[entry.leaseId] = entry;
|
|
244
|
+
});
|
|
245
|
+
let added = false;
|
|
246
|
+
try {
|
|
247
|
+
if (!await gitOk(facts.mainRoot, ['worktree', 'add', '-b', identity.temporaryBranch, worktreePath, input.baseSha])) {
|
|
248
|
+
refuse('story-worktree-add-failed');
|
|
249
|
+
}
|
|
250
|
+
added = true;
|
|
251
|
+
if (this.platform !== 'win32')
|
|
252
|
+
await chmod(worktreePath, 0o700);
|
|
253
|
+
else
|
|
254
|
+
await this.enableWindowsLongPaths(facts, worktreePath);
|
|
255
|
+
const gitDir = await this.worktreeGitDir(worktreePath, facts);
|
|
256
|
+
await writeFile(join(gitDir, STORY_WORKTREE_MARKER_FILE), `${JSON.stringify({ schemaVersion: 1, leaseId: entry.leaseId, nonce })}\n`, { flag: 'wx', mode: 0o600 });
|
|
257
|
+
const active = { ...entry, state: 'active' };
|
|
258
|
+
await this.mutate((document) => {
|
|
259
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
260
|
+
const current = journal.entries[entry.leaseId];
|
|
261
|
+
if (!current || current.state !== 'creating' || current.nonceDigest !== entry.nonceDigest) {
|
|
262
|
+
refuse('story-worktree-entry-conflict');
|
|
263
|
+
}
|
|
264
|
+
journal.entries[entry.leaseId] = active;
|
|
265
|
+
});
|
|
266
|
+
return { ok: true, value: this.leaseValue(active, false), privatePath: worktreePath };
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
await this.rollbackCreate(facts, entry, added);
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
async adopt(input) {
|
|
275
|
+
return this.guard(async () => {
|
|
276
|
+
const identity = this.identity(input);
|
|
277
|
+
const facts = await this.repository();
|
|
278
|
+
await this.assertAuthorizedBase(facts, identity.executionBranch, input.baseSha, input.graphRevision);
|
|
279
|
+
if (typeof input.worktreePath !== 'string' || !isAbsolute(input.worktreePath))
|
|
280
|
+
refuse('story-worktree-adopt-path-invalid');
|
|
281
|
+
let canonical;
|
|
282
|
+
try {
|
|
283
|
+
canonical = await realpath(input.worktreePath);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
refuse('story-worktree-adopt-unregistered');
|
|
287
|
+
}
|
|
288
|
+
const list = await this.listWorktrees(facts);
|
|
289
|
+
const index = list.findIndex((item) => this.samePath(item.path, canonical));
|
|
290
|
+
if (index === 0)
|
|
291
|
+
refuse('story-worktree-adopt-main-refused');
|
|
292
|
+
if (index < 0)
|
|
293
|
+
refuse('story-worktree-adopt-unregistered');
|
|
294
|
+
const listed = list[index];
|
|
295
|
+
if (!listed.branch)
|
|
296
|
+
refuse('story-worktree-adopt-detached');
|
|
297
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(listed.branch) || listed.branch.includes('..')) {
|
|
298
|
+
refuse('story-worktree-adopt-branch-invalid');
|
|
299
|
+
}
|
|
300
|
+
if (PROTECTED_BRANCH.test(listed.branch) || listed.branch === list[0]?.branch
|
|
301
|
+
|| await gitOk(facts.mainRoot, ['config', '--get', `branch.${listed.branch}.remote`])) {
|
|
302
|
+
refuse('story-worktree-adopt-branch-protected');
|
|
303
|
+
}
|
|
304
|
+
const document = await this.readDocument();
|
|
305
|
+
const entries = document.storyWorktrees?.entries ?? {};
|
|
306
|
+
const existing = entries[identity.leaseId];
|
|
307
|
+
if (existing) {
|
|
308
|
+
// P225.08-ADR-3: re-adoption of the same identity/path keeps working
|
|
309
|
+
// after the child committed, as long as HEAD still descends from base.
|
|
310
|
+
if (this.samePath(existing.worktreePath, canonical) && existing.state === 'active' && await this.ownershipProven(existing, facts)) {
|
|
311
|
+
if (!await gitOk(canonical, ['merge-base', '--is-ancestor', input.baseSha, 'HEAD']))
|
|
312
|
+
refuse('story-worktree-base-divergent');
|
|
313
|
+
await this.assertNoCleanupInProgress(facts, existing.leaseId);
|
|
314
|
+
return { ok: true, value: this.leaseValue(existing, true), privatePath: existing.worktreePath };
|
|
315
|
+
}
|
|
316
|
+
refuse('story-worktree-entry-conflict');
|
|
317
|
+
}
|
|
318
|
+
if (Object.values(entries).some((item) => this.samePath(item.worktreePath, canonical)))
|
|
319
|
+
refuse('story-worktree-entry-conflict');
|
|
320
|
+
// P225.08-ADR-1/2: a new adoption needs the exact authorized base and a
|
|
321
|
+
// clean checkout; both are verified before the marker or journal write.
|
|
322
|
+
const head = await gitValue(canonical, ['rev-parse', 'HEAD'], 'story-worktree-git-failed');
|
|
323
|
+
if (head !== input.baseSha)
|
|
324
|
+
refuse('native-worktree-base-mismatch');
|
|
325
|
+
const status = await git(canonical, ['status', '--porcelain=v1', '--untracked-files=all', '-z']);
|
|
326
|
+
if (!status.ok)
|
|
327
|
+
refuse('story-worktree-git-failed');
|
|
328
|
+
if (!await this.clean(canonical))
|
|
329
|
+
refuse('native-worktree-dirty');
|
|
330
|
+
const gitDir = await this.worktreeGitDir(canonical, facts);
|
|
331
|
+
const markerPath = join(gitDir, STORY_WORKTREE_MARKER_FILE);
|
|
332
|
+
if (await pathExists(markerPath)) {
|
|
333
|
+
// Only an orphan marker of this same identity (crash before the
|
|
334
|
+
// journal write, no entry) may be replaced; anything else is foreign.
|
|
335
|
+
if (await this.markerLeaseId(markerPath) !== identity.leaseId)
|
|
336
|
+
refuse('story-worktree-marker-exists');
|
|
337
|
+
await unlink(markerPath);
|
|
338
|
+
}
|
|
339
|
+
const nonce = this.randomNonce();
|
|
340
|
+
const acquired = this.now();
|
|
341
|
+
const entry = {
|
|
342
|
+
schemaVersion: 1,
|
|
343
|
+
leaseId: identity.leaseId,
|
|
344
|
+
epicId: identity.epicId,
|
|
345
|
+
storyId: identity.storyId,
|
|
346
|
+
dispatchDigest: sha256(identity.dispatchId),
|
|
347
|
+
hash8: identity.hash8,
|
|
348
|
+
executionBranch: identity.executionBranch,
|
|
349
|
+
temporaryBranch: listed.branch,
|
|
350
|
+
worktreeRef: identity.worktreeRef,
|
|
351
|
+
worktreePath: canonical,
|
|
352
|
+
workspaceMechanism: 'native_subagent_worktree',
|
|
353
|
+
ownerId: this.ownerId(input.ownerId, nonce),
|
|
354
|
+
nonceDigest: sha256(nonce),
|
|
355
|
+
baseSha: input.baseSha,
|
|
356
|
+
graphRevision: input.graphRevision,
|
|
357
|
+
state: 'active',
|
|
358
|
+
acquiredAt: acquired.toISOString(),
|
|
359
|
+
expiresAt: new Date(acquired.getTime() + (this.options.ttlMs ?? DEFAULT_TTL_MS)).toISOString(),
|
|
360
|
+
};
|
|
361
|
+
await writeFile(markerPath, `${JSON.stringify({ schemaVersion: 1, leaseId: entry.leaseId, nonce })}\n`, { flag: 'wx', mode: 0o600 });
|
|
362
|
+
try {
|
|
363
|
+
await this.mutate((doc) => {
|
|
364
|
+
const journal = ensureStoryWorktreeJournal(doc);
|
|
365
|
+
if (journal.entries[entry.leaseId]
|
|
366
|
+
|| Object.values(journal.entries).some((item) => this.samePath(item.worktreePath, canonical))) {
|
|
367
|
+
refuse('story-worktree-entry-conflict');
|
|
368
|
+
}
|
|
369
|
+
journal.entries[entry.leaseId] = entry;
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
catch (error) {
|
|
373
|
+
await this.removeOwnMarker(markerPath, nonce);
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
return { ok: true, value: this.leaseValue(entry, false), privatePath: canonical };
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
async sync(input) {
|
|
380
|
+
return this.guard(async () => {
|
|
381
|
+
const facts = await this.repository();
|
|
382
|
+
const entry = await this.ownedEntry(input.leaseId, facts);
|
|
383
|
+
let integratedSha = input.integratedSha;
|
|
384
|
+
if (input.directive !== undefined) {
|
|
385
|
+
const directive = input.directive;
|
|
386
|
+
if (!isDependencyReleaseDirective(input.directive)
|
|
387
|
+
|| directive.epicId !== entry.epicId || directive.storyId !== entry.storyId
|
|
388
|
+
|| (integratedSha !== undefined && integratedSha !== directive.integratedEpicHeadSha)) {
|
|
389
|
+
refuse('story-worktree-directive-invalid');
|
|
390
|
+
}
|
|
391
|
+
integratedSha = String(directive.integratedEpicHeadSha);
|
|
392
|
+
}
|
|
393
|
+
if (typeof integratedSha !== 'string' || !FULL_SHA.test(integratedSha))
|
|
394
|
+
refuse('story-worktree-sync-sha-invalid');
|
|
395
|
+
if (!await this.clean(entry.worktreePath))
|
|
396
|
+
refuse('story-worktree-dirty');
|
|
397
|
+
const epicHead = await this.epicHead(facts, entry.executionBranch);
|
|
398
|
+
if (!await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', integratedSha, epicHead])) {
|
|
399
|
+
refuse('story-worktree-sync-sha-unintegrated');
|
|
400
|
+
}
|
|
401
|
+
let outcome = 'already-synced';
|
|
402
|
+
if (!await gitOk(entry.worktreePath, ['merge-base', '--is-ancestor', integratedSha, 'HEAD'])) {
|
|
403
|
+
const merged = await git(entry.worktreePath, ['merge', '--no-edit', integratedSha]);
|
|
404
|
+
if (!merged.ok) {
|
|
405
|
+
const unmerged = await git(entry.worktreePath, ['diff', '--name-only', '--diff-filter=U', '-z']);
|
|
406
|
+
const conflictPaths = unmerged.stdout.split('\0').filter(safeConflictPath).sort().slice(0, MAX_CONFLICT_PATHS);
|
|
407
|
+
if (conflictPaths.length === 0)
|
|
408
|
+
refuse('story-worktree-sync-failed');
|
|
409
|
+
return { ok: false, reasonCode: 'story-worktree-sync-conflict', conflictPaths };
|
|
410
|
+
}
|
|
411
|
+
outcome = 'synced';
|
|
412
|
+
}
|
|
413
|
+
const headSha = await gitValue(entry.worktreePath, ['rev-parse', 'HEAD'], 'story-worktree-git-failed');
|
|
414
|
+
await this.mutate((document) => {
|
|
415
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
416
|
+
const current = journal.entries[entry.leaseId];
|
|
417
|
+
if (!current || current.nonceDigest !== entry.nonceDigest)
|
|
418
|
+
refuse('story-worktree-entry-conflict');
|
|
419
|
+
journal.entries[entry.leaseId] = { ...current, syncedSha: integratedSha };
|
|
420
|
+
});
|
|
421
|
+
return { ok: true, value: { leaseId: entry.leaseId, outcome, integratedSha, headSha } };
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
async status(input) {
|
|
425
|
+
return this.guard(async () => {
|
|
426
|
+
if ((input.leaseId === undefined) === (input.epicId === undefined))
|
|
427
|
+
refuse('story-worktree-status-selector-invalid');
|
|
428
|
+
if (input.leaseId !== undefined && !LEASE_ID.test(input.leaseId))
|
|
429
|
+
refuse('story-worktree-lease-invalid');
|
|
430
|
+
if (input.epicId !== undefined && !EPIC_ID.test(input.epicId))
|
|
431
|
+
refuse('story-worktree-identity-invalid');
|
|
432
|
+
const facts = await this.repository();
|
|
433
|
+
const entries = Object.values((await this.readDocument()).storyWorktrees?.entries ?? {})
|
|
434
|
+
.filter((entry) => (input.leaseId ? entry.leaseId === input.leaseId : entry.epicId === input.epicId))
|
|
435
|
+
.sort((left, right) => left.leaseId.localeCompare(right.leaseId));
|
|
436
|
+
if (input.leaseId && entries.length === 0)
|
|
437
|
+
refuse('story-worktree-lease-unknown');
|
|
438
|
+
const projected = [];
|
|
439
|
+
for (const entry of entries)
|
|
440
|
+
projected.push(await this.project(entry, facts));
|
|
441
|
+
return { ok: true, value: { entries: projected } };
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
async release(input) {
|
|
445
|
+
return this.guard(async () => {
|
|
446
|
+
const facts = await this.repository();
|
|
447
|
+
const entry = await this.ownedEntry(input.leaseId, facts);
|
|
448
|
+
if (!await this.clean(entry.worktreePath))
|
|
449
|
+
refuse('story-worktree-dirty');
|
|
450
|
+
const head = await gitValue(entry.worktreePath, ['rev-parse', 'HEAD'], 'story-worktree-git-failed');
|
|
451
|
+
const epicHead = await this.epicHead(facts, entry.executionBranch);
|
|
452
|
+
if (!await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', head, epicHead]))
|
|
453
|
+
refuse('story-worktree-not-integrated');
|
|
454
|
+
// `git worktree remove` without --force refuses modified/untracked
|
|
455
|
+
// trees; ignored files (build output, local env files) are disposable
|
|
456
|
+
// by contract and are removed with the worktree (spec ADR-7).
|
|
457
|
+
if (!await gitOk(facts.mainRoot, ['worktree', 'remove', entry.worktreePath]))
|
|
458
|
+
refuse('story-worktree-remove-failed');
|
|
459
|
+
await git(facts.mainRoot, ['worktree', 'prune']);
|
|
460
|
+
let preservedReasonCode;
|
|
461
|
+
if (entry.workspaceMechanism === 'native_subagent_worktree') {
|
|
462
|
+
// The branch was created by the native harness, not by this tool.
|
|
463
|
+
preservedReasonCode = 'story-worktree-adopted-branch-preserved';
|
|
464
|
+
}
|
|
465
|
+
else if (!await gitOk(facts.mainRoot, ['update-ref', '-d', `refs/heads/${entry.temporaryBranch}`, head])) {
|
|
466
|
+
// Compare-and-swap on the verified HEAD: a commit that landed after
|
|
467
|
+
// the integration proof keeps the branch (and its reflog) intact.
|
|
468
|
+
preservedReasonCode = 'story-worktree-branch-moved';
|
|
469
|
+
}
|
|
470
|
+
const localBranchRemoved = preservedReasonCode === undefined;
|
|
471
|
+
const cleanedAt = this.now().toISOString();
|
|
472
|
+
const receipt = {
|
|
473
|
+
schemaVersion: 1,
|
|
474
|
+
kind: 'cleanup-receipt',
|
|
475
|
+
receiptId: `swc-${sha256(`${entry.leaseId}|${entry.nonceDigest}|${cleanedAt}`).slice(0, 24)}`,
|
|
476
|
+
epicId: entry.epicId,
|
|
477
|
+
storyId: entry.storyId,
|
|
478
|
+
leaseId: entry.leaseId,
|
|
479
|
+
trigger: 'success',
|
|
480
|
+
worktreeRemoved: true,
|
|
481
|
+
localBranchRemoved,
|
|
482
|
+
remoteBranchRemoved: false,
|
|
483
|
+
...(preservedReasonCode ? { preservedReasonCode } : {}),
|
|
484
|
+
cleanedAt,
|
|
485
|
+
};
|
|
486
|
+
if (!isStoryWorktreeCleanupReceiptRecord(receipt))
|
|
487
|
+
refuse('story-worktree-receipt-invalid');
|
|
488
|
+
await this.mutate((document) => {
|
|
489
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
490
|
+
const current = journal.entries[entry.leaseId];
|
|
491
|
+
if (current && current.nonceDigest === entry.nonceDigest)
|
|
492
|
+
delete journal.entries[entry.leaseId];
|
|
493
|
+
journal.cleanupReceipts.push({ ...receipt });
|
|
494
|
+
while (journal.cleanupReceipts.length > STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS)
|
|
495
|
+
journal.cleanupReceipts.shift();
|
|
496
|
+
});
|
|
497
|
+
return { ok: true, value: { leaseId: entry.leaseId, receipt, receiptDigest: digestStoryWorktreeReceiptLocal(receipt) } };
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
/** P225.06: private ownership/integration probe for the cleanup module. */
|
|
501
|
+
async probe(leaseId) {
|
|
502
|
+
return this.guard(async () => {
|
|
503
|
+
if (typeof leaseId !== 'string' || !LEASE_ID.test(leaseId))
|
|
504
|
+
refuse('story-worktree-lease-invalid');
|
|
505
|
+
const facts = await this.repository();
|
|
506
|
+
const entry = (await this.readDocument()).storyWorktrees?.entries[leaseId];
|
|
507
|
+
if (!entry)
|
|
508
|
+
refuse('story-worktree-lease-unknown');
|
|
509
|
+
const list = await this.listWorktrees(facts);
|
|
510
|
+
const registered = list.some((item, index) => index > 0 && this.samePath(item.path, entry.worktreePath));
|
|
511
|
+
const branchCheckedOut = list.some((item) => item.branch === entry.temporaryBranch);
|
|
512
|
+
const branch = await git(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${entry.temporaryBranch}^{commit}`]);
|
|
513
|
+
const branchSha = branch.ok && FULL_SHA.test(branch.stdout.trim()) ? branch.stdout.trim() : undefined;
|
|
514
|
+
const epic = await git(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${entry.executionBranch}^{commit}`]);
|
|
515
|
+
const epicHead = epic.ok && FULL_SHA.test(epic.stdout.trim()) ? epic.stdout.trim() : undefined;
|
|
516
|
+
const pathPresent = await pathExists(entry.worktreePath);
|
|
517
|
+
const proven = entry.state === 'active' && pathPresent && await this.ownershipProven(entry, facts);
|
|
518
|
+
let headSha;
|
|
519
|
+
let clean;
|
|
520
|
+
if (proven) {
|
|
521
|
+
const head = await git(entry.worktreePath, ['rev-parse', 'HEAD']);
|
|
522
|
+
if (head.ok && FULL_SHA.test(head.stdout.trim()))
|
|
523
|
+
headSha = head.stdout.trim();
|
|
524
|
+
clean = await this.clean(entry.worktreePath);
|
|
525
|
+
}
|
|
526
|
+
const tip = headSha ?? (pathPresent ? undefined : branchSha);
|
|
527
|
+
const integrated = tip && epicHead ? await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', tip, epicHead]) : undefined;
|
|
528
|
+
return {
|
|
529
|
+
ok: true,
|
|
530
|
+
value: {
|
|
531
|
+
entry, facts, ownership: proven ? 'proven' : 'unproven', pathExists: pathPresent, registered,
|
|
532
|
+
...(branchSha ? { branchSha } : {}), branchCheckedOut,
|
|
533
|
+
...(headSha ? { headSha } : {}), ...(clean !== undefined ? { clean } : {}),
|
|
534
|
+
...(epicHead ? { epicHead } : {}), ...(integrated !== undefined ? { integrated } : {}),
|
|
535
|
+
},
|
|
536
|
+
};
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
/** Registered secondary worktrees of this repository (canonical private paths). */
|
|
540
|
+
async registeredWorktrees() {
|
|
541
|
+
return this.guard(async () => {
|
|
542
|
+
const facts = await this.repository();
|
|
543
|
+
return { ok: true, value: { facts, worktrees: (await this.listWorktrees(facts)).slice(1) } };
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
/** Canonical path comparison for the current platform. */
|
|
547
|
+
sameWorktreePath(left, right) {
|
|
548
|
+
return this.samePath(left, right);
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* P225.06 failure/abandon hook: bundle unintegrated work, then remove the
|
|
552
|
+
* worktree (or leave it `remove-pending`). Delegates to the cleanup module.
|
|
553
|
+
*/
|
|
554
|
+
async fail(input) {
|
|
555
|
+
const { StoryWorktreeCleanup } = await import('./story-worktree-cleanup.js');
|
|
556
|
+
return new StoryWorktreeCleanup({ manager: this, projectRoot: this.projectRoot, now: this.now })
|
|
557
|
+
.cleanup({ leaseId: input.leaseId, trigger: input.trigger ?? 'failure', ...(input.dryRun ? { dryRun: true } : {}) });
|
|
558
|
+
}
|
|
559
|
+
async abandon(input) {
|
|
560
|
+
return this.fail({ ...input, trigger: 'abandon' });
|
|
561
|
+
}
|
|
562
|
+
// ---------------------------------------------------------------- helpers
|
|
563
|
+
async guard(run) {
|
|
564
|
+
try {
|
|
565
|
+
return await run();
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
if (error instanceof StoryWorktreeRefusal)
|
|
569
|
+
return { ok: false, reasonCode: error.reasonCode };
|
|
570
|
+
const message = error instanceof Error ? error.message : '';
|
|
571
|
+
// Lifecycle-store errors are already stable public reason codes.
|
|
572
|
+
if (/^git-lifecycle-[a-z0-9-]{1,80}$/.test(message))
|
|
573
|
+
return { ok: false, reasonCode: message };
|
|
574
|
+
return { ok: false, reasonCode: 'story-worktree-internal-error' };
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
identity(input) {
|
|
578
|
+
const result = storyWorktreeIdentity(input);
|
|
579
|
+
if (!result.ok)
|
|
580
|
+
refuse(result.reasonCode);
|
|
581
|
+
if (input.ownerId !== undefined && !OPAQUE_ID.test(input.ownerId))
|
|
582
|
+
refuse('story-worktree-owner-invalid');
|
|
583
|
+
return result.value;
|
|
584
|
+
}
|
|
585
|
+
/** P225.06: a worktree under cleanup (or with an untrusted sidecar) is never handed out again. */
|
|
586
|
+
async assertNoCleanupInProgress(facts, leaseId) {
|
|
587
|
+
const { storyWorktreeCleanupInProgress } = await import('./story-worktree-cleanup.js');
|
|
588
|
+
if (await storyWorktreeCleanupInProgress(facts.commonDir, leaseId, this.now().getTime())) {
|
|
589
|
+
refuse('story-worktree-cleanup-in-progress');
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
ownerId(explicit, nonce) {
|
|
593
|
+
return explicit ?? `owner-${sha256(`owner|${nonce}`).slice(0, 16)}`;
|
|
594
|
+
}
|
|
595
|
+
async repository() {
|
|
596
|
+
let start;
|
|
597
|
+
try {
|
|
598
|
+
start = await realpath(this.projectRoot);
|
|
599
|
+
}
|
|
600
|
+
catch {
|
|
601
|
+
refuse('story-worktree-project-root-invalid');
|
|
602
|
+
}
|
|
603
|
+
const commonRaw = await gitValue(start, ['rev-parse', '--path-format=absolute', '--git-common-dir'], 'story-worktree-project-root-invalid');
|
|
604
|
+
const commonDir = await realpath(commonRaw);
|
|
605
|
+
const list = parseWorktreeList(await gitValue(start, ['worktree', 'list', '--porcelain', '-z'], 'story-worktree-git-failed'));
|
|
606
|
+
const main = list[0];
|
|
607
|
+
if (!main)
|
|
608
|
+
refuse('story-worktree-project-root-invalid');
|
|
609
|
+
return { mainRoot: await realpath(main.path), commonDir };
|
|
610
|
+
}
|
|
611
|
+
async assertAuthorizedBase(facts, executionBranch, baseSha, graphRevision) {
|
|
612
|
+
if (typeof graphRevision !== 'string' || !SHA256.test(graphRevision))
|
|
613
|
+
refuse('story-worktree-graph-revision-invalid');
|
|
614
|
+
if (typeof baseSha !== 'string' || !FULL_SHA.test(baseSha)
|
|
615
|
+
|| !await gitOk(facts.mainRoot, ['cat-file', '-e', `${baseSha}^{commit}`])) {
|
|
616
|
+
refuse('story-worktree-base-invalid');
|
|
617
|
+
}
|
|
618
|
+
const epicHead = await this.epicHead(facts, executionBranch);
|
|
619
|
+
if (!await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', baseSha, epicHead]))
|
|
620
|
+
refuse('story-worktree-base-divergent');
|
|
621
|
+
}
|
|
622
|
+
async epicHead(facts, executionBranch) {
|
|
623
|
+
return gitValue(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${executionBranch}^{commit}`], 'story-worktree-epic-branch-missing');
|
|
624
|
+
}
|
|
625
|
+
async worktreeGitDir(worktreePath, facts) {
|
|
626
|
+
const gitDir = await realpath(await gitValue(worktreePath, ['rev-parse', '--absolute-git-dir'], 'story-worktree-git-failed'));
|
|
627
|
+
const common = await realpath(await gitValue(worktreePath, ['rev-parse', '--path-format=absolute', '--git-common-dir'], 'story-worktree-git-failed'));
|
|
628
|
+
const worktreesDir = join(facts.commonDir, 'worktrees');
|
|
629
|
+
if (common !== facts.commonDir || (!gitDir.startsWith(`${worktreesDir}/`) && !gitDir.startsWith(`${worktreesDir}\\`))) {
|
|
630
|
+
refuse('story-worktree-foreign-repository');
|
|
631
|
+
}
|
|
632
|
+
return gitDir;
|
|
633
|
+
}
|
|
634
|
+
async enableWindowsLongPaths(facts, worktreePath) {
|
|
635
|
+
// Concurrent creations may contend on config.lock: retry, bounded.
|
|
636
|
+
const configure = async (cwd, args) => {
|
|
637
|
+
for (let attempt = 1; attempt <= 8; attempt++) {
|
|
638
|
+
if (await gitOk(cwd, args))
|
|
639
|
+
return;
|
|
640
|
+
await sleep(25 * attempt);
|
|
641
|
+
}
|
|
642
|
+
refuse('story-worktree-config-failed');
|
|
643
|
+
};
|
|
644
|
+
const enabled = await git(facts.mainRoot, ['config', '--get', 'extensions.worktreeConfig']);
|
|
645
|
+
if (!enabled.ok || enabled.stdout.trim() !== 'true')
|
|
646
|
+
await configure(facts.mainRoot, ['config', 'extensions.worktreeConfig', 'true']);
|
|
647
|
+
await configure(worktreePath, ['config', '--worktree', 'core.longPaths', 'true']);
|
|
648
|
+
}
|
|
649
|
+
async ownershipProven(entry, facts) {
|
|
650
|
+
try {
|
|
651
|
+
if (await realpath(entry.worktreePath) !== entry.worktreePath)
|
|
652
|
+
return false;
|
|
653
|
+
const gitDir = await this.worktreeGitDir(entry.worktreePath, facts);
|
|
654
|
+
const marker = JSON.parse(await readFile(join(gitDir, STORY_WORKTREE_MARKER_FILE), 'utf8'));
|
|
655
|
+
if (marker.schemaVersion !== 1 || marker.leaseId !== entry.leaseId || typeof marker.nonce !== 'string'
|
|
656
|
+
|| sha256(marker.nonce) !== entry.nonceDigest)
|
|
657
|
+
return false;
|
|
658
|
+
const list = await this.listWorktrees(facts);
|
|
659
|
+
const index = list.findIndex((item) => this.samePath(item.path, entry.worktreePath));
|
|
660
|
+
return index > 0 && list[index].branch === entry.temporaryBranch;
|
|
661
|
+
}
|
|
662
|
+
catch {
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
async ownedEntry(leaseId, facts) {
|
|
667
|
+
if (typeof leaseId !== 'string' || !LEASE_ID.test(leaseId))
|
|
668
|
+
refuse('story-worktree-lease-invalid');
|
|
669
|
+
const entry = (await this.readDocument()).storyWorktrees?.entries[leaseId];
|
|
670
|
+
if (!entry)
|
|
671
|
+
refuse('story-worktree-lease-unknown');
|
|
672
|
+
if (entry.state !== 'active' || !await this.ownershipProven(entry, facts))
|
|
673
|
+
refuse('story-worktree-ownership-unproven');
|
|
674
|
+
return entry;
|
|
675
|
+
}
|
|
676
|
+
async clean(worktreePath) {
|
|
677
|
+
const status = await git(worktreePath, ['status', '--porcelain=v1', '--untracked-files=all', '-z']);
|
|
678
|
+
if (!status.ok || status.stdout.length > 0)
|
|
679
|
+
return false;
|
|
680
|
+
const mergeHead = await git(worktreePath, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']);
|
|
681
|
+
return !mergeHead.ok;
|
|
682
|
+
}
|
|
683
|
+
async project(entry, facts) {
|
|
684
|
+
const base = {
|
|
685
|
+
leaseId: entry.leaseId,
|
|
686
|
+
epicId: entry.epicId,
|
|
687
|
+
storyId: entry.storyId,
|
|
688
|
+
worktreeId: `nxwt-${entry.hash8}`,
|
|
689
|
+
worktreeRef: entry.worktreeRef,
|
|
690
|
+
temporaryBranch: entry.temporaryBranch,
|
|
691
|
+
workspaceMechanism: entry.workspaceMechanism,
|
|
692
|
+
state: entry.state,
|
|
693
|
+
baseSha: entry.baseSha,
|
|
694
|
+
...(entry.syncedSha ? { syncedSha: entry.syncedSha } : {}),
|
|
695
|
+
ownership: 'unproven',
|
|
696
|
+
expiresAt: entry.expiresAt,
|
|
697
|
+
};
|
|
698
|
+
if (entry.state !== 'active' || !await this.ownershipProven(entry, facts))
|
|
699
|
+
return base;
|
|
700
|
+
const head = await git(entry.worktreePath, ['rev-parse', 'HEAD']);
|
|
701
|
+
const headSha = head.stdout.trim();
|
|
702
|
+
if (!head.ok || !FULL_SHA.test(headSha))
|
|
703
|
+
return { ...base, ownership: 'proven' };
|
|
704
|
+
const epicHead = await git(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${entry.executionBranch}^{commit}`]);
|
|
705
|
+
const integrated = epicHead.ok
|
|
706
|
+
&& await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', headSha, epicHead.stdout.trim()]);
|
|
707
|
+
return { ...base, ownership: 'proven', headSha, clean: await this.clean(entry.worktreePath), integrated };
|
|
708
|
+
}
|
|
709
|
+
leaseValue(entry, reused) {
|
|
710
|
+
const lease = {
|
|
711
|
+
schemaVersion: 1,
|
|
712
|
+
kind: 'story-worktree-lease',
|
|
713
|
+
leaseId: entry.leaseId,
|
|
714
|
+
epicId: entry.epicId,
|
|
715
|
+
storyId: entry.storyId,
|
|
716
|
+
executionBranch: entry.executionBranch,
|
|
717
|
+
temporaryBranch: entry.temporaryBranch,
|
|
718
|
+
worktreeRef: entry.worktreeRef,
|
|
719
|
+
workspaceMechanism: entry.workspaceMechanism,
|
|
720
|
+
ownerId: entry.ownerId,
|
|
721
|
+
baseSha: entry.baseSha,
|
|
722
|
+
graphRevision: entry.graphRevision,
|
|
723
|
+
acquiredAt: entry.acquiredAt,
|
|
724
|
+
expiresAt: entry.expiresAt,
|
|
725
|
+
};
|
|
726
|
+
const worktreeId = `nxwt-${entry.hash8}`;
|
|
727
|
+
return {
|
|
728
|
+
lease,
|
|
729
|
+
leaseDigest: digestStoryWorktreeReceiptLocal(lease),
|
|
730
|
+
worktreeId,
|
|
731
|
+
worktreeRef: entry.worktreeRef,
|
|
732
|
+
temporaryBranch: entry.temporaryBranch,
|
|
733
|
+
baseSha: entry.baseSha,
|
|
734
|
+
reused,
|
|
735
|
+
env: { [STORY_WORKTREE_ID_ENV]: worktreeId },
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
async rollbackCreate(facts, entry, added) {
|
|
739
|
+
if (added) {
|
|
740
|
+
// The worktree was created by this call and holds no child work yet.
|
|
741
|
+
await git(facts.mainRoot, ['worktree', 'remove', entry.worktreePath]);
|
|
742
|
+
await git(facts.mainRoot, ['worktree', 'prune']);
|
|
743
|
+
}
|
|
744
|
+
// `worktree add -b` may leave the new branch behind on checkout failure.
|
|
745
|
+
// Delete it only while it is unchecked-out and still at the base (CAS).
|
|
746
|
+
const list = await this.listWorktrees(facts).catch(() => undefined);
|
|
747
|
+
if (list && !list.some((item) => item.branch === entry.temporaryBranch)) {
|
|
748
|
+
await git(facts.mainRoot, ['update-ref', '-d', `refs/heads/${entry.temporaryBranch}`, entry.baseSha]);
|
|
749
|
+
}
|
|
750
|
+
await this.mutate((document) => {
|
|
751
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
752
|
+
const current = journal.entries[entry.leaseId];
|
|
753
|
+
if (current && current.nonceDigest === entry.nonceDigest)
|
|
754
|
+
delete journal.entries[entry.leaseId];
|
|
755
|
+
compactStoryWorktreeJournal(document);
|
|
756
|
+
}).catch(() => undefined);
|
|
757
|
+
}
|
|
758
|
+
async removeOwnMarker(markerPath, nonce) {
|
|
759
|
+
try {
|
|
760
|
+
const marker = JSON.parse(await readFile(markerPath, 'utf8'));
|
|
761
|
+
if (marker.nonce === nonce)
|
|
762
|
+
await unlink(markerPath);
|
|
763
|
+
}
|
|
764
|
+
catch {
|
|
765
|
+
// Best effort: an unowned or missing marker is left untouched.
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
/** `git worktree list` with every path canonicalised for comparison. */
|
|
769
|
+
async listWorktrees(facts) {
|
|
770
|
+
const raw = parseWorktreeList(await gitValue(facts.mainRoot, ['worktree', 'list', '--porcelain', '-z'], 'story-worktree-git-failed'));
|
|
771
|
+
return Promise.all(raw.map(async (item) => {
|
|
772
|
+
const native = this.platform === 'win32' ? item.path.replace(/\//g, '\\') : item.path;
|
|
773
|
+
try {
|
|
774
|
+
return { ...item, path: await realpath(native) };
|
|
775
|
+
}
|
|
776
|
+
catch {
|
|
777
|
+
return { ...item, path: native };
|
|
778
|
+
}
|
|
779
|
+
}));
|
|
780
|
+
}
|
|
781
|
+
samePath(left, right) {
|
|
782
|
+
if (this.platform === 'win32') {
|
|
783
|
+
const fold = (value) => value.replace(/\//g, '\\').toLowerCase();
|
|
784
|
+
return fold(left) === fold(right);
|
|
785
|
+
}
|
|
786
|
+
return this.platform === 'darwin' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
787
|
+
}
|
|
788
|
+
async markerLeaseId(markerPath) {
|
|
789
|
+
try {
|
|
790
|
+
const marker = JSON.parse(await readFile(markerPath, 'utf8'));
|
|
791
|
+
return typeof marker.leaseId === 'string' ? marker.leaseId : undefined;
|
|
792
|
+
}
|
|
793
|
+
catch {
|
|
794
|
+
return undefined;
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* A `creating` reservation left by a crashed or lock-starved call is
|
|
799
|
+
* reclaimed only when it is provably empty (no path, no branch).
|
|
800
|
+
*/
|
|
801
|
+
async reclaimStaleReservation(entry, facts) {
|
|
802
|
+
if (entry.state !== 'creating')
|
|
803
|
+
return false;
|
|
804
|
+
// Resources left behind (path or branch) belong to P225.06 recovery.
|
|
805
|
+
const empty = !await pathExists(entry.worktreePath)
|
|
806
|
+
&& !await gitOk(facts.mainRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${entry.temporaryBranch}`]);
|
|
807
|
+
if (!empty)
|
|
808
|
+
return false;
|
|
809
|
+
let reclaimed = false;
|
|
810
|
+
await this.mutate((document) => {
|
|
811
|
+
const journal = ensureStoryWorktreeJournal(document);
|
|
812
|
+
const current = journal.entries[entry.leaseId];
|
|
813
|
+
if (current && current.state === 'creating' && current.nonceDigest === entry.nonceDigest) {
|
|
814
|
+
delete journal.entries[entry.leaseId];
|
|
815
|
+
reclaimed = true;
|
|
816
|
+
}
|
|
817
|
+
});
|
|
818
|
+
return reclaimed;
|
|
819
|
+
}
|
|
820
|
+
async readDocument() {
|
|
821
|
+
return readGitLifecycleRuntime(this.projectRoot);
|
|
822
|
+
}
|
|
823
|
+
/** Journal write under the lifecycle lock, retrying bounded lock contention. */
|
|
824
|
+
async mutate(apply) {
|
|
825
|
+
const attempts = this.options.lockRetry?.attempts ?? 40;
|
|
826
|
+
const delayMs = this.options.lockRetry?.delayMs ?? 25;
|
|
827
|
+
for (let attempt = 1;; attempt++) {
|
|
828
|
+
try {
|
|
829
|
+
await mutateGitLifecycleRuntime(this.projectRoot, apply);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
catch (error) {
|
|
833
|
+
// A holder may release between our EEXIST and the ownership probe
|
|
834
|
+
// (ENOENT on the lock directory): that transient is contention too.
|
|
835
|
+
const busy = error instanceof Error && (error.message === 'git-lifecycle-runtime-lock-active'
|
|
836
|
+
|| (error.code === 'ENOENT' && error.message.includes('runtime.lock')));
|
|
837
|
+
if (!busy || attempt >= attempts)
|
|
838
|
+
throw error;
|
|
839
|
+
await sleep(delayMs * Math.min(attempt, 8) + Math.floor(Math.random() * delayMs));
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
}
|