@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.
Files changed (53) hide show
  1. package/dist/release-source.json +1 -1
  2. package/install.ps1 +33 -1
  3. package/install.sh +35 -1
  4. package/package.json +2 -2
  5. package/packages/client/dist/adapters/platform-detector.d.ts +1 -1
  6. package/packages/client/dist/adapters/platform-detector.js +6 -0
  7. package/packages/client/dist/cli.js +7 -0
  8. package/packages/client/dist/commands/invoke.d.ts +15 -8
  9. package/packages/client/dist/commands/invoke.js +75 -1
  10. package/packages/client/dist/commands/story-checkpoint.d.ts +2 -1
  11. package/packages/client/dist/commands/story-checkpoint.js +34 -2
  12. package/packages/client/dist/commands/story-worktree.d.ts +46 -0
  13. package/packages/client/dist/commands/story-worktree.js +258 -0
  14. package/packages/client/dist/config.js +1 -0
  15. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +46 -0
  16. package/packages/client/dist/git/direct-yolo-checkpoint.js +137 -1
  17. package/packages/client/dist/git/git-lifecycle-store.d.ts +84 -0
  18. package/packages/client/dist/git/git-lifecycle-store.js +314 -4
  19. package/packages/client/dist/git/story-worktree-cleanup.d.ts +226 -0
  20. package/packages/client/dist/git/story-worktree-cleanup.js +1058 -0
  21. package/packages/client/dist/git/story-worktree-integration.d.ts +91 -0
  22. package/packages/client/dist/git/story-worktree-integration.js +603 -0
  23. package/packages/client/dist/git/story-worktree-manager.d.ts +205 -0
  24. package/packages/client/dist/git/story-worktree-manager.js +843 -0
  25. package/packages/client/dist/git/story-worktree-paths.d.ts +65 -0
  26. package/packages/client/dist/git/story-worktree-paths.js +150 -0
  27. package/packages/client/dist/policy/subagent-approval-policy.js +3 -1
  28. package/packages/client/dist/runner/headless/continuous-story-workspace.d.ts +49 -1
  29. package/packages/client/dist/runner/headless/continuous-story-workspace.js +175 -27
  30. package/packages/client/dist/runner/headless/run-yoloop.d.ts +39 -0
  31. package/packages/client/dist/runner/headless/run-yoloop.js +71 -0
  32. package/packages/client/dist/runner-cli.js +0 -0
  33. package/packages/client/dist/state/project-state-snapshot.js +3 -0
  34. package/packages/shared/dist/yoloop/epic-terminal-git.js +27 -3
  35. package/targets-stubs/antigravity/gemini.md +1 -1
  36. package/targets-stubs/antigravity/neocortex.md +21 -0
  37. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  38. package/targets-stubs/claude-code/README.md +17 -0
  39. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  40. package/targets-stubs/claude-code/neocortex-root.md +57 -49
  41. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  42. package/targets-stubs/claude-code/neocortex.md +28 -25
  43. package/targets-stubs/codex/AGENTS.md +31 -30
  44. package/targets-stubs/codex/neocortex.toml +10 -0
  45. package/targets-stubs/cursor/agent.md +13 -2
  46. package/targets-stubs/deepseek-harness/SKILL.md +13 -0
  47. package/targets-stubs/gemini-cli/agent.md +23 -2
  48. package/targets-stubs/grok/SKILL.md +21 -0
  49. package/targets-stubs/kimi/neocortex.md +21 -0
  50. package/targets-stubs/openclaw/SKILL.md +21 -0
  51. package/targets-stubs/opencode/neocortex-root.md +19 -15
  52. package/targets-stubs/opencode/neocortex.md +10 -0
  53. package/targets-stubs/vscode/neocortex.agent.md +13 -2
@@ -0,0 +1,603 @@
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.07 -- root-only topological integration of story worktrees.
15
+ *
16
+ * The root never merges a temporary branch. It computes the merged tree with
17
+ * `git merge-tree --write-tree` (no index/checkout/ref effect), materializes
18
+ * exactly one canonical, deterministic commit on top of the epic head and
19
+ * fast-forwards `epic/<ID>`, so the existing `StoryCommitCheckpoint` contract
20
+ * (one commit, parent = base) holds unchanged. Conflicts change nothing and are
21
+ * reported as `conflict-reopened` integration receipts; the server scheduler
22
+ * then reopens C14 for the story. Public values carry IDs, SHAs, digests,
23
+ * relative paths and reason codes only.
24
+ */
25
+ import { execFile } from 'node:child_process';
26
+ import { createHash } from 'node:crypto';
27
+ import { readFile, realpath } from 'node:fs/promises';
28
+ import { join, resolve } from 'node:path';
29
+ import { yoloopDomainHash } from '../../../shared/dist/yoloop/canonical.js';
30
+ import { DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS, directYoloCommitIdempotencyKey, finalizeDirectYoloStoryCheckpoint, resolveDirectYoloIntegrationAuthority, validateDirectYoloWriteSet, } from './direct-yolo-checkpoint.js';
31
+ import { acquireGitLifecyclePhysicalIntegrationLock, appendStoryWorktreeEvidence, applyGitLifecycleRuntimeOverlay, ensureRuntimeEpic, isStoryWorktreeIntegrationReceiptRecord, mutateGitLifecycleRuntime, publicStoryReviewArtifactFromGit, readGitLifecycleRuntime, readStoryWorktreeEvidence, releaseGitLifecyclePhysicalIntegrationLock, verifyGitLifecyclePhysicalIntegrationLock, } from './git-lifecycle-store.js';
32
+ import { StoryWorktreeManager } from './story-worktree-manager.js';
33
+ import { rootMemoryEffectDigest } from '../private-execution/root-memory-git-evidence.js';
34
+ export const STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN = 'neocortex.p225.story-worktree-receipt.v1';
35
+ export const STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS = 200;
36
+ const TIP_TRAILER = 'Neocortex-Story-Worktree-Tip';
37
+ const GIT_TIMEOUT_MS = 30_000;
38
+ const FULL_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
39
+ const LEASE_ID = /^swt-[a-f0-9]{24}$/;
40
+ const STORY_ID = /^P[1-9][0-9]*(?:\.[0-9]+)+$/;
41
+ class IntegrationRefusal extends Error {
42
+ reasonCode;
43
+ constructor(reasonCode) {
44
+ super(reasonCode);
45
+ this.reasonCode = reasonCode;
46
+ }
47
+ }
48
+ function refuse(reasonCode) {
49
+ throw new IntegrationRefusal(reasonCode);
50
+ }
51
+ function gitRun(cwd, args, env) {
52
+ return new Promise((resolvePromise) => {
53
+ execFile('git', [...args], {
54
+ cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, timeout: GIT_TIMEOUT_MS,
55
+ env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
56
+ }, (error, stdout) => {
57
+ const code = error ? (typeof error.code === 'number' ? error.code : 128) : 0;
58
+ resolvePromise({ code, stdout: String(stdout ?? '') });
59
+ });
60
+ });
61
+ }
62
+ async function gitValue(cwd, args, reasonCode, env) {
63
+ const result = await gitRun(cwd, args, env);
64
+ if (result.code !== 0)
65
+ refuse(reasonCode);
66
+ return result.stdout.trim();
67
+ }
68
+ async function gitOk(cwd, args) {
69
+ return (await gitRun(cwd, args)).code === 0;
70
+ }
71
+ function sha256(value) {
72
+ return createHash('sha256').update(value).digest('hex');
73
+ }
74
+ function safeRelativePath(value) {
75
+ return value.length > 0 && value.length <= 1024 && !value.startsWith('/') && !/^[A-Za-z]:[\\/]/.test(value)
76
+ && !value.includes('\\') && !value.includes('\0') && value.split('/').every((part) => part !== '' && part !== '.' && part !== '..');
77
+ }
78
+ function trailerValue(body, key) {
79
+ const prefix = `${key}: `;
80
+ const lines = body.split('\n').map((line) => line.trim()).filter((line) => line.startsWith(prefix));
81
+ return lines.length === 1 ? lines[0].slice(prefix.length) : undefined;
82
+ }
83
+ export function digestStoryWorktreeIntegrationReceipt(receipt) {
84
+ return yoloopDomainHash(STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN, receipt);
85
+ }
86
+ function integrationReceipts(document, epicId) {
87
+ const container = readStoryWorktreeEvidence(document, epicId);
88
+ return (container?.receipts ?? []).filter(isStoryWorktreeIntegrationReceiptRecord);
89
+ }
90
+ /** Contiguous from 1 and head-linked (the shared scheduler's chain rule). */
91
+ function assertIntegrationChain(receipts) {
92
+ const sorted = [...receipts].sort((left, right) => left.integrationIndex - right.integrationIndex);
93
+ sorted.forEach((receipt, index) => {
94
+ if (receipt.integrationIndex !== index + 1
95
+ || (index > 0 && receipt.epicHeadBeforeSha !== sorted[index - 1].epicHeadAfterSha)) {
96
+ refuse('story-worktree-integration-chain-invalid');
97
+ }
98
+ });
99
+ }
100
+ /** The next receipt must start at the head the chain left (M2: checked before any effect). */
101
+ function assertChainHead(receipts, before) {
102
+ const last = [...receipts].sort((left, right) => right.integrationIndex - left.integrationIndex)[0];
103
+ if (last && last.epicHeadAfterSha !== before)
104
+ refuse('story-worktree-integration-chain-invalid');
105
+ }
106
+ const DEPENDENCY_DONE_STATUSES = new Set(['done', 'merged', 'completed', 'released']);
107
+ /**
108
+ * Mirror the scheduler preconditions for an `integrated` receipt (M3): the
109
+ * story is bound to the run (phase-one receipt or spec-barrier membership) and
110
+ * every in-epic dependency is integrated or already terminal.
111
+ */
112
+ function assertIntegrationAdmissible(document, effectiveStories, epicId, storyId, dependencies) {
113
+ const evidence = readStoryWorktreeEvidence(document, epicId);
114
+ const receipts = evidence?.receipts ?? [];
115
+ const bound = receipts.some((item) => (item.kind === 'phase-one-receipt' && item.storyId === storyId)
116
+ || (item.kind === 'spec-barrier-receipt' && Array.isArray(item.storyIds) && item.storyIds.includes(storyId)));
117
+ if (!bound)
118
+ refuse('story-worktree-integration-unbound');
119
+ const integrated = new Set(integrationReceipts(document, epicId)
120
+ .filter((item) => item.outcome === 'integrated').map((item) => item.storyId));
121
+ for (const dependency of dependencies) {
122
+ if (!dependency.startsWith(`${epicId}.`))
123
+ continue;
124
+ const story = effectiveStories[dependency];
125
+ const terminal = Boolean(document.stories[dependency]?.checkpoint)
126
+ || (typeof story?.status === 'string' && DEPENDENCY_DONE_STATUSES.has(story.status));
127
+ if (!integrated.has(dependency) && !terminal)
128
+ refuse('story-worktree-integration-dependency-waiting');
129
+ }
130
+ }
131
+ function buildReceipt(input) {
132
+ const reasonCode = input.outcome === 'integrated' ? 'integrated' : 'integration-conflict-reopened';
133
+ const receiptId = `int-${sha256([
134
+ 'p225-integration-receipt-v1', input.epicId, input.storyId, String(input.index),
135
+ input.before, input.after, input.checkpointDigest, input.outcome,
136
+ ].join('\0')).slice(0, 32)}`;
137
+ return Object.freeze({
138
+ schemaVersion: 1, kind: 'integration-receipt', receiptId, epicId: input.epicId, storyId: input.storyId,
139
+ integrationOwner: 'root_agent', integrationIndex: input.index,
140
+ epicHeadBeforeSha: input.before, epicHeadAfterSha: input.after,
141
+ checkpointDigest: input.checkpointDigest, outcome: input.outcome, reasonCode,
142
+ integratedAt: input.integratedAt,
143
+ });
144
+ }
145
+ function checkpointDigest(checkpoint) {
146
+ return sha256([
147
+ 'p225-integration-checkpoint-v1', checkpoint.storyId, checkpoint.headSha,
148
+ String(checkpoint.idempotencyKey), String(checkpoint.bundleDigest),
149
+ ].join('\0'));
150
+ }
151
+ /**
152
+ * Append one receipt to the chain under the runtime lock. The `expectHead`
153
+ * guard binds the receipt to the observed epic head (CAS on the physical ref).
154
+ */
155
+ async function persistIntegrationReceipt(input) {
156
+ let persisted;
157
+ await mutateGitLifecycleRuntime(input.projectRoot, (document) => {
158
+ const chain = integrationReceipts(document, input.epicId);
159
+ assertIntegrationChain(chain);
160
+ const last = [...chain].sort((left, right) => right.integrationIndex - left.integrationIndex)[0];
161
+ if (last && last.epicHeadAfterSha !== input.before)
162
+ refuse('story-worktree-integration-chain-invalid');
163
+ const latestForStory = [...chain].filter((item) => item.storyId === input.storyId)
164
+ .sort((left, right) => right.integrationIndex - left.integrationIndex)[0];
165
+ if (latestForStory?.outcome === 'integrated')
166
+ refuse('story-worktree-integration-already-integrated');
167
+ persisted = buildReceipt({
168
+ epicId: input.epicId, storyId: input.storyId, index: chain.length + 1,
169
+ before: input.before, after: input.after, checkpointDigest: input.checkpointDigest,
170
+ outcome: input.outcome, integratedAt: input.integratedAt,
171
+ });
172
+ appendStoryWorktreeEvidence(document, input.epicId, { receipts: [persisted] });
173
+ }, {
174
+ preCommit: async () => {
175
+ const head = await gitValue(input.projectRoot, ['rev-parse', `refs/heads/${input.executionBranch}`], 'story-worktree-integration-epic-branch-missing');
176
+ if (head !== input.after)
177
+ refuse('story-worktree-integration-epic-head-raced');
178
+ },
179
+ });
180
+ return persisted;
181
+ }
182
+ function value(input) {
183
+ return { ok: true, value: Object.freeze({ ...input, receiptDigest: digestStoryWorktreeIntegrationReceipt(input.receipt) }) };
184
+ }
185
+ /** Integrate one story worktree into `epic/<ID>` (P225.07-ADR-1..6). */
186
+ export async function integrateStoryWorktree(options) {
187
+ let physical;
188
+ let leaseToRelease;
189
+ let leaseEpicId = '';
190
+ const projectRoot = resolve(options.projectRoot);
191
+ try {
192
+ if (typeof options.storyId !== 'string' || !STORY_ID.test(options.storyId))
193
+ refuse('story-worktree-integration-story-invalid');
194
+ if (options.leaseId !== undefined && !LEASE_ID.test(options.leaseId))
195
+ refuse('story-worktree-integration-lease-invalid');
196
+ const gitDir = await realpath(await gitValue(projectRoot, ['rev-parse', '--absolute-git-dir'], 'story-worktree-integration-not-root'));
197
+ const commonDir = await realpath(await gitValue(projectRoot, ['rev-parse', '--path-format=absolute', '--git-common-dir'], 'story-worktree-integration-not-root'));
198
+ if (gitDir !== commonDir)
199
+ refuse('story-worktree-integration-not-root');
200
+ let authority;
201
+ try {
202
+ authority = await resolveDirectYoloIntegrationAuthority(projectRoot, options.storyId);
203
+ }
204
+ catch (error) {
205
+ refuse(error instanceof Error && /^direct-yolo-[a-z0-9-]+$/.test(error.message)
206
+ ? error.message : 'story-worktree-integration-authority-invalid');
207
+ }
208
+ const { epicId, executionBranch, storyId } = authority;
209
+ leaseEpicId = epicId;
210
+ const nowIso = new Date(options.nowIso ?? Date.now()).toISOString();
211
+ const epicRef = `refs/heads/${executionBranch}`;
212
+ const epicHead = await gitValue(projectRoot, ['rev-parse', epicRef], 'story-worktree-integration-epic-branch-missing');
213
+ if (await gitValue(projectRoot, ['rev-parse', 'HEAD'], 'story-worktree-integration-git-failed') !== epicHead) {
214
+ refuse('story-worktree-integration-root-head-mismatch');
215
+ }
216
+ const binding = authority.originBinding;
217
+ if (!binding || !await gitOk(projectRoot, ['merge-base', '--is-ancestor', binding.originHeadSha, epicHead])) {
218
+ refuse('story-worktree-integration-origin-binding-invalid');
219
+ }
220
+ const runtime = await readGitLifecycleRuntime(projectRoot, { required: true });
221
+ const chain = integrationReceipts(runtime, epicId);
222
+ assertIntegrationChain(chain);
223
+ const storyReceipts = chain.filter((item) => item.storyId === storyId)
224
+ .sort((left, right) => right.integrationIndex - left.integrationIndex);
225
+ const existingCheckpoint = runtime.stories[storyId]?.checkpoint;
226
+ if (storyReceipts[0]?.outcome === 'integrated') {
227
+ return value({ storyId, epicId, outcome: 'already-integrated', receipt: storyReceipts[0],
228
+ ...(existingCheckpoint?.headSha ? { checkpointHeadSha: existingCheckpoint.headSha } : {}) });
229
+ }
230
+ const dependencies = Array.isArray(authority.story.depends_on)
231
+ ? authority.story.depends_on.filter((item) => typeof item === 'string') : [];
232
+ const effectiveStories = await effectiveStoryRecords(projectRoot, runtime);
233
+ assertIntegrationAdmissible(runtime, effectiveStories, epicId, storyId, dependencies);
234
+ const activeEntry = Object.values(runtime.storyWorktrees?.entries ?? {})
235
+ .filter((entry) => entry.storyId === storyId && entry.epicId === epicId && entry.state === 'active'
236
+ && (options.leaseId === undefined || entry.leaseId === options.leaseId));
237
+ if (existingCheckpoint && typeof existingCheckpoint.headSha === 'string') {
238
+ // ADR-5: checkpoint accepted but the receipt was not persisted (crash window).
239
+ const headSha = existingCheckpoint.headSha;
240
+ const body = await gitValue(projectRoot, ['show', '--no-patch', '--format=%B', headSha], 'story-worktree-integration-git-failed');
241
+ if (trailerValue(body, 'Neocortex-Story') !== storyId || !trailerValue(body, TIP_TRAILER)) {
242
+ refuse('story-worktree-integration-checkpoint-not-worktree');
243
+ }
244
+ if (headSha !== epicHead)
245
+ refuse('story-worktree-integration-epic-head-raced');
246
+ assertChainHead(chain, existingCheckpoint.baseSha);
247
+ const receipt = await withShortIntegrationLock(projectRoot, storyId, `recover-${headSha.slice(0, 40)}`, () => persistIntegrationReceipt({
248
+ projectRoot, epicId, storyId, executionBranch,
249
+ before: existingCheckpoint.baseSha, after: headSha,
250
+ checkpointDigest: checkpointDigest(existingCheckpoint), outcome: 'integrated', integratedAt: nowIso,
251
+ }));
252
+ const worktreeRealigned = activeEntry.length === 1
253
+ ? await realignIntegratedWorktree(projectRoot, activeEntry[0].leaseId, headSha) : false;
254
+ return value({ storyId, epicId, outcome: 'integrated', receipt, checkpointHeadSha: headSha, worktreeRealigned });
255
+ }
256
+ // Journal lease of the story worktree (ownership proven, clean).
257
+ const entries = Object.values(runtime.storyWorktrees?.entries ?? {})
258
+ .filter((entry) => entry.storyId === storyId && entry.epicId === epicId && entry.state === 'active'
259
+ && (options.leaseId === undefined || entry.leaseId === options.leaseId));
260
+ if (entries.length === 0)
261
+ refuse('story-worktree-integration-lease-missing');
262
+ if (entries.length > 1)
263
+ refuse('story-worktree-integration-lease-ambiguous');
264
+ const entry = entries[0];
265
+ if (entry.executionBranch !== executionBranch)
266
+ refuse('story-worktree-integration-lease-invalid');
267
+ const manager = new StoryWorktreeManager({ projectRoot });
268
+ const probe = await manager.probe(entry.leaseId);
269
+ if (!probe.ok || probe.value.ownership !== 'proven')
270
+ refuse('story-worktree-integration-ownership-unproven');
271
+ if (probe.value.clean !== true)
272
+ refuse('story-worktree-integration-worktree-dirty');
273
+ const tip = await gitValue(projectRoot, ['rev-parse', `refs/heads/${entry.temporaryBranch}^{commit}`], 'story-worktree-integration-branch-missing');
274
+ if (probe.value.headSha !== tip)
275
+ refuse('story-worktree-integration-worktree-dirty');
276
+ // ADR-5: the epic head may already be this story's integration commit.
277
+ const headBody = await gitValue(projectRoot, ['show', '--no-patch', '--format=%B', epicHead], 'story-worktree-integration-git-failed');
278
+ const resumed = trailerValue(headBody, TIP_TRAILER) === tip && trailerValue(headBody, 'Neocortex-Story') === storyId;
279
+ let preparedBase;
280
+ let commitSha;
281
+ let idempotencyKey;
282
+ let expectedFastForward = false;
283
+ if (resumed) {
284
+ preparedBase = await gitValue(projectRoot, ['rev-parse', `${epicHead}^`], 'story-worktree-integration-git-failed');
285
+ commitSha = epicHead;
286
+ const bundleDigest = trailerValue(headBody, 'Neocortex-Bundle-Digest') ?? '';
287
+ const claimRevision = trailerValue(headBody, 'Neocortex-Claim-Revision') ?? '';
288
+ idempotencyKey = directYoloCommitIdempotencyKey({
289
+ storyId, epicId, executionBranch, baseSha: preparedBase, bundleDigest,
290
+ graphRevision: authority.graphRevision, claimRevision,
291
+ });
292
+ assertChainHead(chain, preparedBase);
293
+ }
294
+ else {
295
+ assertChainHead(chain, epicHead);
296
+ if (await gitOk(projectRoot, ['merge-base', '--is-ancestor', tip, epicHead]))
297
+ refuse('story-worktree-integration-range-empty');
298
+ const mergeBase = await gitValue(projectRoot, ['merge-base', epicHead, tip], 'story-worktree-integration-unrelated-history');
299
+ const merged = await gitRun(projectRoot, [
300
+ 'merge-tree', '--write-tree', '-z', '--name-only', '--no-messages', `--merge-base=${mergeBase}`, epicHead, tip,
301
+ ]);
302
+ if (merged.code !== 0 && merged.code !== 1)
303
+ refuse('story-worktree-integration-git-unsupported');
304
+ const fields = merged.stdout.split('\0');
305
+ const tree = fields[0]?.trim() ?? '';
306
+ if (!FULL_SHA.test(tree))
307
+ refuse('story-worktree-integration-git-unsupported');
308
+ if (merged.code === 1) {
309
+ const conflictPaths = [...new Set(fields.slice(1).filter(safeRelativePath))].sort()
310
+ .slice(0, STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS);
311
+ if (conflictPaths.length === 0)
312
+ refuse('story-worktree-integration-git-failed');
313
+ return await recordConflict({ projectRoot, epicId, storyId, executionBranch, epicHead, tip, conflictPaths,
314
+ integratedAt: nowIso, chain: storyReceipts });
315
+ }
316
+ // Canonical, deterministic single commit (ADR-1).
317
+ const changedPaths = (await gitValue(projectRoot, ['diff', '--name-only', '-z', epicHead, tree], 'story-worktree-integration-git-failed')).split('\0').filter(Boolean);
318
+ const writeSet = validateDirectYoloWriteSet(changedPaths, authority.authorizedWriteSet, storyId, authority.rootMemoryEffect);
319
+ if (!writeSet.ok)
320
+ refuse(writeSet.reasonCode === 'direct-yolo-write-set-unauthorized'
321
+ ? 'story-worktree-integration-write-set-unauthorized' : 'story-worktree-integration-write-set-invalid');
322
+ const review = publicStoryReviewArtifactFromGit(projectRoot, storyId, tree);
323
+ if (review?.verdict !== 'approved')
324
+ refuse('story-worktree-integration-review-not-approved');
325
+ const diffed = await gitRun(projectRoot, ['diff', '--binary', '--full-index', epicHead, tree]);
326
+ if (diffed.code !== 0)
327
+ refuse('story-worktree-integration-git-failed');
328
+ const payload = diffed.stdout;
329
+ if (!payload)
330
+ refuse('story-worktree-integration-range-empty');
331
+ const bundleDigest = sha256(payload);
332
+ const claimRevision = sha256([...authority.authorizedWriteSet].sort().join('\0'));
333
+ idempotencyKey = directYoloCommitIdempotencyKey({
334
+ storyId, epicId, executionBranch, baseSha: epicHead, bundleDigest, graphRevision: authority.graphRevision, claimRevision,
335
+ });
336
+ const subject = (await gitValue(projectRoot, ['show', '--no-patch', '--format=%s', tip], 'story-worktree-integration-git-failed'))
337
+ .slice(0, 200) || `feat(${storyId}): integrate story worktree`;
338
+ const trailers = [
339
+ `Neocortex-Story: ${storyId}`,
340
+ `Neocortex-Epic: ${epicId}`,
341
+ `Neocortex-Execution-Branch: ${executionBranch}`,
342
+ `Neocortex-Prepared-Base: ${epicHead}`,
343
+ `Neocortex-Bundle-Digest: ${bundleDigest}`,
344
+ `Neocortex-Review-Artifact-Digest: ${review.digest}`,
345
+ `Neocortex-Graph-Revision: ${authority.graphRevision}`,
346
+ `Neocortex-Claim-Revision: ${claimRevision}`,
347
+ ...(authority.rootMemoryEffect ? [`Neocortex-Root-Memory-Effect: ${rootMemoryEffectDigest(authority.rootMemoryEffect)}`] : []),
348
+ `${TIP_TRAILER}: ${tip}`,
349
+ ];
350
+ const identity = (await gitValue(projectRoot, ['show', '--no-patch', '--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI', tip], 'story-worktree-integration-git-failed')).split('\0');
351
+ if (identity.length !== 6)
352
+ refuse('story-worktree-integration-git-failed');
353
+ commitSha = await gitValue(projectRoot, [
354
+ 'commit-tree', tree, '-p', epicHead, '-m', subject, '-m', `Story: ${storyId}`, '-m', trailers.join('\n'),
355
+ ], 'story-worktree-integration-commit-failed', {
356
+ GIT_AUTHOR_NAME: identity[0], GIT_AUTHOR_EMAIL: identity[1], GIT_AUTHOR_DATE: identity[2],
357
+ GIT_COMMITTER_NAME: identity[3], GIT_COMMITTER_EMAIL: identity[4], GIT_COMMITTER_DATE: identity[5],
358
+ });
359
+ if (!FULL_SHA.test(commitSha))
360
+ refuse('story-worktree-integration-commit-failed');
361
+ preparedBase = epicHead;
362
+ expectedFastForward = true;
363
+ // Root checkout must not hold staged changes or local edits on the story paths.
364
+ if (!await gitOk(projectRoot, ['diff', '--cached', '--quiet'])
365
+ || !await gitOk(projectRoot, ['diff', '--quiet', 'HEAD', '--', ...changedPaths])) {
366
+ refuse('story-worktree-integration-root-dirty');
367
+ }
368
+ }
369
+ // Lease (P207) + physical lock bound to the finalize idempotency key (ADR-2).
370
+ const current = await readGitLifecycleRuntime(projectRoot, { required: true });
371
+ const priorLease = current.epics[epicId]?.branch_lease;
372
+ const reusable = priorLease && priorLease.ownerStoryId === storyId && priorLease.sessionId === idempotencyKey
373
+ && priorLease.idempotencyKey === idempotencyKey && Date.parse(String(priorLease.expiresAt)) > Date.now()
374
+ ? priorLease : undefined;
375
+ if (priorLease && !reusable && Date.parse(String(priorLease.expiresAt)) > Date.now()) {
376
+ refuse('story-worktree-integration-writer-active');
377
+ }
378
+ const lease = reusable ?? {
379
+ schemaVersion: 1, ownerStoryId: storyId, sessionId: idempotencyKey, idempotencyKey,
380
+ acquiredAt: nowIso, expiresAt: new Date(Date.parse(nowIso) + DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS).toISOString(),
381
+ };
382
+ physical = await acquireGitLifecyclePhysicalIntegrationLock(projectRoot, {
383
+ kind: 'direct', storyId, sessionId: idempotencyKey, idempotencyKey,
384
+ expiresAt: String(lease.expiresAt), persistent: true, createdAt: String(lease.acquiredAt),
385
+ });
386
+ if (!physical.ok)
387
+ refuse(physical.reasonCode === 'git-lifecycle-integration-backpressure'
388
+ ? 'story-worktree-integration-backpressure' : 'story-worktree-integration-lock-failed');
389
+ const lockHeld = physical;
390
+ if (!reusable) {
391
+ await mutateGitLifecycleRuntime(projectRoot, (document) => {
392
+ const epic = ensureRuntimeEpic(document, epicId);
393
+ const live = epic.branch_lease;
394
+ if (live && Date.parse(String(live.expiresAt)) > Date.now())
395
+ refuse('story-worktree-integration-writer-active');
396
+ if (JSON.stringify(epic.origin_binding) !== JSON.stringify(binding))
397
+ refuse('story-worktree-integration-origin-binding-invalid');
398
+ if (epic.graph_revision !== authority.graphRevision)
399
+ refuse('story-worktree-integration-graph-revision-raced');
400
+ epic.branch_lease = lease;
401
+ }, {
402
+ expectedRevision: current.revision,
403
+ preCommit: async (document) => {
404
+ if (!await verifyGitLifecyclePhysicalIntegrationLock(lockHeld.path, lockHeld.owner)) {
405
+ refuse('story-worktree-integration-lock-raced');
406
+ }
407
+ const currentChain = integrationReceipts(document, epicId);
408
+ assertIntegrationChain(currentChain);
409
+ assertChainHead(currentChain, preparedBase);
410
+ if (await gitValue(projectRoot, ['rev-parse', epicRef], 'story-worktree-integration-epic-branch-missing') !== epicHead) {
411
+ refuse('story-worktree-integration-epic-head-raced');
412
+ }
413
+ },
414
+ });
415
+ leaseToRelease = lease;
416
+ }
417
+ if (expectedFastForward) {
418
+ if (await gitValue(projectRoot, ['rev-parse', 'HEAD'], 'story-worktree-integration-git-failed') !== epicHead
419
+ || await gitValue(projectRoot, ['rev-parse', epicRef], 'story-worktree-integration-git-failed') !== epicHead) {
420
+ refuse('story-worktree-integration-epic-head-raced');
421
+ }
422
+ if (!await gitOk(projectRoot, ['merge', '--ff-only', '--no-edit', commitSha]))
423
+ refuse('story-worktree-integration-ff-refused');
424
+ if (await gitValue(projectRoot, ['rev-parse', epicRef], 'story-worktree-integration-git-failed') !== commitSha) {
425
+ refuse('story-worktree-integration-ff-refused');
426
+ }
427
+ }
428
+ await options.afterFastForward?.();
429
+ // M1: the receipt is appended inside finalize's post-persist hook, while the
430
+ // physical integration lock is still held; finalize then releases lock and lease.
431
+ let receipt;
432
+ const finalized = await finalizeDirectYoloStoryCheckpoint({
433
+ projectRoot, storyId, push: options.push, remote: options.remote, nowIso: options.nowIso, qaRunner: options.qaRunner,
434
+ afterCheckpointPersist: async () => {
435
+ const persistedCheckpoint = (await readGitLifecycleRuntime(projectRoot, { required: true }))
436
+ .stories[storyId]?.checkpoint;
437
+ if (!persistedCheckpoint || persistedCheckpoint.headSha !== commitSha || persistedCheckpoint.baseSha !== preparedBase) {
438
+ refuse('story-worktree-integration-checkpoint-mismatch');
439
+ }
440
+ receipt = await persistIntegrationReceipt({
441
+ projectRoot, epicId, storyId, executionBranch, before: preparedBase, after: commitSha,
442
+ checkpointDigest: checkpointDigest(persistedCheckpoint), outcome: 'integrated', integratedAt: nowIso,
443
+ });
444
+ },
445
+ });
446
+ if (!finalized.ok)
447
+ return { ok: false, reasonCode: finalized.reasonCode };
448
+ const checkpoint = finalized.value;
449
+ if (checkpoint.headSha !== commitSha || checkpoint.baseSha !== preparedBase || !receipt) {
450
+ refuse('story-worktree-integration-checkpoint-mismatch');
451
+ }
452
+ // ADR-6: realign the clean temporary worktree to the integration commit.
453
+ const worktreeRealigned = await realignIntegratedWorktree(projectRoot, entry.leaseId, commitSha);
454
+ return value({ storyId, epicId, outcome: 'integrated', receipt, checkpointHeadSha: commitSha, worktreeRealigned });
455
+ }
456
+ catch (error) {
457
+ if (error instanceof IntegrationRefusal)
458
+ return { ok: false, reasonCode: error.reasonCode };
459
+ const message = error instanceof Error ? error.message : '';
460
+ if (/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(message))
461
+ return { ok: false, reasonCode: message };
462
+ return { ok: false, reasonCode: 'story-worktree-integration-failed' };
463
+ }
464
+ finally {
465
+ if (physical?.ok)
466
+ await releaseGitLifecyclePhysicalIntegrationLock(physical.path, physical.owner).catch(() => undefined);
467
+ if (leaseToRelease && leaseEpicId) {
468
+ const expected = leaseToRelease;
469
+ await mutateGitLifecycleRuntime(projectRoot, (document) => {
470
+ const epic = ensureRuntimeEpic(document, leaseEpicId);
471
+ const lease = epic.branch_lease;
472
+ if (lease && lease.sessionId === expected.sessionId && lease.idempotencyKey === expected.idempotencyKey
473
+ && lease.acquiredAt === expected.acquiredAt)
474
+ epic.branch_lease = null;
475
+ }).catch(() => undefined);
476
+ }
477
+ }
478
+ }
479
+ async function effectiveStoryRecords(projectRoot, runtime) {
480
+ const tracked = JSON.parse(await readFile(join(projectRoot, '.neocortex', 'state.json'), 'utf8'));
481
+ const effective = applyGitLifecycleRuntimeOverlay(tracked, runtime);
482
+ const stories = effective.stories;
483
+ return stories && typeof stories === 'object' && !Array.isArray(stories) ? stories : {};
484
+ }
485
+ /** Serialize a receipt-only write with the single integrator (no physical Git effect). */
486
+ async function withShortIntegrationLock(projectRoot, storyId, session, run) {
487
+ const physical = await acquireGitLifecyclePhysicalIntegrationLock(projectRoot, {
488
+ kind: 'direct', storyId, sessionId: session, idempotencyKey: session,
489
+ expiresAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(), persistent: false,
490
+ });
491
+ if (!physical.ok)
492
+ refuse(physical.reasonCode === 'git-lifecycle-integration-backpressure'
493
+ ? 'story-worktree-integration-backpressure' : 'story-worktree-integration-lock-failed');
494
+ try {
495
+ return await run();
496
+ }
497
+ finally {
498
+ await releaseGitLifecyclePhysicalIntegrationLock(physical.path, physical.owner).catch(() => undefined);
499
+ }
500
+ }
501
+ /** ADR-6: move the clean, fully integrated worktree to its integration commit (`reset --keep`). */
502
+ async function realignIntegratedWorktree(projectRoot, leaseId, commitSha) {
503
+ const probe = await new StoryWorktreeManager({ projectRoot }).probe(leaseId);
504
+ if (!probe.ok || probe.value.ownership !== 'proven' || probe.value.clean !== true)
505
+ return false;
506
+ return gitOk(probe.value.entry.worktreePath, ['reset', '--keep', commitSha]);
507
+ }
508
+ async function recordConflict(input) {
509
+ const conflictDigest = sha256(['p225-integration-conflict-v1', input.storyId, input.epicHead, input.tip,
510
+ ...input.conflictPaths].join('\0'));
511
+ const latest = input.chain[0];
512
+ if (latest?.outcome === 'conflict-reopened' && latest.epicHeadAfterSha === input.epicHead
513
+ && latest.checkpointDigest === conflictDigest) {
514
+ return value({ storyId: input.storyId, epicId: input.epicId, outcome: 'conflict-reopened', receipt: latest,
515
+ conflictPaths: Object.freeze([...input.conflictPaths]) });
516
+ }
517
+ // Serialize with the single integrator; nothing physical changes.
518
+ const receipt = await withShortIntegrationLock(input.projectRoot, input.storyId, `conflict-${conflictDigest.slice(0, 48)}`, () => persistIntegrationReceipt({
519
+ projectRoot: input.projectRoot, epicId: input.epicId, storyId: input.storyId, executionBranch: input.executionBranch,
520
+ before: input.epicHead, after: input.epicHead, checkpointDigest: conflictDigest,
521
+ outcome: 'conflict-reopened', integratedAt: input.integratedAt,
522
+ }));
523
+ return value({ storyId: input.storyId, epicId: input.epicId, outcome: 'conflict-reopened', receipt,
524
+ conflictPaths: Object.freeze([...input.conflictPaths]) });
525
+ }
526
+ /** Walk `integrationOrder` strictly; stop at the first not-ready, conflicting or failing story (ADR-8). */
527
+ export async function integrateStoryWorktreesInOrder(options) {
528
+ const order = options.integrationOrder;
529
+ if (!Array.isArray(order) || order.length === 0 || new Set(order).size !== order.length
530
+ || order.some((storyId) => typeof storyId !== 'string' || !STORY_ID.test(storyId))) {
531
+ return { results: [], integratedStoryIds: [], reasonCode: 'story-worktree-integration-order-invalid' };
532
+ }
533
+ const integrate = options.integrate ?? integrateStoryWorktree;
534
+ const ready = new Set(options.readyStoryIds);
535
+ const projectRoot = resolve(options.projectRoot);
536
+ let integratedIds;
537
+ try {
538
+ const runtime = await readGitLifecycleRuntime(projectRoot, { required: true });
539
+ const epicIds = new Set(order.map((storyId) => storyId.split('.')[0]));
540
+ integratedIds = new Set([...epicIds].flatMap((epicId) => integrationReceipts(runtime, epicId))
541
+ .filter((receipt) => receipt.outcome === 'integrated').map((receipt) => receipt.storyId));
542
+ }
543
+ catch {
544
+ return { results: [], integratedStoryIds: [], reasonCode: 'story-worktree-integration-evidence-invalid' };
545
+ }
546
+ const results = [];
547
+ const integratedStoryIds = [];
548
+ for (const storyId of order) {
549
+ if (integratedIds.has(storyId))
550
+ continue;
551
+ if (!ready.has(storyId)) {
552
+ return { results, integratedStoryIds, stoppedAt: storyId, reasonCode: 'story-worktree-integration-waiting' };
553
+ }
554
+ const { integrationOrder: _order, readyStoryIds: _ready, integrate: _integrate, ...rest } = options;
555
+ const result = await integrate({ ...rest, projectRoot, storyId });
556
+ results.push({ storyId, result });
557
+ if (!result.ok)
558
+ return { results, integratedStoryIds, stoppedAt: storyId, reasonCode: result.reasonCode };
559
+ if (result.value.outcome === 'conflict-reopened') {
560
+ return { results, integratedStoryIds, stoppedAt: storyId, reasonCode: 'integration-conflict-reopened' };
561
+ }
562
+ integratedStoryIds.push(storyId);
563
+ integratedIds.add(storyId);
564
+ }
565
+ return { results, integratedStoryIds };
566
+ }
567
+ /**
568
+ * Run `story-worktree sync` for every server `DependencyReleaseDirective`
569
+ * (ADR-8). The manager re-validates the closed directive shape and requires
570
+ * the cited SHA to be contained in `epic/<ID>`.
571
+ */
572
+ export async function syncReleasedDependents(input) {
573
+ const projectRoot = resolve(input.projectRoot);
574
+ const manager = input.manager ?? new StoryWorktreeManager({ projectRoot });
575
+ let runtime;
576
+ try {
577
+ runtime = await readGitLifecycleRuntime(projectRoot, { required: true });
578
+ }
579
+ catch {
580
+ return input.directives.map(() => ({ storyId: '', ok: false, reasonCode: 'story-worktree-sync-evidence-invalid' }));
581
+ }
582
+ const results = [];
583
+ for (const directive of input.directives) {
584
+ const record = directive && typeof directive === 'object' && !Array.isArray(directive)
585
+ ? directive : undefined;
586
+ const storyId = typeof record?.storyId === 'string' && STORY_ID.test(record.storyId) ? record.storyId : '';
587
+ if (!storyId) {
588
+ results.push({ storyId: '', ok: false, reasonCode: 'story-worktree-directive-invalid' });
589
+ continue;
590
+ }
591
+ const leases = Object.values(runtime.storyWorktrees?.entries ?? {})
592
+ .filter((entry) => entry.storyId === storyId && entry.state === 'active');
593
+ if (leases.length !== 1) {
594
+ results.push({ storyId, ok: false, reasonCode: leases.length === 0 ? 'story-worktree-lease-missing' : 'story-worktree-lease-ambiguous' });
595
+ continue;
596
+ }
597
+ const synced = await manager.sync({ leaseId: leases[0].leaseId, directive });
598
+ results.push(synced.ok
599
+ ? { storyId, ok: true, outcome: synced.value.outcome, integratedSha: synced.value.integratedSha }
600
+ : { storyId, ok: false, reasonCode: synced.reasonCode, ...(synced.conflictPaths ? { conflictPaths: synced.conflictPaths } : {}) });
601
+ }
602
+ return results;
603
+ }