@ornexus/neocortex 4.61.4 → 4.61.6

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 (254) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -260
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -364
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +148 -7822
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -174
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  76. package/packages/client/dist/commands/story-worktree.js +5 -258
  77. package/packages/client/dist/config/host-auth-broker.js +1 -60
  78. package/packages/client/dist/config/host-auth-reference.js +1 -93
  79. package/packages/client/dist/config/profile-directory.js +1 -13
  80. package/packages/client/dist/config/resolver-selection.js +1 -278
  81. package/packages/client/dist/config/secure-config.js +12 -281
  82. package/packages/client/dist/config.js +2 -224
  83. package/packages/client/dist/constants.js +1 -25
  84. package/packages/client/dist/context/context-collector.js +2 -222
  85. package/packages/client/dist/context/context-sanitizer.js +1 -145
  86. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  87. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  88. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  89. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  90. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  91. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  92. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  93. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  94. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  95. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  96. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  97. package/packages/client/dist/continuity/outbox.js +1 -117
  98. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  99. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  100. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  101. package/packages/client/dist/errors/error-messages.js +2 -258
  102. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  103. package/packages/client/dist/evidence/collector.js +1 -347
  104. package/packages/client/dist/evidence/index.js +1 -1
  105. package/packages/client/dist/evidence/types.js +0 -2
  106. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  107. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  108. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  109. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  110. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
  111. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
  112. package/packages/client/dist/git/epic-operational-state.js +2 -672
  113. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  114. package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
  115. package/packages/client/dist/git/git-lifecycle-store.js +8 -2500
  116. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  117. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  118. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  119. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  120. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  121. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  122. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  123. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  124. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  125. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  126. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  127. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  128. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  129. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  130. package/packages/client/dist/i18n/first-run.js +2 -60
  131. package/packages/client/dist/index.js +1 -50
  132. package/packages/client/dist/invocation/invoke-input.js +1 -24
  133. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  134. package/packages/client/dist/license/index.js +1 -5
  135. package/packages/client/dist/license/license-client.js +1 -337
  136. package/packages/client/dist/machine/fingerprint.js +2 -163
  137. package/packages/client/dist/machine/index.js +1 -5
  138. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  139. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  140. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  141. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  142. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  143. package/packages/client/dist/migrations/project-identity.js +7 -493
  144. package/packages/client/dist/migrations/state-json.js +4 -393
  145. package/packages/client/dist/policy/architecture-policy.js +2 -184
  146. package/packages/client/dist/policy/index.js +1 -7
  147. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  148. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  149. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  150. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  151. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  152. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  153. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  154. package/packages/client/dist/private-execution/delivery.js +13 -410
  155. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  156. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  157. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  158. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  159. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  160. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  161. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  162. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  163. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  164. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  165. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  166. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  167. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  168. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  169. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  170. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  171. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  172. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  173. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  174. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  175. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  176. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  177. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  178. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  179. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  180. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  181. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  182. package/packages/client/dist/private-execution/session-lease.js +1 -63
  183. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  184. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  185. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  186. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  187. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  188. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  189. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  190. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  191. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  192. package/packages/client/dist/resilience/index.js +1 -8
  193. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  194. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  195. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  196. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  197. package/packages/client/dist/runner/binary.js +1 -404
  198. package/packages/client/dist/runner/cli.js +17 -1571
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.js +1 -85
  202. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  203. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  204. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  205. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  206. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  207. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  208. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  209. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  210. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  211. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  212. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  213. package/packages/client/dist/runner/headless/resolver.js +1 -231
  214. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  215. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  216. package/packages/client/dist/runner/headless/types.js +2 -575
  217. package/packages/client/dist/runner/host-capacity.js +1 -59
  218. package/packages/client/dist/runner/local-console.js +13 -396
  219. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  220. package/packages/client/dist/runner/project-identity.js +1 -106
  221. package/packages/client/dist/runner/scheduler.js +7 -995
  222. package/packages/client/dist/runner-cli.js +2 -18
  223. package/packages/client/dist/state/invocation-shape.js +1 -13
  224. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  225. package/packages/client/dist/state/state-json-repair.js +3 -785
  226. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  227. package/packages/client/dist/telemetry/index.js +1 -5
  228. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  229. package/packages/client/dist/tier/index.js +1 -5
  230. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  231. package/packages/client/dist/types/index.js +1 -38
  232. package/packages/client/dist/version.js +1 -27
  233. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  234. package/packages/client/dist/yolo/change-evidence-collector.js +1 -245
  235. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  236. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  237. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  238. package/packages/client/dist/yoloop/index.js +1 -8
  239. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  240. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  241. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  242. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  243. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  244. package/targets-stubs/antigravity/gemini.md +1 -1
  245. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  246. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  247. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  248. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  249. package/targets-stubs/claude-code/neocortex.md +2 -2
  250. package/targets-stubs/codex/AGENTS.md +1 -1
  251. package/targets-stubs/cursor/agent.md +2 -2
  252. package/targets-stubs/gemini-cli/agent.md +2 -2
  253. package/targets-stubs/opencode/neocortex-root.md +1 -1
  254. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,603 +1,3 @@
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
- }
1
+ import{execFile as Ze}from"node:child_process";import{createHash as et}from"node:crypto";import{readFile as tt,realpath as ve}from"node:fs/promises";import{join as rt,resolve as Se}from"node:path";import{yoloopDomainHash as ot}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as $e,directYoloCommitIdempotencyKey as Le,directYoloWaveQaCoverage as it,finalizeDirectYoloStoryCheckpoint as at,persistDirectYoloWaveStoryCheckpoint as nt,pushDirectYoloWaveHead as st,resolveDirectYoloIntegrationAuthority as Ge,runDirectYoloWaveP205 as ct,validateDirectYoloWriteSet as dt}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Ce,appendStoryWorktreeEvidence as ft,applyGitLifecycleRuntimeOverlay as gt,ensureRuntimeEpic as be,isStoryWorktreeIntegrationReceiptRecord as lt,mutateGitLifecycleRuntime as ye,publicStoryReviewArtifactFromGit as yt,readGitLifecycleRuntime as Y,readStoryWorktreeEvidence as Ke,releaseGitLifecyclePhysicalIntegrationLock as Ee,verifyGitLifecyclePhysicalIntegrationLock as Ye}from"./git-lifecycle-store.js";import{StoryWorktreeManager as Ae}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as ht}from"../private-execution/root-memory-git-evidence.js";const wt="neocortex.p225.story-worktree-receipt.v1",pt=200,he="Neocortex-Story-Worktree-Tip",ut=3e4,Oe=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,mt=/^swt-[a-f0-9]{24}$/,xe=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class _e extends Error{reasonCode;constructor(a){super(a),this.reasonCode=a}}function o(e){throw new _e(e)}function Z(e,a,c){return new Promise(d=>{Ze("git",[...a],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024,timeout:ut,env:{...process.env,...c,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,w)=>{const i=r?typeof r.code=="number"?r.code:128:0;d({code:i,stdout:String(w??"")})})})}async function h(e,a,c,d){const r=await Z(e,a,d);return r.code!==0&&o(c),r.stdout.trim()}async function R(e,a){return(await Z(e,a)).code===0}function ne(e){return et("sha256").update(e).digest("hex")}function kt(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(a=>a!==""&&a!=="."&&a!=="..")}function N(e,a){const c=`${a}: `,d=e.split(`
2
+ `).map(r=>r.trim()).filter(r=>r.startsWith(c));return d.length===1?d[0].slice(c.length):void 0}function He(e){return ot(wt,e)}function F(e,a){return(Ke(e,a)?.receipts??[]).filter(lt)}function we(e){const a=[...e].sort((c,d)=>c.integrationIndex-d.integrationIndex);a.forEach((c,d)=>{(c.integrationIndex!==d+1||d>0&&c.epicHeadBeforeSha!==a[d-1].epicHeadAfterSha)&&o("story-worktree-integration-chain-invalid")})}function se(e,a){const c=[...e].sort((d,r)=>r.integrationIndex-d.integrationIndex)[0];c&&c.epicHeadAfterSha!==a&&o("story-worktree-integration-chain-invalid")}const It=new Set(["done","merged","completed","released"]);function Fe(e,a,c,d,r,w=new Set){(Ke(e,c)?.receipts??[]).some(s=>s.kind==="phase-one-receipt"&&s.storyId===d||s.kind==="spec-barrier-receipt"&&Array.isArray(s.storyIds)&&s.storyIds.includes(d))||o("story-worktree-integration-unbound");const u=new Set(F(e,c).filter(s=>s.outcome==="integrated").map(s=>s.storyId));for(const s of r){if(!s.startsWith(`${c}.`))continue;const v=a[s],k=!!e.stories[s]?.checkpoint||typeof v?.status=="string"&&It.has(v.status);!u.has(s)&&!w.has(s)&&!k&&o("story-worktree-integration-dependency-waiting")}}function vt(e){const a=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",c=`int-${ne(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:c,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:a,integratedAt:e.integratedAt})}function Te(e){return ne(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Re(e){let a;return await ye(e.projectRoot,c=>{const d=F(c,e.epicId);we(d);const r=[...d].sort((i,f)=>f.integrationIndex-i.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&o("story-worktree-integration-chain-invalid"),[...d].filter(i=>i.storyId===e.storyId).sort((i,f)=>f.integrationIndex-i.integrationIndex)[0]?.outcome==="integrated"&&o("story-worktree-integration-already-integrated"),a=vt({epicId:e.epicId,storyId:e.storyId,index:d.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),ft(c,e.epicId,{receipts:[a]})},{preCommit:async()=>{await h(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&o("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await R(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&o("story-worktree-integration-epic-head-raced")}}),a}function pe(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:He(e.receipt)})}}async function St(e){let a,c,d="";const r=Se(e.projectRoot);try{(typeof e.storyId!="string"||!xe.test(e.storyId))&&o("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!mt.test(e.leaseId)&&o("story-worktree-integration-lease-invalid");const w=await ve(await h(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),i=await ve(await h(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));w!==i&&o("story-worktree-integration-not-root");let f;try{f=await Ge(r,e.storyId)}catch(l){o(l instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(l.message)?l.message:"story-worktree-integration-authority-invalid")}const{epicId:g,executionBranch:u,storyId:s}=f;d=g;const v=new Date(e.nowIso??Date.now()).toISOString(),k=`refs/heads/${u}`,p=await h(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing");await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p&&o("story-worktree-integration-root-head-mismatch");const _=f.originBinding;(!_||!await R(r,["merge-base","--is-ancestor",_.originHeadSha,p]))&&o("story-worktree-integration-origin-binding-invalid");const A=await Y(r,{required:!0}),S=F(A,g);we(S);const z=S.filter(l=>l.storyId===s).sort((l,b)=>b.integrationIndex-l.integrationIndex),E=A.stories[s]?.checkpoint;if(z[0]?.outcome==="integrated")return pe({storyId:s,epicId:g,outcome:"already-integrated",receipt:z[0],...E?.headSha?{checkpointHeadSha:E.headSha}:{}});const ce=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(l=>typeof l=="string"):[],T=await Ue(r,A);Fe(A,T,g,s,ce);const D=Object.values(A.storyWorktrees?.entries??{}).filter(l=>l.storyId===s&&l.epicId===g&&l.state==="active"&&(e.leaseId===void 0||l.leaseId===e.leaseId));if(E&&typeof E.headSha=="string"){const l=E.headSha,b=await h(r,["show","--no-patch","--format=%B",l],"story-worktree-integration-git-failed");(N(b,"Neocortex-Story")!==s||!N(b,he))&&o("story-worktree-integration-checkpoint-not-worktree"),l!==p&&o("story-worktree-integration-epic-head-raced"),se(S,E.baseSha);const X=await Ve(r,s,`recover-${l.slice(0,40)}`,()=>Re({projectRoot:r,epicId:g,storyId:s,executionBranch:u,before:E.baseSha,after:l,checkpointDigest:Te(E),outcome:"integrated",integratedAt:v})),oe=D.length===1?await Pe(r,D[0].leaseId,l):!1;return pe({storyId:s,epicId:g,outcome:"integrated",receipt:X,checkpointHeadSha:l,worktreeRealigned:oe})}const q=Object.values(A.storyWorktrees?.entries??{}).filter(l=>l.storyId===s&&l.epicId===g&&l.state==="active"&&(e.leaseId===void 0||l.leaseId===e.leaseId));q.length===0&&o("story-worktree-integration-lease-missing"),q.length>1&&o("story-worktree-integration-lease-ambiguous");const C=q[0];C.executionBranch!==u&&o("story-worktree-integration-lease-invalid");const M=await new Ae({projectRoot:r}).probe(C.leaseId);(!M.ok||M.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),M.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const ee=await h(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");M.value.headSha!==ee&&o("story-worktree-integration-worktree-dirty");const O=await h(r,["show","--no-patch","--format=%B",p],"story-worktree-integration-git-failed"),J=N(O,he)===ee&&N(O,"Neocortex-Story")===s;let x,P,m,K=!1;if(J){x=await h(r,["rev-parse",`${p}^`],"story-worktree-integration-git-failed"),P=p;const l=N(O,"Neocortex-Bundle-Digest")??"",b=N(O,"Neocortex-Claim-Revision")??"";m=Le({storyId:s,epicId:g,executionBranch:u,baseSha:x,bundleDigest:l,graphRevision:f.graphRevision,claimRevision:b}),se(S,x)}else{se(S,p);const l=await Je(r,f,s,p,ee);if(l.kind==="conflict")return await je({projectRoot:r,epicId:g,storyId:s,executionBranch:u,epicHead:p,tip:ee,conflictPaths:l.conflictPaths,integratedAt:v,chain:z});const b=l.changedPaths;P=l.commitSha,m=l.idempotencyKey,x=p,K=!0,(!await R(r,["diff","--cached","--quiet"])||!await R(r,["diff","--quiet","HEAD","--",...b]))&&o("story-worktree-integration-root-dirty")}const U=await Y(r,{required:!0}),B=U.epics[g]?.branch_lease,te=B&&B.ownerStoryId===s&&B.sessionId===m&&B.idempotencyKey===m&&Date.parse(String(B.expiresAt))>Date.now()?B:void 0;B&&!te&&Date.parse(String(B.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const W=te??{schemaVersion:1,ownerStoryId:s,sessionId:m,idempotencyKey:m,acquiredAt:v,expiresAt:new Date(Date.parse(v)+$e).toISOString()};a=await Ce(r,{kind:"direct",storyId:s,sessionId:m,idempotencyKey:m,expiresAt:String(W.expiresAt),persistent:!0,createdAt:String(W.acquiredAt)}),a.ok||o(a.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const $=a;te||(await ye(r,l=>{const b=be(l,g),X=b.branch_lease;X&&Date.parse(String(X.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(b.origin_binding)!==JSON.stringify(_)&&o("story-worktree-integration-origin-binding-invalid"),b.graph_revision!==f.graphRevision&&o("story-worktree-integration-graph-revision-raced"),b.branch_lease=W},{expectedRevision:U.revision,preCommit:async l=>{await Ye($.path,$.owner)||o("story-worktree-integration-lock-raced");const b=F(l,g);we(b),se(b,x),await h(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing")!==p&&o("story-worktree-integration-epic-head-raced")}}),c=W),K&&((await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p||await h(r,["rev-parse",k],"story-worktree-integration-git-failed")!==p)&&o("story-worktree-integration-epic-head-raced"),await R(r,["merge","--ff-only","--no-edit",P])||o("story-worktree-integration-ff-refused"),await h(r,["rev-parse",k],"story-worktree-integration-git-failed")!==P&&o("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let V;const re=await at({projectRoot:r,storyId:s,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const l=(await Y(r,{required:!0})).stories[s]?.checkpoint;(!l||l.headSha!==P||l.baseSha!==x)&&o("story-worktree-integration-checkpoint-mismatch"),V=await Re({projectRoot:r,epicId:g,storyId:s,executionBranch:u,before:x,after:P,checkpointDigest:Te(l),outcome:"integrated",integratedAt:v})}});if(!re.ok)return{ok:!1,reasonCode:re.reasonCode};const j=re.value;(j.headSha!==P||j.baseSha!==x||!V)&&o("story-worktree-integration-checkpoint-mismatch");const de=await Pe(r,C.leaseId,P);return pe({storyId:s,epicId:g,outcome:"integrated",receipt:V,checkpointHeadSha:P,worktreeRealigned:de})}catch(w){if(w instanceof _e)return{ok:!1,reasonCode:w.reasonCode};const i=w instanceof Error?w.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(i)?{ok:!1,reasonCode:i}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(a?.ok&&await Ee(a.path,a.owner).catch(()=>{}),c&&d){const w=c;await ye(r,i=>{const f=be(i,d),g=f.branch_lease;g&&g.sessionId===w.sessionId&&g.idempotencyKey===w.idempotencyKey&&g.acquiredAt===w.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}async function Je(e,a,c,d,r){const{epicId:w,executionBranch:i}=a;await R(e,["merge-base","--is-ancestor",r,d])&&o("story-worktree-integration-range-empty");const f=await h(e,["merge-base",d,r],"story-worktree-integration-unrelated-history"),g=await Z(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,d,r]);g.code!==0&&g.code!==1&&o("story-worktree-integration-git-unsupported");const u=g.stdout.split("\0"),s=u[0]?.trim()??"";if(Oe.test(s)||o("story-worktree-integration-git-unsupported"),g.code===1){const C=[...new Set(u.slice(1).filter(kt))].sort().slice(0,pt);return C.length===0&&o("story-worktree-integration-git-failed"),{kind:"conflict",conflictPaths:C}}const v=(await h(e,["diff","--name-only","-z",d,s],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),k=dt(v,a.authorizedWriteSet,c,a.rootMemoryEffect);k.ok||o(k.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":"story-worktree-integration-write-set-invalid");const p=yt(e,c,s);p?.verdict!=="approved"&&o("story-worktree-integration-review-not-approved");const _=await Z(e,["diff","--binary","--full-index",d,s]);_.code!==0&&o("story-worktree-integration-git-failed");const A=_.stdout;A||o("story-worktree-integration-range-empty");const S=ne(A),z=ne([...a.authorizedWriteSet].sort().join("\0")),E=Le({storyId:c,epicId:w,executionBranch:i,baseSha:d,bundleDigest:S,graphRevision:a.graphRevision,claimRevision:z}),ce=(await h(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${c}): integrate story worktree`,T=[`Neocortex-Story: ${c}`,`Neocortex-Epic: ${w}`,`Neocortex-Execution-Branch: ${i}`,`Neocortex-Prepared-Base: ${d}`,`Neocortex-Bundle-Digest: ${S}`,`Neocortex-Review-Artifact-Digest: ${p.digest}`,`Neocortex-Graph-Revision: ${a.graphRevision}`,`Neocortex-Claim-Revision: ${z}`,...a.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${ht(a.rootMemoryEffect)}`]:[],`${he}: ${r}`],D=(await h(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");D.length!==6&&o("story-worktree-integration-git-failed");const q=await h(e,["commit-tree",s,"-p",d,"-m",ce,"-m",`Story: ${c}`,"-m",T.join(`
3
+ `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:D[0],GIT_AUTHOR_EMAIL:D[1],GIT_AUTHOR_DATE:D[2],GIT_COMMITTER_NAME:D[3],GIT_COMMITTER_EMAIL:D[4],GIT_COMMITTER_DATE:D[5]});return Oe.test(q)||o("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:q,changedPaths:v,idempotencyKey:E}}async function Ue(e,a){const c=JSON.parse(await tt(rt(e,".neocortex","state.json"),"utf8")),r=gt(c,a).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function Ve(e,a,c,d){const r=await Ce(e,{kind:"direct",storyId:a,sessionId:c,idempotencyKey:c,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||o(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await d()}finally{await Ee(r.path,r.owner).catch(()=>{})}}async function Pe(e,a,c){const d=await new Ae({projectRoot:e}).probe(a);return!d.ok||d.value.ownership!=="proven"||d.value.clean!==!0?!1:R(d.value.entry.worktreePath,["reset","--keep",c])}async function je(e){const a=ne(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),c=e.chain[0];if(c?.outcome==="conflict-reopened"&&c.epicHeadAfterSha===e.epicHead&&c.checkpointDigest===a)return pe({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:c,conflictPaths:Object.freeze([...e.conflictPaths])});const d=()=>Re({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:a,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await d():await Ve(e.projectRoot,e.storyId,`conflict-${a.slice(0,48)}`,d);return pe({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const bt=64;function At(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function Pt(e){let a,c,d="",r=0,w;const i=Se(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>bt||new Set(f).size!==f.length||f.some(t=>typeof t!="string"||!xe.test(t)))&&o("story-worktree-wave-stories-invalid");const g=await ve(await h(i,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await ve(await h(i,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==u&&o("story-worktree-integration-not-root");const s=new Map;for(const t of f)try{s.set(t,await Ge(i,t))}catch(n){o(n instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(n.message)?n.message:"story-worktree-integration-authority-invalid")}const v=s.get(f[0]),{epicId:k,executionBranch:p}=v;for(const t of s.values())(t.epicId!==k||t.executionBranch!==p||t.graphRevision!==v.graphRevision||JSON.stringify(t.originBinding)!==JSON.stringify(v.originBinding))&&o("story-worktree-wave-epic-mixed");d=k;const _=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${p}`,S=await h(i,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==S||await h(i,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==p)&&o("story-worktree-integration-root-head-mismatch");const z=v.originBinding;(!z||!await R(i,["merge-base","--is-ancestor",z.originHeadSha,S]))&&o("story-worktree-integration-origin-binding-invalid");const E=t=>{const n=s.get(t).story;return Array.isArray(n.depends_on)?n.depends_on.filter(y=>typeof y=="string"):[]},ce=new Map(f.map((t,n)=>[t,n]));f.forEach((t,n)=>{for(const y of E(t)){const I=ce.get(y);I!==void 0&&I>=n&&o("story-worktree-wave-order-invalid")}});const T=await Y(i,{required:!0}),D=F(T,k);we(D);const q=t=>D.filter(n=>n.storyId===t).sort((n,y)=>y.integrationIndex-n.integrationIndex)[0],C=f.filter(t=>q(t)?.outcome!=="integrated"),G=new Map(f.filter(t=>!C.includes(t)).map(t=>{const n=q(t),y=T.stories[t]?.checkpoint;return[t,Object.freeze({storyId:t,outcome:"already-integrated",receiptDigest:He(n),...y?.headSha?{checkpointHeadSha:y.headSha}:{}})]})),M=t=>({ok:!0,value:Object.freeze({epicId:k,...t,gateRuns:r,stories:Object.freeze(f.map(n=>G.get(n)??Object.freeze({storyId:n,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return M({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0});const ee=new Set(C),O=[];let J=S;for(let t=0;t<C.length;t++){const n=await h(i,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed"),y=N(n,"Neocortex-Story");if(!y||!ee.has(y)||!N(n,he))break;O.unshift(J),J=await h(i,["rev-parse",`${J}^`],"story-worktree-integration-git-failed")}const x=J;se(D,x);const P=await Ue(i,T),m=[];let K,U=x;for(const[t,n]of C.entries()){const y=s.get(n);Fe(T,P,k,n,E(n),new Set(C.slice(0,t)));const I=Object.values(T.storyWorktrees?.entries??{}).filter(L=>L.storyId===n&&L.epicId===k&&L.state==="active"),H=T.stories[n]?.checkpoint;if(H&&typeof H.headSha=="string"){const L=H.headSha,We=await h(i,["show","--no-patch","--format=%B",L],"story-worktree-integration-git-failed");(N(We,"Neocortex-Story")!==n||!N(We,he))&&o("story-worktree-integration-checkpoint-not-worktree"),(H.baseSha!==U||O[t]!==L)&&o("story-worktree-integration-checkpoint-mismatch");const Qe=(await h(i,["diff-tree","--no-commit-id","--name-only","-r","-z",L],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);m.push({storyId:n,sha:L,changedPaths:Qe,...I.length===1?{leaseId:I[0].leaseId}:{}}),U=L;continue}I.length===0&&o("story-worktree-integration-lease-missing"),I.length>1&&o("story-worktree-integration-lease-ambiguous");const ke=I[0];ke.executionBranch!==p&&o("story-worktree-integration-lease-invalid");const Ie=await new Ae({projectRoot:i}).probe(ke.leaseId);(!Ie.ok||Ie.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),Ie.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const De=await h(i,["rev-parse",`refs/heads/${ke.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Ie.value.headSha!==De&&o("story-worktree-integration-worktree-dirty");const ae=await Je(i,y,n,U,De);if(ae.kind==="conflict"){t<O.length&&o("story-worktree-wave-resume-mismatch"),K={storyId:n,tip:De,conflictPaths:ae.conflictPaths};break}t<O.length&&O[t]!==ae.commitSha&&o("story-worktree-wave-resume-mismatch"),m.push({storyId:n,sha:ae.commitSha,changedPaths:ae.changedPaths,leaseId:ke.leaseId}),U=ae.commitSha}if(m.length<O.length&&o("story-worktree-wave-resume-mismatch"),m.length===0){const t=K,n=await je({projectRoot:i,epicId:k,storyId:t.storyId,executionBranch:p,epicHead:S,tip:t.tip,conflictPaths:t.conflictPaths,integratedAt:_,chain:D.filter(y=>y.storyId===t.storyId).sort((y,I)=>I.integrationIndex-y.integrationIndex)});return n.ok?(G.set(t.storyId,Object.freeze({storyId:t.storyId,outcome:"conflict-reopened",receiptDigest:n.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...t.conflictPaths])})),M({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0})):{ok:!1,reasonCode:n.reasonCode,gateRuns:r}}const B=m[m.length-1].sha,te=[...new Set(m.flatMap(t=>t.changedPaths))].sort();(!await R(i,["diff","--cached","--quiet"])||!await R(i,["diff","--quiet","HEAD","--",...te]))&&o("story-worktree-integration-root-dirty");const W=At(m.length),$=ne(["p205-wave-lease-v1",k,p,x,...m.map(t=>t.sha)].join("\0")),V=m[0].storyId,re=await Y(i,{required:!0}),j=re.epics[k]?.branch_lease,de=j&&j.ownerStoryId===V&&j.sessionId===$&&j.idempotencyKey===$&&Date.parse(String(j.expiresAt))>Date.now()?j:void 0;j&&!de&&Date.parse(String(j.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const l=de??{schemaVersion:1,ownerStoryId:V,sessionId:$,idempotencyKey:$,acquiredAt:_,expiresAt:new Date(Date.parse(_)+$e*W).toISOString()};a=await Ce(i,{kind:"direct",storyId:V,sessionId:$,idempotencyKey:$,expiresAt:String(l.expiresAt),persistent:!0,createdAt:String(l.acquiredAt)}),a.ok||o(a.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const b=a;de||await ye(i,t=>{const n=be(t,k),y=n.branch_lease;y&&Date.parse(String(y.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(n.origin_binding)!==JSON.stringify(z)&&o("story-worktree-integration-origin-binding-invalid"),n.graph_revision!==v.graphRevision&&o("story-worktree-integration-graph-revision-raced"),n.branch_lease=l},{expectedRevision:re.revision,preCommit:async t=>{await Ye(b.path,b.owner)||o("story-worktree-integration-lock-raced");const n=F(t,k);we(n),se(n,x),await h(i,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==S&&o("story-worktree-integration-epic-head-raced")}}),c=l;const X=new Set(m.map(t=>t.sha));let oe=!0;if(e.push&&O.length>0){const t=(await Z(i,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";Oe.test(t)&&await R(i,["merge-base","--is-ancestor",O[0],t])&&(oe=!1)}let ie=S;const ue=async t=>{if((await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==ie||await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ie||await h(i,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==p)&&o("story-worktree-integration-epic-head-raced"),ie===t)return;const n=await R(i,["merge-base","--is-ancestor",ie,t]);!n&&(!oe||!X.has(ie))&&o("story-worktree-wave-pushed-immovable"),(!(n?await R(i,["merge","--ff-only","--no-edit",t]):await R(i,["reset","--keep",t]))||await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==t||await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==t)&&o("story-worktree-integration-ff-refused"),ie=t};w=oe?{epicRef:A,base:x,owned:X}:void 0,await ue(B),await e.afterWaveFastForward?.();const Xe=[...new Set([v.graphRevision,...m.map(t=>T.stories[t.storyId]?.checkpoint?.graphRevision).filter(t=>typeof t=="string")])],ze=async t=>{const n=m[t];await ue(n.sha),r>=W&&o("story-worktree-wave-gate-cap-exceeded"),r++;const y=await ct({projectRoot:i,headSha:n.sha,storyId:n.storyId,graphRevisions:Xe,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==n.sha||await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==n.sha||!await R(i,["diff","--cached","--quiet"])||!await R(i,["diff","--quiet","HEAD","--",...te]))&&o("story-worktree-integration-epic-head-raced"),!y.ok&&y.kind==="infrastructure"&&o(y.reasonCode),y},me=await ze(m.length-1);let Be=m.length-1,Ne=me.ok?me.authorities:void 0,fe,ge;if(!me.ok){oe||o("story-worktree-wave-gate-failed-pushed");let t=-1,n=m.length-1;for(ge=me.reasonCode;n-t>1;){const I=Math.floor((t+n)/2),H=await ze(I);H.ok?(t=I,Ne=H.authorities):(n=I,ge=H.reasonCode)}fe=n,Be=t;const y=m[n].storyId;if(G.set(y,Object.freeze({storyId:y,outcome:"gate-failed",reasonCode:ge})),t<0)return await ue(x),w=void 0,M({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:y,failureReasonCode:ge,epicHeadBeforeSha:S,epicHeadAfterSha:x,gateRunCap:W});await ue(m[t].sha)}const Q=m.slice(0,Be+1),le=Q[Q.length-1].sha,qe=it({epicId:k,executionBranch:p,waveHeadSha:le,waveStoryIds:Q.map(t=>t.storyId),waveCommitShas:Q.map(t=>t.sha)});e.push&&(w=void 0,await st(i,e.remote??"origin",p,le)||o("story-worktree-wave-remote-head-mismatch")),w=void 0;const Me=[];for(const[t,n]of Q.entries()){const y=t===0?x:Q[t-1].sha,I=await nt({projectRoot:i,storyId:n.storyId,headSha:n.sha,coverage:qe,authorities:Ne,expectedLease:l,physicalLock:b,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||o(I.reasonCode),(I.value.headSha!==n.sha||I.value.baseSha!==y)&&o("story-worktree-integration-checkpoint-mismatch");const H=await Re({projectRoot:i,epicId:k,storyId:n.storyId,executionBranch:p,before:y,after:n.sha,checkpointDigest:Te(I.value),outcome:"integrated",integratedAt:_,expectedEpicHead:le});Me.push(n.storyId),G.set(n.storyId,Object.freeze({storyId:n.storyId,outcome:"integrated",checkpointHeadSha:n.sha,receiptDigest:He(H)})),await e.afterWaveStoryPersist?.(n.storyId)}if(K&&fe===void 0){const t=K,n=await Y(i,{required:!0}),y=await je({projectRoot:i,epicId:k,storyId:t.storyId,executionBranch:p,epicHead:le,tip:t.tip,conflictPaths:t.conflictPaths,integratedAt:_,chain:F(n,k).filter(I=>I.storyId===t.storyId).sort((I,H)=>H.integrationIndex-I.integrationIndex),lockHeld:!0});y.ok||o(y.reasonCode),G.set(t.storyId,Object.freeze({storyId:t.storyId,outcome:"conflict-reopened",receiptDigest:y.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...t.conflictPaths])}))}for(const t of Q){if(!t.leaseId)continue;const n=await Pe(i,t.leaseId,t.sha);G.set(t.storyId,Object.freeze({...G.get(t.storyId),worktreeRealigned:n}))}return M({outcome:fe!==void 0?"gate-failed":K?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Me),...fe!==void 0?{failedStoryId:m[fe].storyId,failureReasonCode:ge}:{},epicHeadBeforeSha:S,epicHeadAfterSha:le,qaCoverage:qe,gateRunCap:W})}catch(f){let g=f instanceof _e?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(w){const u=w,s=(await Z(i,["rev-parse",u.epicRef])).stdout.trim(),v=(await Z(i,["rev-parse","HEAD"])).stdout.trim();s!==u.base&&(s!==v||!u.owned.has(s)||!await R(i,["reset","--keep",u.base]))&&(g="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:g,gateRuns:r}}finally{if(a?.ok&&await Ee(a.path,a.owner).catch(()=>{}),c&&d){const f=c;await ye(i,g=>{const u=be(g,d),s=u.branch_lease;s&&s.sessionId===f.sessionId&&s.idempotencyKey===f.idempotencyKey&&s.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function jt(e){const a=e.integrationOrder;if(!Array.isArray(a)||a.length===0||new Set(a).size!==a.length||a.some(g=>typeof g!="string"||!xe.test(g)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const c=e.integrate??St,d=new Set(e.readyStoryIds),r=Se(e.projectRoot);let w;try{const g=await Y(r,{required:!0}),u=new Set(a.map(s=>s.split(".")[0]));w=new Set([...u].flatMap(s=>F(g,s)).filter(s=>s.outcome==="integrated").map(s=>s.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const i=[],f=[];for(const g of a){if(w.has(g))continue;if(!d.has(g))return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:s,integrate:v,...k}=e,p=await c({...k,projectRoot:r,storyId:g});if(i.push({storyId:g,result:p}),!p.ok)return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:p.reasonCode};if(p.value.outcome==="conflict-reopened")return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:"integration-conflict-reopened"};f.push(g),w.add(g)}return{results:i,integratedStoryIds:f}}async function zt(e){const a=Se(e.projectRoot),c=e.manager??new Ae({projectRoot:a});let d;try{d=await Y(a,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const w of e.directives){const i=w&&typeof w=="object"&&!Array.isArray(w)?w:void 0,f=typeof i?.storyId=="string"&&xe.test(i.storyId)?i.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const g=Object.values(d.storyWorktrees?.entries??{}).filter(s=>s.storyId===f&&s.state==="active");if(g.length!==1){r.push({storyId:f,ok:!1,reasonCode:g.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await c.sync({leaseId:g[0].leaseId,directive:w});r.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return r}export{pt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,wt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,bt as STORY_WORKTREE_WAVE_MAX_STORIES,He as digestStoryWorktreeIntegrationReceipt,St as integrateStoryWorktree,Pt as integrateStoryWorktreeWave,jt as integrateStoryWorktreesInOrder,At as storyWorktreeWaveGateRunCap,zt as syncReleasedDependents};