@ornexus/neocortex 4.61.5 → 4.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +1 -1
  5. package/package.json +5 -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.d.ts +8 -1
  20. package/packages/client/dist/agent/update-description.js +2 -260
  21. package/packages/client/dist/cache/crypto-utils.js +1 -78
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  23. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  24. package/packages/client/dist/cache/index.js +1 -13
  25. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  26. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  27. package/packages/client/dist/checkpoint/index.js +1 -11
  28. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  29. package/packages/client/dist/cli.js +5 -364
  30. package/packages/client/dist/commands/activate.js +8 -394
  31. package/packages/client/dist/commands/architecture-answers.js +7 -274
  32. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  33. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  34. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  35. package/packages/client/dist/commands/cache-status.js +2 -112
  36. package/packages/client/dist/commands/config.js +1 -88
  37. package/packages/client/dist/commands/doctor.js +2 -635
  38. package/packages/client/dist/commands/invoke.d.ts +17 -0
  39. package/packages/client/dist/commands/invoke.js +148 -7822
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  41. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  42. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  44. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  45. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  46. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  47. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  49. package/packages/client/dist/commands/mutation-qa.js +1 -220
  50. package/packages/client/dist/commands/native-agent.js +2 -136
  51. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  52. package/packages/client/dist/commands/planning-generation.js +1 -53
  53. package/packages/client/dist/commands/planning-memory.js +1 -40
  54. package/packages/client/dist/commands/planning-research.js +1 -42
  55. package/packages/client/dist/commands/private-session.js +1 -75
  56. package/packages/client/dist/commands/property-qa.js +1 -139
  57. package/packages/client/dist/commands/qa-control.js +1 -16
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  60. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  61. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  62. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  68. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  69. package/packages/client/dist/commands/refactor-commit.js +13 -399
  70. package/packages/client/dist/commands/refactor-control.js +3 -142
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  72. package/packages/client/dist/commands/refactor-review.js +5 -283
  73. package/packages/client/dist/commands/refactor-root.js +7 -588
  74. package/packages/client/dist/commands/refresh-memory.js +3 -174
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  77. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  78. package/packages/client/dist/commands/story-worktree.js +5 -258
  79. package/packages/client/dist/config/host-auth-broker.js +1 -60
  80. package/packages/client/dist/config/host-auth-reference.js +1 -93
  81. package/packages/client/dist/config/profile-directory.js +1 -13
  82. package/packages/client/dist/config/resolver-selection.js +1 -278
  83. package/packages/client/dist/config/secure-config.js +12 -281
  84. package/packages/client/dist/config.js +2 -224
  85. package/packages/client/dist/constants.js +1 -25
  86. package/packages/client/dist/context/context-collector.js +2 -222
  87. package/packages/client/dist/context/context-sanitizer.js +1 -145
  88. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  89. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  90. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  91. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  92. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  93. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  94. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  95. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  96. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  97. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  98. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  99. package/packages/client/dist/continuity/outbox.js +1 -117
  100. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  101. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  102. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  103. package/packages/client/dist/errors/error-messages.js +2 -258
  104. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  105. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  106. package/packages/client/dist/evidence/collector.js +1 -347
  107. package/packages/client/dist/evidence/index.js +1 -1
  108. package/packages/client/dist/evidence/types.js +0 -2
  109. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  110. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  111. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  112. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  113. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +94 -9
  114. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -1592
  115. package/packages/client/dist/git/epic-operational-state.js +2 -672
  116. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  117. package/packages/client/dist/git/git-lifecycle-store.d.ts +88 -0
  118. package/packages/client/dist/git/git-lifecycle-store.js +9 -2529
  119. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  120. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  121. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  122. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  123. package/packages/client/dist/git/release-gate-env.d.ts +62 -0
  124. package/packages/client/dist/git/release-gate-env.js +1 -0
  125. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  126. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -186
  127. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  128. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  129. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  130. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  131. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  132. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  133. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  134. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  135. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  136. package/packages/client/dist/i18n/first-run.js +2 -60
  137. package/packages/client/dist/index.js +1 -50
  138. package/packages/client/dist/invocation/invoke-input.js +1 -24
  139. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  140. package/packages/client/dist/license/index.js +1 -5
  141. package/packages/client/dist/license/license-client.js +1 -337
  142. package/packages/client/dist/machine/fingerprint.js +2 -163
  143. package/packages/client/dist/machine/index.js +1 -5
  144. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  145. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  146. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  147. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  148. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  149. package/packages/client/dist/migrations/project-identity.js +7 -493
  150. package/packages/client/dist/migrations/state-json.js +4 -393
  151. package/packages/client/dist/policy/architecture-policy.js +2 -184
  152. package/packages/client/dist/policy/index.js +1 -7
  153. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  154. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  155. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  156. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  157. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  158. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  159. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  160. package/packages/client/dist/private-execution/delivery.js +13 -410
  161. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  162. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  163. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  164. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  165. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  166. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  167. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  168. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  169. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  170. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  171. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  172. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  173. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  174. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  175. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  176. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  177. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  178. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  179. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  180. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  181. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  182. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  183. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  184. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  185. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  186. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  187. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  188. package/packages/client/dist/private-execution/session-lease.js +1 -63
  189. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  190. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  191. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  192. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  193. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  194. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  195. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  196. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  197. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  198. package/packages/client/dist/resilience/index.js +1 -8
  199. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  200. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  201. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  202. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  203. package/packages/client/dist/runner/binary.js +1 -404
  204. package/packages/client/dist/runner/cli.js +17 -1571
  205. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  206. package/packages/client/dist/runner/headless/adapters.js +1 -49
  207. package/packages/client/dist/runner/headless/background-root.js +1 -85
  208. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  209. package/packages/client/dist/runner/headless/child-env.js +1 -0
  210. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  211. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  212. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  213. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  214. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
  215. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  216. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  217. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  218. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  219. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  220. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  221. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  222. package/packages/client/dist/runner/headless/resolver.js +1 -231
  223. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  224. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  225. package/packages/client/dist/runner/headless/types.js +2 -575
  226. package/packages/client/dist/runner/host-capacity.js +1 -59
  227. package/packages/client/dist/runner/local-console.js +13 -396
  228. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  229. package/packages/client/dist/runner/project-identity.js +1 -106
  230. package/packages/client/dist/runner/scheduler.js +7 -995
  231. package/packages/client/dist/runner-cli.js +2 -18
  232. package/packages/client/dist/state/invocation-shape.js +1 -13
  233. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  234. package/packages/client/dist/state/state-json-repair.js +3 -785
  235. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  236. package/packages/client/dist/telemetry/index.js +1 -5
  237. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  238. package/packages/client/dist/tier/index.js +1 -5
  239. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  240. package/packages/client/dist/types/index.js +1 -38
  241. package/packages/client/dist/version.js +1 -27
  242. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  243. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  244. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  245. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  246. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  247. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  248. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  249. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  250. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  251. package/packages/client/dist/yoloop/index.js +1 -8
  252. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  253. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
  254. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  255. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  256. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  257. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  258. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  259. package/packages/shared/dist/project-manifest-projection.js +199 -0
  260. package/packages/shared/dist/project-validation-commands.js +14 -6
  261. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  262. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  263. package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
  264. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  265. package/targets-stubs/antigravity/gemini.md +1 -1
  266. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  267. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  268. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  269. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  270. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  271. package/targets-stubs/claude-code/neocortex.md +5 -5
  272. package/targets-stubs/codex/AGENTS.md +1 -1
  273. package/targets-stubs/cursor/agent.md +2 -2
  274. package/targets-stubs/gemini-cli/agent.md +2 -2
  275. package/targets-stubs/lib/managed-config-merge.js +77 -1
  276. package/targets-stubs/lib/managed-profile.sh +7 -0
  277. package/targets-stubs/opencode/neocortex-root.md +1 -1
  278. package/targets-stubs/vscode/install-vscode.sh +21 -0
  279. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,26 +1,4 @@
1
- /**
2
- * Branchless preparation sandboxes for continuous yoloop children.
3
- *
4
- * A child receives an independent Git index at a detached HEAD, but no branch
5
- * and no Git worktree are created. Only the root applies the validated result
6
- * and creates the single logical story commit on the epic branch.
7
- *
8
- * P225.09: v4 `client_managed_worktree` plans select the `story_worktree`
9
- * strategy instead; its worktree is created by the client-owned
10
- * `StoryWorktreeManager` (never by this module) and integrated root-only.
11
- */
12
- import { execFile, spawn } from 'node:child_process';
13
- import { createHash, randomBytes } from 'node:crypto';
14
- import { lstat, readFile, realpath, stat } from 'node:fs/promises';
15
- import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
16
- import { promisify } from 'node:util';
17
- import { admitPreparedStoryBundle } from './prepared-story-bundle.js';
18
- import { StoryWorktreeManager, } from '../../git/story-worktree-manager.js';
19
- import { acquireGitLifecyclePhysicalIntegrationLock, assertGitLifecyclePrivateDirectory, assertGitLifecyclePrivateFile, applyGitLifecycleRuntimeOverlay, computeImmutableStoryQaEvidenceDigest, computeP205StoryQaEvidenceDigest, ensureGitLifecyclePrivateChildDirectory, ensureRuntimeEpic, ensureRuntimeStory, gitLifecycleRuntimeDirectory, mutateGitLifecycleRuntime, P205_COMPLETE_COMMAND, readGitLifecycleRuntime, releaseGitLifecyclePhysicalIntegrationLock, removeGitLifecyclePrivateDirectory, verifyAcceptedGitLifecycleStoryCheckpoint, verifyGitLifecyclePhysicalIntegrationLock, } from '../../git/git-lifecycle-store.js';
20
- import { anchoredAtomicWriteFile, anchoredCreateDirectory, anchoredDirectoryIdentity, anchoredExecuteGit, anchoredEnsureDirectory, anchoredRemoveFile, } from '../../git/secure-filesystem-boundary.js';
21
- import { GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID, } from '../../git/git-lifecycle-step-ids.js';
22
- const execFileAsync = promisify(execFile);
23
- const ANCHORED_CHILD_HELPER = String.raw `
1
+ import{execFile as wt,spawn as Fe}from"node:child_process";import{createHash as W,randomBytes as Ve}from"node:crypto";import{lstat as ye,readFile as B,realpath as U,stat as gt}from"node:fs/promises";import{basename as $,dirname as j,isAbsolute as ke,join as C,relative as mt,resolve as Qe}from"node:path";import{promisify as St}from"node:util";import{admitPreparedStoryBundle as vt}from"./prepared-story-bundle.js";import{buildHeadlessChildEnv as It,classifyCompleteGateFailure as Rt,completeGateTimeoutMs as bt,loadHeadlessChildEnvContract as kt,projectHeadlessGateEnv as xt}from"./child-env.js";import{StoryWorktreeManager as Et}from"../../git/story-worktree-manager.js";import{acquireGitLifecyclePhysicalIntegrationLock as At,assertGitLifecyclePrivateDirectory as L,assertGitLifecyclePrivateFile as F,applyGitLifecycleRuntimeOverlay as ie,computeImmutableStoryQaEvidenceDigest as jt,computeP205StoryQaEvidenceDigest as Ct,ensureGitLifecyclePrivateChildDirectory as xe,ensureRuntimeEpic as we,ensureRuntimeStory as _t,gitLifecycleRuntimeDirectory as Ye,mutateGitLifecycleRuntime as X,P205_COMPLETE_COMMAND as Dt,readGitLifecycleRuntime as V,releaseGitLifecyclePhysicalIntegrationLock as Ot,removeGitLifecyclePrivateDirectory as ee,verifyAcceptedGitLifecycleStoryCheckpoint as Ee,verifyGitLifecyclePhysicalIntegrationLock as Ae}from"../../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as Nt,anchoredCreateDirectory as je,anchoredDirectoryIdentity as Ze,anchoredExecuteGit as Ce,anchoredEnsureDirectory as Pt,anchoredRemoveFile as Bt}from"../../git/secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ue,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ge}from"../../git/git-lifecycle-step-ids.js";const _e=St(wt),$t=String.raw`
24
2
  const fs = require('node:fs');
25
3
  const cp = require('node:child_process');
26
4
  const [expectedParentDev, expectedParentIno, name, expectedChildDev, expectedChildIno, encoded, handshake] = process.argv.slice(1);
@@ -68,1756 +46,13 @@ runtime.on('close', (code, signal) => {
68
46
  if (signal) process.kill(process.pid, signal);
69
47
  else process.exit(Number.isInteger(code) ? code : 1);
70
48
  });
71
- `;
72
- /**
73
- * Create the only command runner authorized for a continuous child. The helper
74
- * owns and revalidates the sandbox cwd before launching the runtime, so the
75
- * mutable public pathname is never reused as the runtime's cwd.
76
- */
77
- export function createAnchoredContinuousStoryCommandRunner(lease, hooks = {}) {
78
- return async (command, args, options = {}) => runAnchoredChildCommand(lease, command, args, options, hooks);
79
- }
80
- /** Default continuous-DAG workspace policy. It never creates a Git worktree. */
81
- export function createBranchlessContinuousStoryWorkspaceManager(options = {}) {
82
- let preparationTail = Promise.resolve();
83
- return {
84
- async prepare(input) {
85
- if ((options.platform ?? process.platform) === 'win32') {
86
- return failure('continuous-sandbox-platform-unsupported');
87
- }
88
- if (!/^[a-f0-9]{64}$/.test(input.dispatchId))
89
- return failure('continuous-sandbox-dispatch-invalid');
90
- if (!safeRelativePath(input.targetRef))
91
- return failure('continuous-sandbox-target-invalid');
92
- if (!safeBranch(input.executionBranch))
93
- return failure('continuous-execution-branch-invalid');
94
- if (!/^[a-f0-9]{64}$/.test(input.graphRevision))
95
- return failure('continuous-graph-revision-invalid');
96
- const authorizedWriteSet = normalizeWriteSet(input.authorizedWriteSet);
97
- if (authorizedWriteSet.length === 0 || authorizedWriteSet.length !== input.authorizedWriteSet.length) {
98
- return failure('continuous-authorized-write-set-invalid');
99
- }
100
- const claimRevision = hashCanonical(authorizedWriteSet);
101
- const previousPreparation = preparationTail;
102
- let unlockPreparation = () => undefined;
103
- preparationTail = new Promise((resolvePreparation) => { unlockPreparation = resolvePreparation; });
104
- await previousPreparation;
105
- let acquiredLeasePath;
106
- let acquiredLeaseOwner;
107
- try {
108
- const projectRoot = await canonicalRoot(input.projectRoot);
109
- const baseSha = await git(projectRoot, ['rev-parse', 'HEAD']);
110
- const graphAuthority = await readCurrentGraphAuthoritySnapshot(projectRoot, input.epicId, input.storyId);
111
- const graphAuthorityRevision = graphAuthority.revision;
112
- const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
113
- const dispatchLease = await acquireContinuousDispatchLease(runtimeDirectory, input.dispatchId, (leasePath, owner) => { acquiredLeasePath = leasePath; acquiredLeaseOwner = owner; }, options.beforeSandboxWriteCommit);
114
- if (!dispatchLease.ok)
115
- return dispatchLease;
116
- const { leasePath } = dispatchLease.value;
117
- const sandboxesRoot = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'sandboxes');
118
- const workspacePath = join(sandboxesRoot, input.dispatchId.slice(0, 20));
119
- const recovered = await readSandboxMetadata(workspacePath, sandboxesRoot);
120
- let contextSnapshots;
121
- let workspaceIdentity;
122
- const preparedAt = recovered?.preparedAt ?? new Date().toISOString();
123
- const workspaceOwnerNonce = recovered?.workspaceOwnerNonce ?? randomBytes(16).toString('hex');
124
- if (recovered) {
125
- if (recovered.projectRoot !== projectRoot || recovered.storyId !== input.storyId
126
- || recovered.targetRef !== input.targetRef || recovered.dispatchId !== input.dispatchId
127
- || recovered.epicId !== input.epicId || recovered.executionBranch !== input.executionBranch
128
- || recovered.graphRevision !== input.graphRevision || recovered.claimRevision !== claimRevision
129
- || recovered.graphAuthorityRevision !== graphAuthorityRevision
130
- || recovered.graphAuthorityEpoch !== graphAuthority.epoch
131
- || recovered.graphAuthorityStoryStatus !== graphAuthority.storyStatus
132
- || !sameStrings(recovered.authorizedWriteSet, authorizedWriteSet))
133
- return failure('continuous-sandbox-recovery-mismatch');
134
- contextSnapshots = recovered.contextSnapshots.map((snapshot) => ({
135
- path: snapshot.path,
136
- ...(snapshot.contentBase64 !== undefined ? { content: Buffer.from(snapshot.contentBase64, 'base64') } : {}),
137
- }));
138
- workspaceIdentity = await anchoredDirectoryIdentity(workspacePath);
139
- if (workspaceIdentity.dev !== recovered.workspaceIdentity.dev
140
- || workspaceIdentity.ino !== recovered.workspaceIdentity.ino) {
141
- return failure('continuous-sandbox-recovery-mismatch');
142
- }
143
- }
144
- else {
145
- await removeGitLifecyclePrivateDirectory(workspacePath, sandboxesRoot);
146
- workspaceIdentity = await anchoredCreateDirectory(sandboxesRoot, basename(workspacePath));
147
- await assertGitLifecyclePrivateDirectory(workspacePath, sandboxesRoot);
148
- await sandboxGitAt(sandboxesRoot, basename(workspacePath), workspaceIdentity, ['init', '--quiet']);
149
- await initializeBranchlessRuntimeProjection(projectRoot, workspacePath);
150
- await copyGitIdentity(projectRoot, sandboxesRoot, basename(workspacePath), workspaceIdentity);
151
- await sandboxGitAt(sandboxesRoot, basename(workspacePath), workspaceIdentity, ['remote', 'add', 'neocortex-root', projectRoot]);
152
- await sandboxGitAt(sandboxesRoot, basename(workspacePath), workspaceIdentity, ['fetch', '--quiet', '--no-tags', 'neocortex-root', baseSha]);
153
- await sandboxGitAt(sandboxesRoot, basename(workspacePath), workspaceIdentity, ['checkout', '--quiet', '--detach', 'FETCH_HEAD']);
154
- contextSnapshots = await copyCurrentContext(projectRoot, workspacePath, input.epicId, input.targetRef, options.beforeSandboxWriteCommit);
155
- await writeSandboxMetadata(workspacePath, sandboxesRoot, {
156
- schemaVersion: 1,
157
- projectRoot,
158
- storyId: input.storyId,
159
- targetRef: input.targetRef,
160
- epicId: input.epicId,
161
- executionBranch: input.executionBranch,
162
- graphRevision: input.graphRevision,
163
- graphAuthorityRevision,
164
- graphAuthorityEpoch: graphAuthority.epoch,
165
- graphAuthorityStoryStatus: graphAuthority.storyStatus,
166
- authorizedWriteSet,
167
- claimRevision,
168
- dispatchId: input.dispatchId,
169
- baseSha,
170
- preparedAt,
171
- workspaceOwnerNonce,
172
- workspaceIdentity,
173
- contextSnapshots: contextSnapshots.map((snapshot) => ({
174
- path: snapshot.path,
175
- ...(snapshot.content !== undefined ? { contentBase64: snapshot.content.toString('base64') } : {}),
176
- })),
177
- }, options.beforeSandboxWriteCommit);
178
- }
179
- acquiredLeasePath = undefined;
180
- return {
181
- ok: true,
182
- value: {
183
- projectRoot,
184
- workspacePath,
185
- workspaceStrategy: 'branchless_sandbox',
186
- storyId: input.storyId,
187
- targetRef: input.targetRef,
188
- epicId: input.epicId,
189
- executionBranch: input.executionBranch,
190
- graphRevision: input.graphRevision,
191
- graphAuthorityRevision,
192
- graphAuthorityEpoch: graphAuthority.epoch,
193
- graphAuthorityStoryStatus: graphAuthority.storyStatus,
194
- authorizedWriteSet,
195
- claimRevision,
196
- baseSha: recovered?.baseSha ?? baseSha,
197
- dispatchId: input.dispatchId,
198
- preparedAt,
199
- leasePath,
200
- leaseOwnerNonce: dispatchLease.value.owner.nonce,
201
- workspaceOwnerNonce,
202
- workspaceIdentity,
203
- contextSnapshots,
204
- },
205
- };
206
- }
207
- catch {
208
- if (acquiredLeasePath && acquiredLeaseOwner) {
209
- const cleanupLeasePath = acquiredLeasePath;
210
- const cleanupLeaseOwner = acquiredLeaseOwner;
211
- await removeGitLifecyclePrivateDirectory(cleanupLeasePath, dirname(cleanupLeasePath), async (renamed) => sameLeaseOwner(await readLeaseOwner(renamed, dirname(cleanupLeasePath)), cleanupLeaseOwner)).catch(() => undefined);
212
- }
213
- return failure('continuous-sandbox-prepare-failed');
214
- }
215
- finally {
216
- unlockPreparation();
217
- }
218
- },
219
- async integrate(lease, authority) {
220
- const leaseOwner = await readLeaseOwner(lease.leasePath, dirname(lease.leasePath)).catch(() => undefined);
221
- const sandboxOwner = await readSandboxMetadata(lease.workspacePath, dirname(lease.workspacePath)).catch(() => undefined);
222
- if (!leaseOwner || leaseOwner.nonce !== lease.leaseOwnerNonce
223
- || sandboxOwner?.workspaceOwnerNonce !== lease.workspaceOwnerNonce
224
- || sandboxOwner.dispatchId !== lease.dispatchId || sandboxOwner.storyId !== lease.storyId) {
225
- return failure('continuous-sandbox-owner-mismatch');
226
- }
227
- const lockStartedAt = normalizeEvidenceTime(authority?.nowIso ?? new Date().toISOString());
228
- const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(lease.projectRoot, {
229
- kind: 'continuous', storyId: lease.storyId, sessionId: lease.dispatchId,
230
- idempotencyKey: lease.dispatchId,
231
- expiresAt: new Date(Date.parse(lockStartedAt) + 30 * 60 * 1000).toISOString(),
232
- persistent: false, createdAt: lockStartedAt,
233
- });
234
- if (!physicalLock.ok)
235
- return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
236
- ? 'continuous-integration-backpressure' : 'continuous-integration-lease-failed');
237
- let rootSnapshots = [];
238
- let rootCommitCreated = false;
239
- let rootEffectsStarted = false;
240
- try {
241
- // Preserve the leading porcelain status column: `sandboxGit` trims it
242
- // and would misclassify an ordinary unstaged modification as staged.
243
- const sandboxStatus = (await sandboxGitRaw(lease, ['status', '--porcelain'])).trimEnd();
244
- const childHeadSha = await sandboxGit(lease, ['rev-parse', 'HEAD']);
245
- const currentBranch = await gitOptional(lease.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
246
- if (currentBranch !== lease.executionBranch)
247
- return failure('continuous-execution-branch-mismatch');
248
- const runtimeDirectory = dirname(dirname(lease.leasePath));
249
- const integratedRoot = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'integrated');
250
- const markerPath = join(integratedRoot, lease.dispatchId);
251
- const marker = await readMarker(markerPath, integratedRoot);
252
- if (marker?.childHeadSha === childHeadSha
253
- && marker.bundle.storyId === lease.storyId
254
- && marker.bundle.epicId === lease.epicId
255
- && marker.bundle.executionBranch === lease.executionBranch
256
- && marker.bundle.graphRevision === lease.graphRevision
257
- && marker.bundle.claimRevision === lease.claimRevision
258
- && sameStrings(marker.bundle.authorizedWriteSet, lease.authorizedWriteSet)
259
- && marker.checkpoint.idempotencyKey === lease.dispatchId
260
- && marker.checkpoint.bundleId === marker.bundle.bundleId
261
- && marker.checkpoint.bundleDigest === marker.bundle.bundleDigest
262
- && marker.checkpoint.graphRevision === lease.graphRevision
263
- && marker.checkpoint.claimRevision === lease.claimRevision
264
- && await gitExitOk(lease.projectRoot, ['merge-base', '--is-ancestor', marker.rootHeadSha, 'HEAD'])
265
- && await checkpointExistsInRootState(lease, marker.checkpoint)) {
266
- return {
267
- ok: true,
268
- value: {
269
- headSha: marker.rootHeadSha,
270
- alreadyIntegrated: true,
271
- bundle: marker.bundle,
272
- checkpoint: marker.checkpoint,
273
- },
274
- };
275
- }
276
- // The delegated child owns only filesystem writes. Any staged path or
277
- // commit is an attempted authority escalation; the root writer alone
278
- // stages, integrates and creates the single logical story commit.
279
- if (childHeadSha !== lease.baseSha) {
280
- return failure('continuous-sandbox-child-git-authority-denied');
281
- }
282
- if (sandboxStatus.length === 0)
283
- return failure('continuous-bundle-empty');
284
- const childStaged = sandboxStatus.split('\n')
285
- .some((line) => line.length > 0 && line[0] !== ' ' && line[0] !== '?');
286
- if (!childStaged)
287
- await sandboxGit(lease, ['add', '-A']);
288
- const changedPaths = splitNull(await sandboxGitRaw(lease, ['diff', '--cached', '--name-only', '-z', lease.baseSha]));
289
- if (changedPaths.length === 0 || changedPaths.some((path) => !safeRelativePath(path))) {
290
- return failure('continuous-integration-write-set-invalid');
291
- }
292
- if (!(await sandboxGitExitOk(lease, ['merge-base', '--is-ancestor', lease.baseSha, childHeadSha]))) {
293
- return failure('continuous-bundle-base-not-ancestor');
294
- }
295
- if (!(await gitExitOk(lease.projectRoot, ['merge-base', '--is-ancestor', lease.baseSha, 'HEAD']))) {
296
- return failure('continuous-root-base-not-ancestor');
297
- }
298
- const nowIso = authority?.nowIso ?? new Date().toISOString();
299
- const receiptRefs = normalizeReceiptRefs(authority?.receiptRefs, lease.dispatchId);
300
- const payload = await sandboxGitRaw(lease, ['diff', '--cached', '--binary', lease.baseSha]);
301
- const bundleBody = {
302
- schemaVersion: 1,
303
- storyId: lease.storyId,
304
- epicId: lease.epicId,
305
- executionBranch: lease.executionBranch,
306
- baseSha: lease.baseSha,
307
- bundleDigest: createHash('sha256').update(payload).digest('hex'),
308
- graphRevision: lease.graphRevision,
309
- claimRevision: lease.claimRevision,
310
- authorizedWriteSet: lease.authorizedWriteSet,
311
- contextDigests: Object.fromEntries(lease.contextSnapshots.map((snapshot) => [
312
- snapshot.path,
313
- createHash('sha256').update(snapshot.content ?? Buffer.alloc(0)).digest('hex'),
314
- ])),
315
- validationRefs: receiptRefs,
316
- createdAt: lease.preparedAt,
317
- expiresAt: new Date(Date.parse(lease.preparedAt) + 24 * 60 * 60 * 1000).toISOString(),
318
- branchless: true,
319
- };
320
- const bundle = Object.freeze({
321
- ...bundleBody,
322
- bundleId: hashCanonical(bundleBody),
323
- });
324
- const recoveredCommit = await findIntegratedDispatchCommit(lease, bundle);
325
- if (recoveredCommit) {
326
- const existingCheckpoint = await readMatchingRootCheckpoint(lease, bundle, recoveredCommit);
327
- if (existingCheckpoint) {
328
- await writeMarker(markerPath, childHeadSha, recoveredCommit.headSha, bundle, existingCheckpoint, options.beforeSandboxWriteCommit);
329
- return {
330
- ok: true,
331
- value: { headSha: recoveredCommit.headSha, alreadyIntegrated: true, bundle, checkpoint: existingCheckpoint },
332
- };
333
- }
334
- }
335
- if (!recoveredCommit
336
- && await readCurrentGraphAuthorityRevision(lease.projectRoot, lease.epicId) !== lease.graphAuthorityRevision) {
337
- return failure('continuous-graph-revision-stale');
338
- }
339
- if (recoveredCommit) {
340
- const evidence = await produceIndependentCheckpointEvidence({
341
- lease, bundle, baseSha: recoveredCommit.baseSha, headSha: recoveredCommit.headSha,
342
- receiptRefs, nowIso, qaRunner: options.storyQaRunner,
343
- });
344
- if (!evidence.ok)
345
- return evidence;
346
- await options.beforeCheckpointPersist?.({
347
- projectRoot: lease.projectRoot, storyId: lease.storyId, headSha: recoveredCommit.headSha,
348
- });
349
- const checkpoint = await persistRootCheckpoint({
350
- lease,
351
- physicalLock,
352
- checkpointAuthority: recoveredCommit.checkpointAuthority,
353
- bundle,
354
- baseSha: recoveredCommit.baseSha,
355
- headSha: recoveredCommit.headSha,
356
- receiptRefs: [...receiptRefs, `bundle:${bundle.bundleId}`, evidence.value.qaReceipt.receiptRef, evidence.value.reviewReceipt.receiptRef],
357
- qaReceipt: evidence.value.qaReceipt,
358
- reviewReceipt: evidence.value.reviewReceipt,
359
- recordedAt: nowIso,
360
- checkpointNow: options.checkpointNow,
361
- insideCheckpointPreCommit: options.insideCheckpointPreCommit,
362
- afterCheckpointPersist: options.afterCheckpointPersist,
363
- });
364
- if (!checkpoint.ok)
365
- return checkpoint;
366
- await writeMarker(markerPath, childHeadSha, recoveredCommit.headSha, bundle, checkpoint.value, options.beforeSandboxWriteCommit);
367
- return { ok: true, value: { headSha: recoveredCommit.headSha, alreadyIntegrated: true, bundle, checkpoint: checkpoint.value } };
368
- }
369
- // A staged index is accepted only as replay input when immutable root
370
- // evidence above proves that this exact bundle was already integrated.
371
- // It can never authorize a fresh root effect.
372
- if (childStaged)
373
- return failure('continuous-sandbox-child-git-authority-denied');
374
- const stagedPaths = splitNull(await gitRaw(lease.projectRoot, ['diff', '--cached', '--name-only', '-z']));
375
- if (stagedPaths.length > 0)
376
- return failure('continuous-integration-root-index-dirty');
377
- const managedPaths = new Set(lease.contextSnapshots.map((snapshot) => snapshot.path));
378
- const unauthorized = changedPaths.filter((path) => !lease.authorizedWriteSet.some((authorized) => writeSetCovers(authorized, path)));
379
- if (unauthorized.length > 0)
380
- return failure('continuous-bundle-write-set-unauthorized');
381
- const patchPaths = changedPaths.filter((path) => !managedPaths.has(path));
382
- const interveningPaths = new Set(splitNull(await gitRaw(lease.projectRoot, ['diff', '--name-only', '-z', `${lease.baseSha}..HEAD`])));
383
- if (patchPaths.some((path) => interveningPaths.has(path)))
384
- return failure('continuous-bundle-intervening-conflict');
385
- const dirtyPaths = new Set([
386
- ...splitNull(await gitRaw(lease.projectRoot, ['diff', '--name-only', '-z'])),
387
- ...splitNull(await gitRaw(lease.projectRoot, ['ls-files', '--others', '--exclude-standard', '-z'])),
388
- ]);
389
- if (patchPaths.some((path) => dirtyPaths.has(path)))
390
- return failure('continuous-integration-root-conflict');
391
- rootSnapshots = await snapshotPaths(lease.projectRoot, [...new Set([...changedPaths, '.neocortex/state.json'])]);
392
- const writer = await acquireRootWriterLease(lease, nowIso);
393
- if (!writer.ok)
394
- return writer;
395
- const admissionErrors = admitPreparedStoryBundle({
396
- bundle,
397
- payload: Buffer.from(payload),
398
- expected: {
399
- epicId: lease.epicId,
400
- storyId: lease.storyId,
401
- executionBranch: lease.executionBranch,
402
- baseSha: lease.baseSha,
403
- graphRevision: lease.graphRevision,
404
- claimRevision: lease.claimRevision,
405
- authorizedWriteSet: lease.authorizedWriteSet,
406
- nowIso,
407
- },
408
- writerLease: writer.value,
409
- });
410
- if (admissionErrors.length > 0) {
411
- await restoreIntegration(lease.projectRoot, rootSnapshots);
412
- return failure(`continuous-bundle-admission-${admissionErrors[0]}`);
413
- }
414
- const rootBaseSha = await git(lease.projectRoot, ['rev-parse', 'HEAD']);
415
- let checkpointAuthority;
416
- await options.beforeRootCommit?.({
417
- projectRoot: lease.projectRoot,
418
- storyId: lease.storyId,
419
- headSha: rootBaseSha,
420
- });
421
- try {
422
- await mutateGitLifecycleRuntime(lease.projectRoot, (document) => {
423
- const currentWriter = asRecordOrUndefined(ensureRuntimeEpic(document, lease.epicId).branch_lease);
424
- if (currentWriter?.ownerStoryId !== lease.storyId
425
- || currentWriter.sessionId !== lease.dispatchId
426
- || currentWriter.idempotencyKey !== lease.dispatchId
427
- || Date.parse(String(currentWriter.expiresAt)) <= Date.now()) {
428
- throw new Error('continuous-checkpoint-writer-lease-lost');
429
- }
430
- }, { preCommit: async (document) => {
431
- const currentAuthority = await readCurrentGraphAuthoritySnapshot(lease.projectRoot, lease.epicId, lease.storyId, document);
432
- if (currentAuthority.revision !== lease.graphAuthorityRevision
433
- || currentAuthority.epoch !== lease.graphAuthorityEpoch
434
- || currentAuthority.storyStatus !== lease.graphAuthorityStoryStatus) {
435
- throw new Error('continuous-graph-revision-stale');
436
- }
437
- if (!(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))) {
438
- throw new Error('continuous-integration-lock-raced');
439
- }
440
- const guardedBranch = await gitOptional(lease.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
441
- const guardedHead = await git(lease.projectRoot, ['rev-parse', 'HEAD']);
442
- if (guardedBranch !== lease.executionBranch || guardedHead !== rootBaseSha) {
443
- throw new Error('continuous-integration-head-raced');
444
- }
445
- const guardedStaged = splitNull(await gitRaw(lease.projectRoot, ['diff', '--cached', '--name-only', '-z']));
446
- const guardedDirty = new Set([
447
- ...splitNull(await gitRaw(lease.projectRoot, ['diff', '--name-only', '-z'])),
448
- ...splitNull(await gitRaw(lease.projectRoot, ['ls-files', '--others', '--exclude-standard', '-z'])),
449
- ]);
450
- if (guardedStaged.length > 0)
451
- throw new Error('continuous-integration-root-index-dirty');
452
- if (patchPaths.some((path) => guardedDirty.has(path)))
453
- throw new Error('continuous-integration-root-conflict');
454
- rootEffectsStarted = true;
455
- if (patchPaths.length > 0) {
456
- const patch = await sandboxGitRaw(lease, ['diff', '--cached', '--binary', lease.baseSha, '--', ...patchPaths]);
457
- if (patch.length > 0 && !(await gitWithInput(lease.projectRoot, ['apply', '--index', '--3way', '--whitespace=nowarn'], patch)))
458
- throw new Error('continuous-integration-conflict');
459
- }
460
- for (const snapshot of lease.contextSnapshots) {
461
- if (!changedPaths.includes(snapshot.path))
462
- continue;
463
- const current = await readOptional(join(lease.projectRoot, snapshot.path));
464
- const child = await sandboxGitIndexBlob(lease, snapshot.path);
465
- const merged = snapshot.path === '.neocortex/state.json'
466
- ? mergeJsonBuffers(snapshot.content, current, filterChildGitState(snapshot.content, child, lease.storyId))
467
- : mergeBuffers(snapshot.content, current, child);
468
- if (!merged.ok)
469
- throw new Error(snapshot.path === '.neocortex/state.json'
470
- ? 'continuous-state-merge-conflict'
471
- : 'continuous-context-merge-conflict');
472
- await writeOptional(lease.projectRoot, snapshot.path, merged.value);
473
- await git(lease.projectRoot, ['add', '-A', '--', snapshot.path]);
474
- }
475
- if (changedPaths.includes('.neocortex/state.json')) {
476
- await git(lease.projectRoot, ['add', '-A', '--', '.neocortex/state.json']);
477
- }
478
- if (await gitExitOk(lease.projectRoot, ['diff', '--cached', '--quiet'])) {
479
- throw new Error('continuous-integration-empty-after-admission');
480
- }
481
- checkpointAuthority = await readCurrentGraphAuthoritySnapshot(lease.projectRoot, lease.epicId, lease.storyId, document);
482
- await git(lease.projectRoot, [
483
- 'commit', '-m', `feat(yoloop): integrate ${lease.storyId}`,
484
- '-m', `Neocortex-Story: ${lease.storyId}`,
485
- '-m', `Neocortex-Epic: ${lease.epicId}`,
486
- '-m', `Neocortex-Execution-Branch: ${lease.executionBranch}`,
487
- '-m', `Neocortex-Prepared-Base: ${lease.baseSha}`,
488
- '-m', `Neocortex-Dispatch: ${lease.dispatchId}`,
489
- '-m', `Neocortex-Bundle: ${bundle.bundleId}`,
490
- '-m', `Neocortex-Bundle-Digest: ${bundle.bundleDigest}`,
491
- '-m', `Neocortex-Graph-Revision: ${lease.graphRevision}`,
492
- '-m', `Neocortex-Claim-Revision: ${lease.claimRevision}`,
493
- '-m', `Neocortex-Checkpoint-Authority: ${checkpointAuthority.revision}`,
494
- '-m', `Neocortex-Checkpoint-Epoch: ${checkpointAuthority.epoch ?? 'null'}`,
495
- '-m', `Neocortex-Checkpoint-Story-Status: ${checkpointAuthority.storyStatus ?? 'null'}`,
496
- ]);
497
- rootCommitCreated = true;
498
- } });
499
- }
500
- catch (error) {
501
- if (rootEffectsStarted && !rootCommitCreated)
502
- await restoreIntegration(lease.projectRoot, rootSnapshots);
503
- const reasonCode = error instanceof Error && /^continuous-/.test(error.message)
504
- ? error.message
505
- : 'continuous-integration-failed';
506
- return failure(reasonCode);
507
- }
508
- const rootHeadSha = await git(lease.projectRoot, ['rev-parse', 'HEAD']);
509
- if (!checkpointAuthority)
510
- return failure('continuous-checkpoint-authority-missing');
511
- await options.afterRootCommit?.({
512
- projectRoot: lease.projectRoot, storyId: lease.storyId, headSha: rootHeadSha,
513
- });
514
- const evidence = await produceIndependentCheckpointEvidence({
515
- lease, bundle, baseSha: rootBaseSha, headSha: rootHeadSha,
516
- receiptRefs, nowIso, qaRunner: options.storyQaRunner,
517
- });
518
- if (!evidence.ok)
519
- return evidence;
520
- await options.beforeCheckpointPersist?.({
521
- projectRoot: lease.projectRoot, storyId: lease.storyId, headSha: rootHeadSha,
522
- });
523
- const checkpoint = await persistRootCheckpoint({
524
- lease,
525
- physicalLock,
526
- checkpointAuthority,
527
- bundle,
528
- baseSha: rootBaseSha,
529
- headSha: rootHeadSha,
530
- receiptRefs: [...receiptRefs, `bundle:${bundle.bundleId}`, evidence.value.qaReceipt.receiptRef, evidence.value.reviewReceipt.receiptRef],
531
- qaReceipt: evidence.value.qaReceipt,
532
- reviewReceipt: evidence.value.reviewReceipt,
533
- recordedAt: nowIso,
534
- checkpointNow: options.checkpointNow,
535
- insideCheckpointPreCommit: options.insideCheckpointPreCommit,
536
- afterCheckpointPersist: options.afterCheckpointPersist,
537
- });
538
- if (!checkpoint.ok)
539
- return checkpoint;
540
- await writeMarker(markerPath, childHeadSha, rootHeadSha, bundle, checkpoint.value, options.beforeSandboxWriteCommit);
541
- return { ok: true, value: { headSha: rootHeadSha, alreadyIntegrated: false, bundle, checkpoint: checkpoint.value } };
542
- }
543
- catch {
544
- if (rootEffectsStarted && !rootCommitCreated && rootSnapshots.length > 0) {
545
- await restoreIntegration(lease.projectRoot, rootSnapshots);
546
- }
547
- return failure('continuous-integration-failed');
548
- }
549
- finally {
550
- await releaseRootWriterLease(lease).catch(() => undefined);
551
- await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
552
- }
553
- },
554
- async release(lease, preserveForRecovery) {
555
- if (!preserveForRecovery) {
556
- await removeGitLifecyclePrivateDirectory(lease.workspacePath, dirname(lease.workspacePath), async (renamed) => {
557
- const metadata = await readSandboxMetadata(renamed, dirname(lease.workspacePath)).catch(() => undefined);
558
- return metadata?.workspaceOwnerNonce === lease.workspaceOwnerNonce
559
- && metadata.dispatchId === lease.dispatchId && metadata.storyId === lease.storyId;
560
- });
561
- }
562
- await removeGitLifecyclePrivateDirectory(lease.leasePath, dirname(lease.leasePath), async (renamed) => {
563
- const owner = await readLeaseOwner(renamed, dirname(lease.leasePath)).catch(() => undefined);
564
- return owner?.nonce === lease.leaseOwnerNonce;
565
- });
566
- },
567
- };
568
- }
569
- /** Root-only integration (P225.07): the runner strategy never commits on `epic/<ID>`. */
570
- export const STORY_WORKTREE_INTEGRATION_ROOT_OWNED = 'story-worktree-integration-root-owned';
571
- /**
572
- * P225.09 (AC4, ADR-4): `story_worktree` strategy for v4
573
- * `client_managed_worktree` plans. It reuses the branchless dispatch lease
574
- * (`leases/<dispatchId>/owner.json`) and returns the anchored workspace
575
- * identity, so `createAnchoredContinuousStoryCommandRunner` runs the child
576
- * inside the managed worktree unchanged. Integration stays root-only through
577
- * `executeYoloopV4IntegrationOrder`; worktree removal stays with the
578
- * client-owned `story-worktree` release/cleanup lifecycle.
579
- */
580
- export function createStoryWorktreeContinuousStoryWorkspaceManager(options = {}) {
581
- const provider = options.storyWorktrees ?? ((projectRoot) => new StoryWorktreeManager({ projectRoot }));
582
- let preparationTail = Promise.resolve();
583
- return {
584
- async prepare(input) {
585
- if (!/^[a-f0-9]{64}$/.test(input.dispatchId))
586
- return failure('continuous-sandbox-dispatch-invalid');
587
- if (!safeRelativePath(input.targetRef))
588
- return failure('continuous-sandbox-target-invalid');
589
- if (!safeBranch(input.executionBranch))
590
- return failure('continuous-execution-branch-invalid');
591
- if (!/^[a-f0-9]{64}$/.test(input.graphRevision))
592
- return failure('continuous-graph-revision-invalid');
593
- const authorizedWriteSet = normalizeWriteSet(input.authorizedWriteSet);
594
- if (authorizedWriteSet.length === 0 || authorizedWriteSet.length !== input.authorizedWriteSet.length) {
595
- return failure('continuous-authorized-write-set-invalid');
596
- }
597
- const claimRevision = hashCanonical(authorizedWriteSet);
598
- const previousPreparation = preparationTail;
599
- let unlockPreparation = () => undefined;
600
- preparationTail = new Promise((resolvePreparation) => { unlockPreparation = resolvePreparation; });
601
- await previousPreparation;
602
- let acquired;
603
- try {
604
- const projectRoot = await canonicalRoot(input.projectRoot);
605
- const baseSha = await git(projectRoot, ['rev-parse', '--verify', `refs/heads/${input.executionBranch}^{commit}`]);
606
- const graphAuthority = await readCurrentGraphAuthoritySnapshot(projectRoot, input.epicId, input.storyId);
607
- const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
608
- const dispatchLease = await acquireContinuousDispatchLease(runtimeDirectory, input.dispatchId, (leasePath, owner) => { acquired = { leasePath, owner }; }, options.beforeSandboxWriteCommit);
609
- if (!dispatchLease.ok)
610
- return dispatchLease;
611
- const created = await provider(projectRoot).create({
612
- epicId: input.epicId,
613
- storyId: input.storyId,
614
- dispatchId: input.dispatchId,
615
- baseSha,
616
- graphRevision: input.graphRevision,
617
- });
618
- if (!created.ok || !created.privatePath || !isAbsolute(created.privatePath)) {
619
- // Preserve the provider reason code even if the lease release fails.
620
- acquired = undefined;
621
- await releaseContinuousDispatchLease(dispatchLease.value.leasePath, dispatchLease.value.owner.nonce)
622
- .catch(() => undefined);
623
- return failure(created.ok ? 'story-worktree-path-unavailable' : created.reasonCode);
624
- }
625
- const workspacePath = resolve(created.privatePath);
626
- const workspaceIdentity = await anchoredDirectoryIdentity(workspacePath);
627
- acquired = undefined;
628
- return {
629
- ok: true,
630
- value: {
631
- projectRoot,
632
- workspacePath,
633
- workspaceStrategy: 'story_worktree',
634
- storyWorktreeLeaseId: created.value.lease.leaseId,
635
- storyId: input.storyId,
636
- targetRef: input.targetRef,
637
- epicId: input.epicId,
638
- executionBranch: input.executionBranch,
639
- graphRevision: input.graphRevision,
640
- graphAuthorityRevision: graphAuthority.revision,
641
- graphAuthorityEpoch: graphAuthority.epoch,
642
- graphAuthorityStoryStatus: graphAuthority.storyStatus,
643
- authorizedWriteSet,
644
- claimRevision,
645
- baseSha: created.value.baseSha,
646
- preparedAt: new Date().toISOString(),
647
- dispatchId: input.dispatchId,
648
- leasePath: dispatchLease.value.leasePath,
649
- leaseOwnerNonce: dispatchLease.value.owner.nonce,
650
- workspaceOwnerNonce: dispatchLease.value.owner.nonce,
651
- workspaceIdentity,
652
- contextSnapshots: [],
653
- },
654
- };
655
- }
656
- catch {
657
- const pending = acquired;
658
- if (pending)
659
- await releaseContinuousDispatchLease(pending.leasePath, pending.owner.nonce).catch(() => undefined);
660
- return failure('story-worktree-prepare-failed');
661
- }
662
- finally {
663
- unlockPreparation();
664
- }
665
- },
666
- async integrate(lease) {
667
- if (lease.workspaceStrategy !== 'story_worktree')
668
- return failure('continuous-workspace-strategy-mismatch');
669
- return failure(STORY_WORKTREE_INTEGRATION_ROOT_OWNED);
670
- },
671
- async release(lease) {
672
- // The managed worktree is preserved for root integration (P225.07) and
673
- // client-owned cleanup (P225.05/.06); only the dispatch lease ends here.
674
- await releaseContinuousDispatchLease(lease.leasePath, lease.leaseOwnerNonce);
675
- },
676
- };
677
- }
678
- /**
679
- * P225.09 (AC4): select the runner workspace strategy from the server plan.
680
- * Only a server-authorized v4 `client_managed_worktree` plan selects
681
- * `story_worktree`; every other plan keeps the v3 `branchless_sandbox`
682
- * fallback.
683
- */
684
- export function selectContinuousStoryWorkspaceStrategy(plan) {
685
- const record = plan && typeof plan === 'object' && !Array.isArray(plan) ? plan : undefined;
686
- return record?.version === 4 && record.mode === 'two_phase_worktree_dag'
687
- && record.authorization === 'server_authorized'
688
- && record.workspaceMechanism === 'client_managed_worktree'
689
- ? 'story_worktree'
690
- : 'branchless_sandbox';
691
- }
692
- export function selectContinuousStoryWorkspaceManager(plan, managers = {}) {
693
- const strategy = selectContinuousStoryWorkspaceStrategy(plan);
694
- return strategy === 'story_worktree'
695
- ? { strategy, manager: managers.storyWorktree ?? createStoryWorktreeContinuousStoryWorkspaceManager() }
696
- : { strategy, manager: managers.branchless ?? createBranchlessContinuousStoryWorkspaceManager() };
697
- }
698
- /** Exclusive per-dispatch lease shared by both runner workspace strategies. */
699
- async function acquireContinuousDispatchLease(runtimeDirectory, dispatchId, onAcquired, beforeCommit) {
700
- const leasesRoot = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'leases');
701
- const leasePath = join(leasesRoot, dispatchId);
702
- try {
703
- await anchoredCreateDirectory(leasesRoot, dispatchId);
704
- await assertGitLifecyclePrivateDirectory(leasePath, leasesRoot);
705
- }
706
- catch (error) {
707
- if (!isNodeError(error, 'EEXIST'))
708
- throw error;
709
- await assertGitLifecyclePrivateDirectory(leasePath, leasesRoot);
710
- const owner = await readLeaseOwner(leasePath, leasesRoot);
711
- if (owner !== undefined && processExists(owner.pid))
712
- return failure('continuous-sandbox-lease-active');
713
- if (!owner || !(await removeGitLifecyclePrivateDirectory(leasePath, leasesRoot, async (renamed) => sameLeaseOwner(await readLeaseOwner(renamed, leasesRoot), owner))))
714
- return failure('continuous-sandbox-lease-owner-replaced');
715
- await anchoredCreateDirectory(leasesRoot, dispatchId);
716
- await assertGitLifecyclePrivateDirectory(leasePath, leasesRoot);
717
- }
718
- const owner = Object.freeze({
719
- pid: process.pid,
720
- createdAt: new Date().toISOString(),
721
- nonce: randomBytes(16).toString('hex'),
722
- });
723
- onAcquired(leasePath, owner);
724
- await writeOptional(leasePath, 'owner.json', Buffer.from(JSON.stringify(owner)), beforeCommit);
725
- await assertGitLifecyclePrivateFile(join(leasePath, 'owner.json'), leasePath);
726
- return { ok: true, value: { leasePath, owner } };
727
- }
728
- async function releaseContinuousDispatchLease(leasePath, ownerNonce) {
729
- await removeGitLifecyclePrivateDirectory(leasePath, dirname(leasePath), async (renamed) => {
730
- const owner = await readLeaseOwner(renamed, dirname(leasePath)).catch(() => undefined);
731
- return owner?.nonce === ownerNonce;
732
- });
733
- }
734
- async function copyCurrentContext(projectRoot, workspacePath, epicId, targetRef, beforeCommit) {
735
- const paths = [...new Set(['.neocortex/state.json', targetRef, `docs/epics/epic-${safeRef(epicId)}.md`])];
736
- const snapshots = [];
737
- for (const path of paths) {
738
- if (!safeRelativePath(path))
739
- continue;
740
- const content = await readOptional(join(projectRoot, path));
741
- snapshots.push({ path, ...(content !== undefined ? { content } : {}) });
742
- if (content !== undefined)
743
- await writeOptional(workspacePath, path, content, beforeCommit);
744
- }
745
- return snapshots;
746
- }
747
- async function canonicalRoot(projectRoot) {
748
- const root = await git(projectRoot, ['rev-parse', '--show-toplevel']);
749
- const [canonicalGitRoot, canonicalInputRoot] = await Promise.all([realpath(root), realpath(projectRoot)]);
750
- if (canonicalGitRoot !== canonicalInputRoot)
751
- throw new Error('project root mismatch');
752
- return canonicalGitRoot;
753
- }
754
- async function copyGitIdentity(projectRoot, workspaceParent, workspaceName, workspaceIdentity) {
755
- for (const key of ['user.name', 'user.email']) {
756
- const value = await gitOptional(projectRoot, ['config', '--get', key]);
757
- if (value)
758
- await sandboxGitAt(workspaceParent, workspaceName, workspaceIdentity, ['config', key, value]);
759
- }
760
- }
761
- async function initializeBranchlessRuntimeProjection(projectRoot, workspacePath) {
762
- const rootRuntime = await readGitLifecycleRuntime(projectRoot);
763
- await mutateGitLifecycleRuntime(workspacePath, (document) => {
764
- for (const [epicId, epic] of Object.entries(rootRuntime.epics)) {
765
- document.epics[epicId] = {
766
- ...structuredClone(epic),
767
- branch_lease: null,
768
- };
769
- }
770
- for (const [storyId, story] of Object.entries(rootRuntime.stories)) {
771
- document.stories[storyId] = structuredClone(story);
772
- }
773
- });
774
- }
775
- async function sandboxGitAt(workspaceParent, workspaceName, workspaceIdentity, args) {
776
- return (await anchoredExecuteGit(workspaceParent, workspaceName, workspaceIdentity, args)).toString('utf8').trim();
777
- }
778
- async function sandboxGitRaw(lease, args) {
779
- return (await anchoredExecuteGit(dirname(lease.workspacePath), basename(lease.workspacePath), lease.workspaceIdentity, args)).toString('utf8');
780
- }
781
- async function sandboxGit(lease, args) {
782
- return (await sandboxGitRaw(lease, args)).trim();
783
- }
784
- async function sandboxGitExitOk(lease, args) {
785
- try {
786
- await sandboxGit(lease, args);
787
- return true;
788
- }
789
- catch {
790
- return false;
791
- }
792
- }
793
- async function sandboxGitIndexBlob(lease, path) {
794
- try {
795
- return await anchoredExecuteGit(dirname(lease.workspacePath), basename(lease.workspacePath), lease.workspaceIdentity, ['show', `:${path}`]);
796
- }
797
- catch {
798
- return undefined;
799
- }
800
- }
801
- async function runAnchoredChildCommand(lease, command, args, options, hooks) {
802
- const startedAt = Date.now();
803
- const empty = (overrides) => ({
804
- exitCode: null, timedOut: false, durationMs: Date.now() - startedAt,
805
- stdout: '', stderr: '', stdoutBytes: 0, stderrBytes: 0, ...overrides,
806
- });
807
- if (options.signal?.aborted)
808
- return empty({ signal: 'SIGTERM', cancelled: true });
809
- if (!command || command.length > 4096 || command.includes('\0') || args.length > 512
810
- || args.some((arg) => arg.length > 32768 || arg.includes('\0'))) {
811
- return empty({ exitCode: 73, stderr: 'continuous-child-invocation-invalid', stderrBytes: 35 });
812
- }
813
- const parentPath = dirname(lease.workspacePath);
814
- const parentEntry = await lstat(parentPath, { bigint: true });
815
- const parentIdentity = await stat(parentPath, { bigint: true });
816
- if (!parentEntry.isDirectory() || parentEntry.isSymbolicLink() || !parentIdentity.isDirectory()
817
- || parentEntry.dev !== parentIdentity.dev || parentEntry.ino !== parentIdentity.ino) {
818
- return empty({ exitCode: 73, stderr: 'continuous-child-parent-invalid', stderrBytes: 31 });
819
- }
820
- await hooks.beforeHandoff?.();
821
- const encoded = Buffer.from(JSON.stringify({ command, args: [...args] })).toString('base64url');
822
- const maxOutputBytes = options.maxOutputBytes ?? 64_000;
823
- const timeoutMs = Math.max(1, Math.min(options.timeoutMs ?? 10 * 60 * 1000, 30 * 60 * 1000));
824
- return await new Promise((resolveCommand) => {
825
- const child = spawn(process.execPath, [
826
- '-e', ANCHORED_CHILD_HELPER,
827
- String(parentIdentity.dev), String(parentIdentity.ino), basename(lease.workspacePath),
828
- lease.workspaceIdentity.dev, lease.workspaceIdentity.ino, encoded, hooks.afterHandoff ? '1' : '0',
829
- ], { cwd: parentPath, env: options.env, stdio: ['pipe', 'pipe', 'pipe'] });
830
- let stdout = '';
831
- let stderr = '';
832
- let stdoutBytes = 0;
833
- let stderrBytes = 0;
834
- let settled = false;
835
- let timedOut = false;
836
- let cancelled = false;
837
- let handoffStarted = !hooks.afterHandoff;
838
- const finish = (exitCode, signal) => {
839
- if (settled)
840
- return;
841
- settled = true;
842
- clearTimeout(timer);
843
- options.signal?.removeEventListener('abort', abort);
844
- resolveCommand({
845
- exitCode, ...(signal ? { signal } : {}), timedOut, ...(cancelled ? { cancelled: true } : {}),
846
- durationMs: Date.now() - startedAt, stdout, stderr, stdoutBytes, stderrBytes,
847
- });
848
- };
849
- const abort = () => { cancelled = true; child.kill('SIGTERM'); };
850
- options.signal?.addEventListener('abort', abort, { once: true });
851
- const timer = setTimeout(() => { timedOut = true; child.kill('SIGTERM'); }, timeoutMs);
852
- child.stdout.on('data', (chunk) => {
853
- stdoutBytes += chunk.length;
854
- if (stdoutBytes + stderrBytes > maxOutputBytes)
855
- child.kill('SIGTERM');
856
- else
857
- stdout += chunk.toString('utf8');
858
- });
859
- child.stderr.on('data', (chunk) => {
860
- stderrBytes += chunk.length;
861
- if (stdoutBytes + stderrBytes > maxOutputBytes)
862
- child.kill('SIGTERM');
863
- else
864
- stderr += chunk.toString('utf8');
865
- if (!handoffStarted && stderr.includes('continuous-child-handoff-ready\n')) {
866
- handoffStarted = true;
867
- Promise.resolve(hooks.afterHandoff?.())
868
- .then(() => child.stdin.end())
869
- .catch(() => child.kill('SIGTERM'));
870
- }
871
- });
872
- child.once('error', () => finish(null));
873
- child.once('close', (code, signal) => finish(code, signal));
874
- if (!hooks.afterHandoff)
875
- child.stdin.end();
876
- });
877
- }
878
- async function git(cwd, args) {
879
- return (await gitRaw(cwd, args)).trim();
880
- }
881
- async function gitRaw(cwd, args) {
882
- const result = await execFileAsync('git', args, { cwd, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
883
- return String(result.stdout);
884
- }
885
- async function gitOptional(cwd, args) {
886
- try {
887
- return await git(cwd, args);
888
- }
889
- catch (error) {
890
- if (isNodeError(error, 'ENOENT'))
891
- return undefined;
892
- throw error;
893
- }
894
- }
895
- async function gitExitOk(cwd, args) {
896
- try {
897
- await git(cwd, args);
898
- return true;
899
- }
900
- catch {
901
- return false;
902
- }
903
- }
904
- async function gitWithInput(cwd, args, input) {
905
- return await new Promise((resolveProcess) => {
906
- const child = spawn('git', [...args], { cwd, stdio: ['pipe', 'ignore', 'ignore'] });
907
- child.once('error', () => resolveProcess(false));
908
- child.once('close', (code) => resolveProcess(code === 0));
909
- child.stdin.end(input);
910
- });
911
- }
912
- async function gitBlob(cwd, revision, path) {
913
- try {
914
- const result = await execFileAsync('git', ['show', `${revision}:${path}`], { cwd, encoding: 'buffer', maxBuffer: 16 * 1024 * 1024 });
915
- return Buffer.from(result.stdout);
916
- }
917
- catch (error) {
918
- if (isNodeError(error, 'ENOENT'))
919
- return undefined;
920
- throw error;
921
- }
922
- }
923
- async function readOptional(path) {
924
- try {
925
- return await readFile(path);
926
- }
927
- catch (error) {
928
- if (isNodeError(error, 'ENOENT'))
929
- return undefined;
930
- throw error;
931
- }
932
- }
933
- async function writeOptional(boundaryRootInput, relativePathInput, content, beforeCommit) {
934
- const relativePath = normalizeRepositoryPath(relativePathInput);
935
- if (!safeRelativePath(relativePath))
936
- throw new Error('continuous-sandbox-write-path-invalid');
937
- const boundaryRoot = await realpath(boundaryRootInput);
938
- if (boundaryRoot !== resolve(boundaryRootInput))
939
- throw new Error('continuous-sandbox-write-root-symlink');
940
- const parentRelative = dirname(relativePath) === '.' ? '' : dirname(relativePath);
941
- const parentPath = await ensureContainedDirectoryPath(boundaryRoot, parentRelative);
942
- const parentIdentity = await directoryIdentity(parentPath);
943
- const destinationPath = join(parentPath, basename(relativePath));
944
- await assertContainedDestination(destinationPath, boundaryRoot, true);
945
- if (content === undefined) {
946
- await beforeCommit?.({ boundaryRoot, relativePath, destinationPath });
947
- await assertSameDirectoryIdentity(parentPath, boundaryRoot, parentIdentity);
948
- await assertContainedDestination(destinationPath, boundaryRoot, true);
949
- await anchoredRemoveFile(parentPath, basename(relativePath));
950
- return;
951
- }
952
- await beforeCommit?.({ boundaryRoot, relativePath, destinationPath });
953
- await assertSameDirectoryIdentity(parentPath, boundaryRoot, parentIdentity);
954
- await assertContainedDestination(destinationPath, boundaryRoot, true);
955
- await anchoredAtomicWriteFile(parentPath, basename(relativePath), content);
956
- await assertContainedDestination(destinationPath, boundaryRoot, false);
957
- }
958
- async function ensureContainedDirectoryPath(boundaryRoot, relativeDirectory) {
959
- let current = boundaryRoot;
960
- for (const component of relativeDirectory.split('/').filter(Boolean)) {
961
- current = join(current, component);
962
- await anchoredEnsureDirectory(dirname(current), basename(current));
963
- const entry = await lstat(current);
964
- if (!entry.isDirectory() || entry.isSymbolicLink() || await realpath(current) !== current) {
965
- throw new Error('continuous-sandbox-write-component-unsafe');
966
- }
967
- assertPathContained(boundaryRoot, current);
968
- }
969
- return current;
970
- }
971
- async function assertContainedDestination(path, boundaryRoot, allowMissing) {
972
- assertPathContained(boundaryRoot, path);
973
- try {
974
- const entry = await lstat(path);
975
- if (entry.isSymbolicLink() || !entry.isFile())
976
- throw new Error('continuous-sandbox-write-destination-unsafe');
977
- if (await realpath(path) !== path)
978
- throw new Error('continuous-sandbox-write-destination-symlink');
979
- }
980
- catch (error) {
981
- if (allowMissing && isNodeError(error, 'ENOENT'))
982
- return;
983
- throw error;
984
- }
985
- }
986
- function assertPathContained(boundaryRoot, candidate) {
987
- const relation = relative(boundaryRoot, candidate);
988
- if (relation === '' || relation.startsWith('..') || isAbsolute(relation)) {
989
- throw new Error('continuous-sandbox-write-containment-invalid');
990
- }
991
- }
992
- async function directoryIdentity(path) {
993
- const entry = await lstat(path, { bigint: true });
994
- if (!entry.isDirectory() || entry.isSymbolicLink())
995
- throw new Error('continuous-sandbox-write-parent-unsafe');
996
- return { dev: entry.dev, ino: entry.ino };
997
- }
998
- async function sameDirectoryIdentity(path, boundaryRoot, expected) {
999
- try {
1000
- if (path !== boundaryRoot)
1001
- assertPathContained(boundaryRoot, path);
1002
- if (await realpath(path) !== path)
1003
- return false;
1004
- const current = await directoryIdentity(path);
1005
- return current.dev === expected.dev && current.ino === expected.ino;
1006
- }
1007
- catch {
1008
- return false;
1009
- }
1010
- }
1011
- async function assertSameDirectoryIdentity(path, boundaryRoot, expected) {
1012
- if (!(await sameDirectoryIdentity(path, boundaryRoot, expected))) {
1013
- throw new Error('continuous-sandbox-write-parent-raced');
1014
- }
1015
- }
1016
- async function snapshotPaths(root, paths) {
1017
- return await Promise.all(paths.map(async (path) => {
1018
- const content = await readOptional(join(root, path));
1019
- return { path, ...(content !== undefined ? { content } : {}) };
1020
- }));
1021
- }
1022
- async function restoreIntegration(root, snapshots) {
1023
- const paths = snapshots.map((snapshot) => snapshot.path);
1024
- if (paths.length > 0)
1025
- await gitExitOk(root, ['reset', '--quiet', 'HEAD', '--', ...paths]);
1026
- for (const snapshot of snapshots)
1027
- await writeOptional(root, snapshot.path, snapshot.content);
1028
- }
1029
- async function acquireRootWriterLease(lease, nowIso) {
1030
- try {
1031
- const statePath = join(lease.projectRoot, '.neocortex/state.json');
1032
- const tracked = asRecord(JSON.parse((await readFile(statePath)).toString('utf8')));
1033
- const legacyEpic = asRecordOrUndefined(asRecordOrUndefined(tracked.epics)?.[lease.epicId]);
1034
- const legacyLease = asRecordOrUndefined(legacyEpic?.branch_lease);
1035
- const requested = Object.freeze({
1036
- schemaVersion: 1,
1037
- ownerStoryId: lease.storyId,
1038
- sessionId: lease.dispatchId,
1039
- idempotencyKey: lease.dispatchId,
1040
- acquiredAt: nowIso,
1041
- expiresAt: new Date(Date.parse(nowIso) + 10 * 60 * 1000).toISOString(),
1042
- });
1043
- let blocked = false;
1044
- await mutateGitLifecycleRuntime(lease.projectRoot, (document) => {
1045
- const epic = ensureRuntimeEpic(document, lease.epicId);
1046
- const current = asRecordOrUndefined(epic.branch_lease) ?? legacyLease;
1047
- if (current && typeof current.expiresAt === 'string' && current.expiresAt > nowIso
1048
- && (current.ownerStoryId !== lease.storyId || current.idempotencyKey !== lease.dispatchId)) {
1049
- blocked = true;
1050
- return;
1051
- }
1052
- epic.branch_mode = 'epic';
1053
- epic.execution_branch = lease.executionBranch;
1054
- epic.branch_lease = requested;
1055
- });
1056
- if (blocked)
1057
- return failure('continuous-epic-checkout-writer-active');
1058
- return { ok: true, value: requested };
1059
- }
1060
- catch {
1061
- return failure('continuous-writer-lease-persist-failed');
1062
- }
1063
- }
1064
- async function releaseRootWriterLease(lease) {
1065
- await mutateGitLifecycleRuntime(lease.projectRoot, (document) => {
1066
- const epic = ensureRuntimeEpic(document, lease.epicId);
1067
- const current = asRecordOrUndefined(epic.branch_lease);
1068
- if (current?.ownerStoryId === lease.storyId && current.idempotencyKey === lease.dispatchId)
1069
- epic.branch_lease = null;
1070
- });
1071
- }
1072
- async function persistRootCheckpoint(input) {
1073
- try {
1074
- const statePath = join(input.lease.projectRoot, '.neocortex/state.json');
1075
- const checkpoint = Object.freeze({
1076
- schemaVersion: 1,
1077
- storyId: input.lease.storyId,
1078
- epicId: input.lease.epicId,
1079
- branch: input.lease.executionBranch,
1080
- baseSha: input.baseSha,
1081
- headSha: input.headSha,
1082
- commits: Object.freeze([input.headSha]),
1083
- idempotencyKey: input.lease.dispatchId,
1084
- dispatchId: input.lease.dispatchId,
1085
- bundleId: input.bundle.bundleId,
1086
- bundleDigest: input.bundle.bundleDigest,
1087
- graphRevision: input.lease.graphRevision,
1088
- claimRevision: input.lease.claimRevision,
1089
- receiptRefs: Object.freeze([...new Set(input.receiptRefs)]),
1090
- qaVerdict: 'passed',
1091
- reviewVerdict: 'approved',
1092
- qaReceipt: input.qaReceipt,
1093
- reviewReceipt: input.reviewReceipt,
1094
- recordedAt: input.recordedAt,
1095
- });
1096
- const tracked = asRecord(JSON.parse((await readFile(statePath)).toString('utf8')));
1097
- const trackedStory = asRecordOrUndefined(asRecordOrUndefined(tracked.stories)?.[input.lease.storyId]);
1098
- let outcome = 'persisted';
1099
- let reused;
1100
- let writerAtCas;
1101
- let authorityRuntimeAtCas;
1102
- let storyAtCasBefore;
1103
- let storyAtCasExisted = false;
1104
- let epicLeaseAtCasBefore;
1105
- const physicalGuard = async (candidate, runtimeDocument, trackedDocument) => {
1106
- const currentBranch = await gitOptional(input.lease.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
1107
- const currentHead = await git(input.lease.projectRoot, ['rev-parse', 'HEAD']);
1108
- if (currentBranch !== input.lease.executionBranch || currentHead !== input.headSha) {
1109
- throw new Error('continuous-checkpoint-head-raced');
1110
- }
1111
- if (candidate.graphRevision !== input.lease.graphRevision
1112
- || candidate.claimRevision !== input.lease.claimRevision
1113
- || candidate.bundleId !== input.bundle.bundleId
1114
- || candidate.bundleDigest !== input.bundle.bundleDigest) {
1115
- throw new Error('continuous-checkpoint-graph-raced');
1116
- }
1117
- const currentTracked = trackedDocument
1118
- ?? asRecord(JSON.parse((await readFile(statePath)).toString('utf8')));
1119
- const effective = applyGitLifecycleRuntimeOverlay(currentTracked, runtimeDocument ?? await readGitLifecycleRuntime(input.lease.projectRoot));
1120
- const currentEpic = asRecordOrUndefined(asRecordOrUndefined(effective.epics)?.[input.lease.epicId]);
1121
- const currentStory = asRecordOrUndefined(asRecordOrUndefined(effective.stories)?.[input.lease.storyId]);
1122
- const dependencies = Array.isArray(currentStory?.depends_on)
1123
- ? currentStory.depends_on.filter((value) => typeof value === 'string')
1124
- : [];
1125
- const effectiveStories = asRecordOrUndefined(effective.stories);
1126
- if (currentEpic?.execution_branch !== input.lease.executionBranch
1127
- || dependencies.some((dependencyId) => {
1128
- const dependency = asRecordOrUndefined(effectiveStories?.[dependencyId]);
1129
- return !dependency || !['done', 'completed', 'merged'].includes(String(dependency.status));
1130
- })) {
1131
- throw new Error('continuous-checkpoint-dependency-raced');
1132
- }
1133
- const changedPaths = splitNull(await gitRaw(input.lease.projectRoot, [
1134
- 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', input.headSha,
1135
- ]));
1136
- if (changedPaths.length === 0
1137
- || changedPaths.some((path) => !input.lease.authorizedWriteSet.some((scope) => writeSetCovers(scope, path)))) {
1138
- throw new Error('continuous-checkpoint-write-set-raced');
1139
- }
1140
- if (!(await verifyAcceptedGitLifecycleStoryCheckpoint(input.lease.projectRoot, candidate, input.lease.storyId, input.lease.epicId, input.lease.executionBranch, undefined, input.lease.authorizedWriteSet)))
1141
- throw new Error('continuous-checkpoint-receipt-revalidation-failed');
1142
- };
1143
- const runtimeBefore = await readGitLifecycleRuntime(input.lease.projectRoot, { required: true });
1144
- const writerBefore = asRecordOrUndefined(asRecordOrUndefined(runtimeBefore.epics[input.lease.epicId])?.branch_lease);
1145
- if (writerBefore?.ownerStoryId !== input.lease.storyId
1146
- || writerBefore.idempotencyKey !== input.lease.dispatchId
1147
- || writerBefore.sessionId !== input.lease.dispatchId
1148
- || typeof writerBefore.expiresAt !== 'string'
1149
- || Date.parse(writerBefore.expiresAt) <= (input.checkpointNow?.('before-mutation') ?? Date.now())) {
1150
- return failure('continuous-checkpoint-writer-lease-lost');
1151
- }
1152
- if (!(await verifyGitLifecyclePhysicalIntegrationLock(input.physicalLock.path, input.physicalLock.owner))) {
1153
- return failure('continuous-checkpoint-integration-lock-raced');
1154
- }
1155
- const trackedAuthorityBytes = await readFile(statePath);
1156
- const trackedAuthorityDigest = createHash('sha256').update(trackedAuthorityBytes).digest('hex');
1157
- await physicalGuard(checkpoint, runtimeBefore);
1158
- const authorityBefore = currentGraphAuthoritySnapshot(asRecord(JSON.parse(trackedAuthorityBytes.toString('utf8'))), runtimeBefore, input.lease.epicId, input.lease.storyId);
1159
- if (authorityBefore.revision !== input.checkpointAuthority.revision
1160
- || authorityBefore.epoch !== input.checkpointAuthority.epoch
1161
- || authorityBefore.storyStatus !== input.checkpointAuthority.storyStatus) {
1162
- return failure('continuous-graph-revision-stale');
1163
- }
1164
- const persistedMutation = await mutateGitLifecycleRuntime(input.lease.projectRoot, (document) => {
1165
- const epic = ensureRuntimeEpic(document, input.lease.epicId);
1166
- const writer = asRecordOrUndefined(epic.branch_lease);
1167
- writerAtCas = writer === undefined ? undefined : structuredClone(writer);
1168
- authorityRuntimeAtCas = structuredClone(document);
1169
- storyAtCasExisted = document.stories[input.lease.storyId] !== undefined;
1170
- storyAtCasBefore = structuredClone(document.stories[input.lease.storyId] ?? {});
1171
- epicLeaseAtCasBefore = structuredClone(epic.branch_lease);
1172
- const story = ensureRuntimeStory(document, input.lease.storyId);
1173
- const existing = asRecordOrUndefined(story.checkpoint) ?? asRecordOrUndefined(trackedStory?.checkpoint);
1174
- if (existing?.idempotencyKey === input.lease.dispatchId) {
1175
- if (existing.baseSha !== input.baseSha || existing.headSha !== input.headSha
1176
- || existing.bundleId !== input.bundle.bundleId
1177
- || existing.bundleDigest !== input.bundle.bundleDigest
1178
- || existing.graphRevision !== input.lease.graphRevision
1179
- || existing.claimRevision !== input.lease.claimRevision) {
1180
- outcome = 'conflict';
1181
- }
1182
- else {
1183
- outcome = 'reused';
1184
- reused = existing;
1185
- epic.branch_lease = null;
1186
- }
1187
- return;
1188
- }
1189
- if (writer?.ownerStoryId !== input.lease.storyId
1190
- || writer.idempotencyKey !== input.lease.dispatchId
1191
- || writer.sessionId !== input.lease.dispatchId) {
1192
- outcome = 'lease-lost';
1193
- return;
1194
- }
1195
- story.checkpoint = checkpoint;
1196
- story.status = 'done';
1197
- story.last_step = GIT_LIFECYCLE_REVIEW_PR_STEP_ID;
1198
- const steps = Array.isArray(story.steps_completed) ? story.steps_completed.filter((item) => typeof item === 'string') : [];
1199
- story.steps_completed = [...new Set([...steps, GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID])];
1200
- epic.branch_lease = null;
1201
- }, {
1202
- expectedRevision: runtimeBefore.revision,
1203
- preCommit: async (document) => {
1204
- if (writerAtCas?.ownerStoryId !== input.lease.storyId
1205
- || writerAtCas.idempotencyKey !== input.lease.dispatchId
1206
- || writerAtCas.sessionId !== input.lease.dispatchId
1207
- || typeof writerAtCas.expiresAt !== 'string'
1208
- || Date.parse(writerAtCas.expiresAt) <= (input.checkpointNow?.('pre-commit') ?? Date.now())) {
1209
- throw new Error('continuous-checkpoint-writer-lease-lost');
1210
- }
1211
- await input.insideCheckpointPreCommit?.({
1212
- projectRoot: input.lease.projectRoot,
1213
- storyId: input.lease.storyId,
1214
- headSha: input.headSha,
1215
- });
1216
- if (!(await verifyGitLifecyclePhysicalIntegrationLock(input.physicalLock.path, input.physicalLock.owner))) {
1217
- throw new Error('continuous-checkpoint-integration-lock-raced');
1218
- }
1219
- await physicalGuard(reused ?? checkpoint, document);
1220
- const finalTrackedBytes = await readFile(statePath);
1221
- if (createHash('sha256').update(finalTrackedBytes).digest('hex') !== trackedAuthorityDigest) {
1222
- throw new Error('continuous-graph-revision-stale');
1223
- }
1224
- if (!authorityRuntimeAtCas)
1225
- throw new Error('continuous-checkpoint-authority-missing');
1226
- const finalTracked = asRecord(JSON.parse(finalTrackedBytes.toString('utf8')));
1227
- const authorityAtCas = currentGraphAuthoritySnapshot(finalTracked, authorityRuntimeAtCas, input.lease.epicId, input.lease.storyId);
1228
- if (authorityAtCas.revision !== input.checkpointAuthority.revision
1229
- || authorityAtCas.epoch !== input.checkpointAuthority.epoch
1230
- || authorityAtCas.storyStatus !== input.checkpointAuthority.storyStatus) {
1231
- throw new Error('continuous-graph-revision-stale');
1232
- }
1233
- if (outcome === 'persisted'
1234
- && !exactPersistedCheckpointProjection(finalTracked, document, input.lease, checkpoint)) {
1235
- throw new Error('continuous-checkpoint-projection-raced');
1236
- }
1237
- },
1238
- });
1239
- // The outcome is assigned inside the serialized mutation callback. TypeScript
1240
- // does not model writes performed by a callback, so re-widen it here.
1241
- const finalOutcome = outcome;
1242
- if (finalOutcome === 'conflict')
1243
- return failure('continuous-checkpoint-idempotency-conflict');
1244
- if (finalOutcome === 'lease-lost')
1245
- return failure('continuous-checkpoint-writer-lease-lost');
1246
- if (finalOutcome === 'reused' && reused) {
1247
- try {
1248
- await physicalGuard(reused);
1249
- return { ok: true, value: reused };
1250
- }
1251
- catch {
1252
- return failure('continuous-checkpoint-reused-evidence-invalid');
1253
- }
1254
- }
1255
- try {
1256
- await input.afterCheckpointPersist?.({
1257
- projectRoot: input.lease.projectRoot,
1258
- storyId: input.lease.storyId,
1259
- headSha: input.headSha,
1260
- });
1261
- const runtimeAfterPersist = await readGitLifecycleRuntime(input.lease.projectRoot, { required: true });
1262
- if (runtimeAfterPersist.revision !== persistedMutation.document.revision) {
1263
- throw new Error('continuous-checkpoint-post-persist-runtime-raced');
1264
- }
1265
- await physicalGuard(checkpoint, runtimeAfterPersist);
1266
- const finalTrackedBytes = await readFile(statePath);
1267
- if (createHash('sha256').update(finalTrackedBytes).digest('hex') !== trackedAuthorityDigest) {
1268
- throw new Error('continuous-checkpoint-post-persist-authority-raced');
1269
- }
1270
- const finalTracked = asRecord(JSON.parse(finalTrackedBytes.toString('utf8')));
1271
- if (!exactPersistedCheckpointProjection(finalTracked, runtimeAfterPersist, input.lease, checkpoint)) {
1272
- throw new Error('continuous-checkpoint-post-persist-projection-raced');
1273
- }
1274
- }
1275
- catch {
1276
- const cleanupTrackedBytes = await readFile(statePath).catch(() => undefined);
1277
- const trackedAuthorityChanged = cleanupTrackedBytes === undefined
1278
- || createHash('sha256').update(cleanupTrackedBytes).digest('hex') !== trackedAuthorityDigest;
1279
- await mutateGitLifecycleRuntime(input.lease.projectRoot, (document) => {
1280
- const epic = asRecordOrUndefined(document.epics[input.lease.epicId]);
1281
- const story = asRecordOrUndefined(document.stories[input.lease.storyId]);
1282
- const cleanupTracked = cleanupTrackedBytes === undefined
1283
- ? undefined
1284
- : asRecord(JSON.parse(cleanupTrackedBytes.toString('utf8')));
1285
- if (!epic || !story || !cleanupTracked
1286
- || !exactPersistedCheckpointProjection(cleanupTracked, document, input.lease, checkpoint)) {
1287
- throw new Error('continuous-checkpoint-cleanup-cas-conflict');
1288
- }
1289
- if (trackedAuthorityChanged) {
1290
- if (storyAtCasExisted)
1291
- restoreRecord(story, storyAtCasBefore ?? {});
1292
- else
1293
- delete document.stories[input.lease.storyId];
1294
- if (epicLeaseAtCasBefore === undefined)
1295
- delete epic.branch_lease;
1296
- else
1297
- epic.branch_lease = structuredClone(epicLeaseAtCasBefore);
1298
- return;
1299
- }
1300
- story.checkpoint = null;
1301
- story.status = 'blocked';
1302
- epic.branch_lease = null;
1303
- }, { expectedRevision: persistedMutation.document.revision }).catch(() => undefined);
1304
- return failure('continuous-checkpoint-post-persist-raced');
1305
- }
1306
- return { ok: true, value: checkpoint };
1307
- }
1308
- catch (error) {
1309
- const reasonCode = error instanceof Error && /^continuous-/.test(error.message)
1310
- ? error.message
1311
- : 'continuous-checkpoint-persist-failed';
1312
- return failure(reasonCode);
1313
- }
1314
- }
1315
- async function produceIndependentCheckpointEvidence(input) {
1316
- try {
1317
- if (await git(input.lease.projectRoot, ['rev-parse', 'HEAD']) !== input.headSha) {
1318
- return failure('continuous-story-evidence-head-raced');
1319
- }
1320
- const manifestRaw = await readFile(join(input.lease.projectRoot, 'config', 'release-gates.v2.json'), 'utf8');
1321
- const manifest = JSON.parse(manifestRaw);
1322
- const gateIds = Array.isArray(manifest.requiredCompleteClasses)
1323
- ? manifest.requiredCompleteClasses.filter((item) => typeof item === 'string' && /^[a-z0-9-]+$/.test(item))
1324
- : [];
1325
- if (manifest.contract !== 'P205-CI-02' || gateIds.length === 0) {
1326
- return failure('continuous-story-qa-manifest-invalid');
1327
- }
1328
- const qaOutput = String((await execFileAsync(process.execPath, ['scripts/test-root.mjs', '--gate', 'complete'], {
1329
- cwd: input.lease.projectRoot,
1330
- encoding: 'utf8',
1331
- maxBuffer: 32 * 1024 * 1024,
1332
- })).stdout);
1333
- await input.qaRunner?.({ projectRoot: input.lease.projectRoot, storyId: input.lease.storyId, headSha: input.headSha });
1334
- if (await git(input.lease.projectRoot, ['rev-parse', 'HEAD']) !== input.headSha) {
1335
- return failure('continuous-story-qa-head-raced');
1336
- }
1337
- const checkedAt = normalizeEvidenceTime(input.nowIso);
1338
- const commitCount = await git(input.lease.projectRoot, ['rev-list', '--count', `${input.baseSha}..${input.headSha}`]);
1339
- const commitBody = await gitRaw(input.lease.projectRoot, ['show', '--no-patch', '--format=%H%n%P%n%B', input.headSha]);
1340
- const changedPaths = splitNull(await gitRaw(input.lease.projectRoot, ['diff', '--name-only', '-z', `${input.baseSha}..${input.headSha}`]));
1341
- const gitEvidenceDigest = computeImmutableStoryQaEvidenceDigest({
1342
- storyId: input.lease.storyId, baseSha: input.baseSha, headSha: input.headSha,
1343
- bundleDigest: input.bundle.bundleDigest, graphRevision: input.lease.graphRevision,
1344
- commitBody, changedPaths,
1345
- });
1346
- const manifestDigest = createHash('sha256').update(manifestRaw).digest('hex');
1347
- const resultDigest = createHash('sha256').update(qaOutput).digest('hex');
1348
- const qaSourceDigest = computeP205StoryQaEvidenceDigest({
1349
- gitEvidenceDigest, headSha: input.headSha, graphRevision: input.lease.graphRevision,
1350
- manifestDigest, gateIds, resultDigest,
1351
- });
1352
- const qaReceiptRef = `story-qa:${qaSourceDigest}`;
1353
- const qaReceipt = Object.freeze({
1354
- schemaVersion: 1, kind: 'story_qa_evidence', producer: 'local-yolo-tdd', evidenceVersion: 'p205-execution-v2',
1355
- storyId: input.lease.storyId, epicId: input.lease.epicId,
1356
- baseSha: input.baseSha, headSha: input.headSha,
1357
- bundleDigest: input.bundle.bundleDigest, graphRevision: input.lease.graphRevision,
1358
- contract: 'P205-CI-02', command: P205_COMPLETE_COMMAND,
1359
- manifestDigest, gateIds: Object.freeze(gateIds), resultDigest,
1360
- sourceEvidenceDigest: qaSourceDigest, verdict: 'passed', checkedAt, receiptRef: qaReceiptRef,
1361
- });
1362
- const trailers = [
1363
- `Neocortex-Story: ${input.lease.storyId}`,
1364
- `Neocortex-Epic: ${input.lease.epicId}`,
1365
- `Neocortex-Bundle-Digest: ${input.bundle.bundleDigest}`,
1366
- `Neocortex-Graph-Revision: ${input.lease.graphRevision}`,
1367
- ];
1368
- if (commitCount !== '1' || !trailers.every((trailer) => commitBody.includes(trailer))
1369
- || changedPaths.length === 0
1370
- || changedPaths.some((path) => !input.lease.authorizedWriteSet.some((authorized) => writeSetCovers(authorized, path)))) {
1371
- return failure('continuous-story-review-evidence-rejected');
1372
- }
1373
- const reviewSourceDigest = createHash('sha256').update([
1374
- 'root-commit-range-review-v1', input.lease.storyId, input.baseSha, input.headSha,
1375
- input.bundle.bundleDigest, input.lease.graphRevision, qaReceiptRef,
1376
- createHash('sha256').update(commitBody).digest('hex'), [...changedPaths].sort().join(','),
1377
- ].join('\0')).digest('hex');
1378
- const reviewReceiptRef = `story-review:${reviewSourceDigest}`;
1379
- const reviewReceipt = Object.freeze({
1380
- schemaVersion: 1, kind: 'story_review_evidence', producer: 'root-commit-range-review',
1381
- storyId: input.lease.storyId, epicId: input.lease.epicId,
1382
- baseSha: input.baseSha, headSha: input.headSha,
1383
- bundleDigest: input.bundle.bundleDigest, graphRevision: input.lease.graphRevision,
1384
- sourceEvidenceDigest: reviewSourceDigest, qaReceiptRef,
1385
- verdict: 'approved', reviewedAt: checkedAt, receiptRef: reviewReceiptRef,
1386
- });
1387
- return { ok: true, value: { qaReceipt, reviewReceipt } };
1388
- }
1389
- catch {
1390
- return failure('continuous-story-evidence-production-failed');
1391
- }
1392
- }
1393
- function normalizeEvidenceTime(value) {
1394
- return Number.isFinite(Date.parse(value)) ? new Date(Date.parse(value)).toISOString() : new Date().toISOString();
1395
- }
1396
- function filterChildGitState(baseContent, childContent, storyId) {
1397
- if (childContent === undefined)
1398
- return undefined;
1399
- try {
1400
- const base = baseContent === undefined ? {} : asRecord(JSON.parse(baseContent.toString('utf8')));
1401
- const untrustedChild = asRecord(JSON.parse(childContent.toString('utf8')));
1402
- const child = structuredClone(base);
1403
- const baseStory = asRecordOrUndefined(asRecordOrUndefined(base.stories)?.[storyId]);
1404
- const untrustedStory = asRecordOrUndefined(asRecordOrUndefined(untrustedChild.stories)?.[storyId]);
1405
- const stories = ensureRecord(child, 'stories');
1406
- const childStory = structuredClone(baseStory ?? {});
1407
- for (const field of [
1408
- 'status', 'last_step', 'steps_completed', 'last_updated', 'blocked_reason',
1409
- 'blocked_at', 'implementation_evidence', 'validation_evidence', 'qa_gate',
1410
- ]) {
1411
- if (untrustedStory && Object.prototype.hasOwnProperty.call(untrustedStory, field)) {
1412
- childStory[field] = structuredClone(untrustedStory[field]);
1413
- }
1414
- }
1415
- stories[storyId] = childStory;
1416
- return Buffer.from(`${JSON.stringify(child, null, 2)}\n`);
1417
- }
1418
- catch {
1419
- return Buffer.from('{invalid-child-state');
1420
- }
1421
- }
1422
- function ensureRecord(parent, key) {
1423
- const current = asRecordOrUndefined(parent[key]);
1424
- if (current)
1425
- return current;
1426
- const created = {};
1427
- parent[key] = created;
1428
- return created;
1429
- }
1430
- function asRecord(value) {
1431
- if (!value || typeof value !== 'object' || Array.isArray(value))
1432
- throw new Error('record expected');
1433
- return value;
1434
- }
1435
- function asRecordOrUndefined(value) {
1436
- return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
1437
- }
1438
- function mergeBuffers(base, root, child) {
1439
- if (sameBuffer(child, base) || sameBuffer(root, child))
1440
- return { ok: true, value: root };
1441
- if (sameBuffer(root, base))
1442
- return { ok: true, value: child };
1443
- return failure('continuous-context-merge-conflict');
1444
- }
1445
- function mergeJsonBuffers(base, root, child) {
1446
- try {
1447
- const merged = mergeJsonValue(parseJson(base), parseJson(root), parseJson(child));
1448
- return merged.ok ? { ok: true, value: merged.value === undefined ? undefined : Buffer.from(`${JSON.stringify(merged.value, null, 2)}\n`) } : merged;
1449
- }
1450
- catch {
1451
- return failure('continuous-state-merge-invalid');
1452
- }
1453
- }
1454
- function parseJson(value) {
1455
- return value === undefined ? undefined : JSON.parse(value.toString('utf8'));
1456
- }
1457
- function mergeJsonValue(base, root, child) {
1458
- if (sameJson(child, base) || sameJson(root, child))
1459
- return { ok: true, value: root };
1460
- if (sameJson(root, base))
1461
- return { ok: true, value: child };
1462
- if (isPlainRecord(base) && isPlainRecord(root) && isPlainRecord(child)) {
1463
- const merged = {};
1464
- for (const key of [...new Set([...Object.keys(base), ...Object.keys(root), ...Object.keys(child)])].sort()) {
1465
- const value = mergeJsonValue(base[key], root[key], child[key]);
1466
- if (!value.ok)
1467
- return value;
1468
- if (value.value !== undefined)
1469
- merged[key] = value.value;
1470
- }
1471
- return { ok: true, value: merged };
1472
- }
1473
- if (Array.isArray(base) && Array.isArray(root) && Array.isArray(child) && isJsonPrefix(base, root) && isJsonPrefix(base, child)) {
1474
- const values = [...base, ...root.slice(base.length), ...child.slice(base.length)];
1475
- const seen = new Set();
1476
- return { ok: true, value: values.filter((item) => {
1477
- const key = JSON.stringify(item);
1478
- if (seen.has(key))
1479
- return false;
1480
- seen.add(key);
1481
- return true;
1482
- }) };
1483
- }
1484
- return failure('continuous-state-merge-conflict');
1485
- }
1486
- function isPlainRecord(value) {
1487
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
1488
- }
1489
- function isJsonPrefix(prefix, value) {
1490
- return prefix.length <= value.length && prefix.every((item, index) => sameJson(item, value[index]));
1491
- }
1492
- function sameJson(left, right) {
1493
- return JSON.stringify(left) === JSON.stringify(right);
1494
- }
1495
- function sameBuffer(left, right) {
1496
- return left === undefined || right === undefined ? left === right : left.equals(right);
1497
- }
1498
- function splitNull(value) {
1499
- return value.split('\0').filter(Boolean);
1500
- }
1501
- function safeRelativePath(value) {
1502
- const normalized = normalizeRepositoryPath(value);
1503
- return normalized.length > 0 && normalized.length <= 1024 && !isAbsolute(normalized)
1504
- && !/^[A-Za-z]:\//.test(normalized) && !normalized.split('/').includes('..')
1505
- && !normalized.includes('\0') && !normalized.startsWith('/');
1506
- }
1507
- function normalizeRepositoryPath(value) {
1508
- return value.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/{2,}/g, '/');
1509
- }
1510
- function normalizeWriteSet(values) {
1511
- const normalized = values.map(normalizeRepositoryPath).filter(safeRelativePath);
1512
- return [...new Set(normalized)].sort();
1513
- }
1514
- function writeSetCovers(authorized, changed) {
1515
- const scope = normalizeRepositoryPath(authorized);
1516
- const path = normalizeRepositoryPath(changed);
1517
- return scope === path || scope.endsWith('/') && path.startsWith(scope);
1518
- }
1519
- function safeBranch(value) {
1520
- return value.length > 0 && value.length <= 240 && !value.startsWith('-') && !value.startsWith('/')
1521
- && !value.endsWith('/') && !value.endsWith('.lock') && !value.includes('..') && !value.includes('\\')
1522
- && !value.includes('@{') && !value.includes('//') && /^[A-Za-z0-9._/-]+$/.test(value);
1523
- }
1524
- function sameStrings(left, right) {
1525
- return left.length === right.length && left.every((value, index) => value === right[index]);
1526
- }
1527
- async function readCurrentGraphAuthoritySnapshot(projectRoot, epicId, storyId, runtimeDocument) {
1528
- const tracked = asRecord(JSON.parse(await readFile(join(projectRoot, '.neocortex/state.json'), 'utf8')));
1529
- return currentGraphAuthoritySnapshot(tracked, runtimeDocument ?? await readGitLifecycleRuntime(projectRoot), epicId, storyId);
1530
- }
1531
- function currentGraphAuthoritySnapshot(tracked, runtimeDocument, epicId, storyId) {
1532
- const effective = applyGitLifecycleRuntimeOverlay(tracked, runtimeDocument);
1533
- const epics = asRecordOrUndefined(effective.epics);
1534
- const stories = asRecordOrUndefined(effective.stories);
1535
- const epic = asRecordOrUndefined(epics?.[epicId]) ?? {};
1536
- const authoredStoryIds = (Array.isArray(epic.stories) ? epic.stories : Array.isArray(epic.story_ids) ? epic.story_ids : [])
1537
- .filter((value) => typeof value === 'string');
1538
- const storyIds = authoredStoryIds.length > 0
1539
- ? authoredStoryIds
1540
- : Object.entries(stories ?? {})
1541
- .filter(([storyId, value]) => {
1542
- const story = asRecordOrUndefined(value);
1543
- return story?.epic_id === epicId || storyId.startsWith(`${epicId}.`);
1544
- })
1545
- .map(([storyId]) => storyId)
1546
- .sort();
1547
- const authorityFields = [
1548
- 'status', 'depends_on', 'files_to_modify', 'contracts', 'contract_refs', 'shared_surfaces',
1549
- 'steps_completed', 'last_step', 'branch_name', 'physicalMergeStatus', 'merged', 'checkpoint',
1550
- 'planning', 'attempts', 'retry_count', 'rollback_receipt', 'cancelled_at',
1551
- ];
1552
- const storyAuthority = Object.fromEntries(storyIds.map((storyId) => {
1553
- const story = asRecordOrUndefined(stories?.[storyId]) ?? {};
1554
- return [storyId, Object.fromEntries(authorityFields
1555
- .filter((field) => Object.prototype.hasOwnProperty.call(story, field))
1556
- .map((field) => [field, story[field]]))];
1557
- }));
1558
- return {
1559
- revision: hashCanonical({
1560
- epicId,
1561
- epic: {
1562
- stories: storyIds,
1563
- status: epic.status ?? null,
1564
- branch_mode: epic.branch_mode ?? null,
1565
- execution_branch: epic.execution_branch ?? null,
1566
- graph_revision: epic.graph_revision ?? null,
1567
- depends_on: epic.depends_on ?? null,
1568
- planning: epic.planning ?? null,
1569
- execution_plan: epic.execution_plan ?? null,
1570
- waves: epic.waves ?? null,
1571
- current_wave: epic.current_wave ?? null,
1572
- replan: epic.replan ?? null,
1573
- replan_revision: epic.replan_revision ?? null,
1574
- dependency_graph: epic.dependency_graph ?? null,
1575
- scheduler: epic.scheduler ?? null,
1576
- attempts: epic.attempts ?? null,
1577
- retry_count: epic.retry_count ?? null,
1578
- },
1579
- stories: storyAuthority,
1580
- }),
1581
- epoch: typeof epic.graph_revision === 'string' ? epic.graph_revision : null,
1582
- storyStatus: typeof asRecordOrUndefined(stories?.[storyId])?.status === 'string'
1583
- ? String(asRecordOrUndefined(stories?.[storyId])?.status)
1584
- : null,
1585
- };
1586
- }
1587
- function exactPersistedCheckpointProjection(tracked, runtimeDocument, lease, checkpoint) {
1588
- const effective = applyGitLifecycleRuntimeOverlay(tracked, runtimeDocument);
1589
- const epic = asRecordOrUndefined(asRecordOrUndefined(effective.epics)?.[lease.epicId]);
1590
- const story = asRecordOrUndefined(asRecordOrUndefined(effective.stories)?.[lease.storyId]);
1591
- const steps = Array.isArray(story?.steps_completed)
1592
- ? story.steps_completed.filter((value) => typeof value === 'string')
1593
- : [];
1594
- return Boolean(epic && story
1595
- && epic.branch_lease === null
1596
- && story.status === 'done'
1597
- && story.last_step === GIT_LIFECYCLE_REVIEW_PR_STEP_ID
1598
- && steps.includes(GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID)
1599
- && steps.includes(GIT_LIFECYCLE_REVIEW_PR_STEP_ID)
1600
- && canonicalJson(story.checkpoint) === canonicalJson(checkpoint));
1601
- }
1602
- function restoreRecord(target, previous) {
1603
- for (const key of Object.keys(target))
1604
- delete target[key];
1605
- Object.assign(target, structuredClone(previous));
1606
- }
1607
- async function readCurrentGraphAuthorityRevision(projectRoot, epicId) {
1608
- return (await readCurrentGraphAuthoritySnapshot(projectRoot, epicId, '')).revision;
1609
- }
1610
- function hashCanonical(value) {
1611
- return createHash('sha256').update(canonicalJson(value)).digest('hex');
1612
- }
1613
- function canonicalJson(value) {
1614
- if (value === null || typeof value !== 'object')
1615
- return JSON.stringify(value);
1616
- if (Array.isArray(value))
1617
- return `[${value.map(canonicalJson).join(',')}]`;
1618
- return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(',')}}`;
1619
- }
1620
- function normalizeReceiptRefs(values, dispatchId) {
1621
- const safe = (values ?? []).filter((value) => /^[A-Za-z0-9._/:@#-]{1,200}$/.test(value) && !value.includes('..'));
1622
- return Object.freeze([...new Set(safe.length > 0 ? safe : [`dispatch:${dispatchId}`])].sort());
1623
- }
1624
- function safeRef(value) {
1625
- return value.replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 80);
1626
- }
1627
- function failure(reasonCode) {
1628
- return { ok: false, reasonCode };
1629
- }
1630
- function isNodeError(error, code) {
1631
- return error instanceof Error && 'code' in error && error.code === code;
1632
- }
1633
- async function readLeaseOwner(leasePath, leasesRoot) {
1634
- try {
1635
- await assertGitLifecyclePrivateDirectory(leasePath, leasesRoot);
1636
- const ownerPath = join(leasePath, 'owner.json');
1637
- await assertGitLifecyclePrivateFile(ownerPath, leasePath);
1638
- const parsed = JSON.parse(await readFile(ownerPath, 'utf8'));
1639
- if (!Number.isSafeInteger(parsed.pid) || Number(parsed.pid) <= 0
1640
- || typeof parsed.createdAt !== 'string' || !Number.isFinite(Date.parse(parsed.createdAt))
1641
- || typeof parsed.nonce !== 'string' || !/^[a-f0-9]{32}$/.test(parsed.nonce)) {
1642
- throw new Error('continuous-sandbox-lease-owner-invalid');
1643
- }
1644
- return { pid: Number(parsed.pid), createdAt: parsed.createdAt, nonce: parsed.nonce };
1645
- }
1646
- catch (error) {
1647
- if (isNodeError(error, 'ENOENT'))
1648
- return undefined;
1649
- throw error;
1650
- }
1651
- }
1652
- function sameLeaseOwner(left, right) {
1653
- return left?.pid === right.pid && left.createdAt === right.createdAt && left.nonce === right.nonce;
1654
- }
1655
- function processExists(pid) {
1656
- try {
1657
- process.kill(pid, 0);
1658
- return true;
1659
- }
1660
- catch (error) {
1661
- return isNodeError(error, 'EPERM');
1662
- }
1663
- }
1664
- async function readSandboxMetadata(workspacePath, sandboxesRoot) {
1665
- try {
1666
- await assertGitLifecyclePrivateDirectory(workspacePath, sandboxesRoot);
1667
- const gitDirectory = join(workspacePath, '.git');
1668
- await assertGitLifecyclePrivateDirectory(gitDirectory, workspacePath);
1669
- const metadataPath = join(gitDirectory, 'neocortex-sandbox.json');
1670
- await assertGitLifecyclePrivateFile(metadataPath, gitDirectory);
1671
- const parsed = JSON.parse(await readFile(metadataPath, 'utf8'));
1672
- if (parsed.schemaVersion !== 1 || typeof parsed.workspaceOwnerNonce !== 'string'
1673
- || !/^[a-f0-9]{32}$/.test(parsed.workspaceOwnerNonce)
1674
- || !/^[a-f0-9]{64}$/.test(parsed.graphAuthorityRevision)
1675
- || !(parsed.graphAuthorityEpoch === null || /^[a-f0-9]{64}$/.test(parsed.graphAuthorityEpoch))
1676
- || !(parsed.graphAuthorityStoryStatus === null
1677
- || typeof parsed.graphAuthorityStoryStatus === 'string' && parsed.graphAuthorityStoryStatus.length <= 80)
1678
- || typeof parsed.workspaceIdentity?.dev !== 'string' || !/^[0-9]+$/.test(parsed.workspaceIdentity.dev)
1679
- || typeof parsed.workspaceIdentity?.ino !== 'string' || !/^[0-9]+$/.test(parsed.workspaceIdentity.ino)) {
1680
- throw new Error('continuous-sandbox-metadata-invalid');
1681
- }
1682
- return parsed;
1683
- }
1684
- catch (error) {
1685
- if (isNodeError(error, 'ENOENT'))
1686
- return undefined;
1687
- throw error;
1688
- }
1689
- }
1690
- async function writeSandboxMetadata(workspacePath, sandboxesRoot, metadata, beforeCommit) {
1691
- await assertGitLifecyclePrivateDirectory(workspacePath, sandboxesRoot);
1692
- const gitDirectory = join(workspacePath, '.git');
1693
- await assertGitLifecyclePrivateDirectory(gitDirectory, workspacePath);
1694
- const metadataPath = join(gitDirectory, 'neocortex-sandbox.json');
1695
- await writeOptional(workspacePath, '.git/neocortex-sandbox.json', Buffer.from(`${JSON.stringify(metadata, null, 2)}\n`), beforeCommit);
1696
- await assertGitLifecyclePrivateFile(metadataPath, gitDirectory);
1697
- }
1698
- async function readMarker(markerPath, integratedRoot) {
1699
- try {
1700
- await assertGitLifecyclePrivateFile(markerPath, integratedRoot);
1701
- const parsed = JSON.parse(await readFile(markerPath, 'utf8'));
1702
- return typeof parsed.childHeadSha === 'string' && typeof parsed.rootHeadSha === 'string'
1703
- && /^[a-f0-9]{40,64}$/.test(parsed.childHeadSha) && /^[a-f0-9]{40,64}$/.test(parsed.rootHeadSha)
1704
- && parsed.bundle?.schemaVersion === 1 && parsed.checkpoint?.schemaVersion === 1
1705
- ? parsed
1706
- : undefined;
1707
- }
1708
- catch (error) {
1709
- if (isNodeError(error, 'ENOENT'))
1710
- return undefined;
1711
- throw error;
1712
- }
1713
- }
1714
- async function checkpointExistsInRootState(lease, checkpoint) {
1715
- try {
1716
- const tracked = asRecord(JSON.parse(await readFile(join(lease.projectRoot, '.neocortex/state.json'), 'utf8')));
1717
- const state = applyGitLifecycleRuntimeOverlay(tracked, await readGitLifecycleRuntime(lease.projectRoot));
1718
- const current = asRecordOrUndefined(asRecordOrUndefined(state.stories)?.[lease.storyId]);
1719
- const persisted = asRecordOrUndefined(current?.checkpoint);
1720
- return persisted?.idempotencyKey === checkpoint.idempotencyKey
1721
- && persisted.headSha === checkpoint.headSha
1722
- && persisted.bundleDigest === checkpoint.bundleDigest
1723
- && asRecordOrUndefined(asRecordOrUndefined(state.epics)?.[lease.epicId])?.branch_lease === null
1724
- && await verifyAcceptedGitLifecycleStoryCheckpoint(lease.projectRoot, persisted, lease.storyId, lease.epicId, lease.executionBranch, undefined, lease.authorizedWriteSet);
1725
- }
1726
- catch {
1727
- return false;
1728
- }
1729
- }
1730
- async function readMatchingRootCheckpoint(lease, bundle, commit) {
1731
- try {
1732
- const tracked = asRecord(JSON.parse(await readFile(join(lease.projectRoot, '.neocortex/state.json'), 'utf8')));
1733
- const state = applyGitLifecycleRuntimeOverlay(tracked, await readGitLifecycleRuntime(lease.projectRoot));
1734
- const story = asRecordOrUndefined(asRecordOrUndefined(state.stories)?.[lease.storyId]);
1735
- const checkpoint = asRecordOrUndefined(story?.checkpoint);
1736
- if (checkpoint?.schemaVersion !== 1
1737
- || checkpoint.storyId !== lease.storyId
1738
- || checkpoint.epicId !== lease.epicId
1739
- || checkpoint.branch !== lease.executionBranch
1740
- || checkpoint.baseSha !== commit.baseSha
1741
- || checkpoint.headSha !== commit.headSha
1742
- || checkpoint.idempotencyKey !== lease.dispatchId
1743
- || checkpoint.dispatchId !== lease.dispatchId
1744
- || checkpoint.bundleId !== bundle.bundleId
1745
- || checkpoint.bundleDigest !== bundle.bundleDigest
1746
- || checkpoint.graphRevision !== lease.graphRevision
1747
- || checkpoint.claimRevision !== lease.claimRevision
1748
- || asRecordOrUndefined(asRecordOrUndefined(state.epics)?.[lease.epicId])?.branch_lease !== null
1749
- || !(await verifyAcceptedGitLifecycleStoryCheckpoint(lease.projectRoot, checkpoint, lease.storyId, lease.epicId, lease.executionBranch, undefined, lease.authorizedWriteSet)))
1750
- return undefined;
1751
- return checkpoint;
1752
- }
1753
- catch {
1754
- return undefined;
1755
- }
1756
- }
1757
- async function findIntegratedDispatchCommit(lease, bundle) {
1758
- const matches = (await gitOptional(lease.projectRoot, [
1759
- 'log', '--format=%H', '--fixed-strings', `--grep=Neocortex-Dispatch: ${lease.dispatchId}`,
1760
- ]))?.split('\n').filter((sha) => /^[a-f0-9]{40,64}$/.test(sha)) ?? [];
1761
- if (matches.length !== 1)
1762
- return undefined;
1763
- const headSha = matches[0];
1764
- if (!(await gitExitOk(lease.projectRoot, ['merge-base', '--is-ancestor', headSha, 'HEAD'])))
1765
- return undefined;
1766
- const message = await git(lease.projectRoot, ['show', '-s', '--format=%B', headSha]);
1767
- const trailers = new Set(message.split('\n').map((line) => line.trim()));
1768
- for (const trailer of [
1769
- `Neocortex-Story: ${lease.storyId}`,
1770
- `Neocortex-Epic: ${lease.epicId}`,
1771
- `Neocortex-Execution-Branch: ${lease.executionBranch}`,
1772
- `Neocortex-Prepared-Base: ${lease.baseSha}`,
1773
- `Neocortex-Dispatch: ${lease.dispatchId}`,
1774
- `Neocortex-Bundle: ${bundle.bundleId}`,
1775
- `Neocortex-Bundle-Digest: ${bundle.bundleDigest}`,
1776
- `Neocortex-Graph-Revision: ${lease.graphRevision}`,
1777
- `Neocortex-Claim-Revision: ${lease.claimRevision}`,
1778
- ])
1779
- if (!trailers.has(trailer))
1780
- return undefined;
1781
- const authorityRevision = readCommitTrailer(message, 'Neocortex-Checkpoint-Authority');
1782
- const authorityEpoch = readCommitTrailer(message, 'Neocortex-Checkpoint-Epoch');
1783
- const authorityStoryStatus = readCommitTrailer(message, 'Neocortex-Checkpoint-Story-Status');
1784
- if (!authorityRevision || !/^[a-f0-9]{64}$/.test(authorityRevision)
1785
- || !authorityEpoch || !(authorityEpoch === 'null' || /^[a-f0-9]{64}$/.test(authorityEpoch))
1786
- || !authorityStoryStatus || authorityStoryStatus.length > 80)
1787
- return undefined;
1788
- const parentSha = await gitOptional(lease.projectRoot, ['rev-parse', `${headSha}^`]);
1789
- if (!parentSha || !/^[a-f0-9]{40,64}$/.test(parentSha))
1790
- return undefined;
1791
- const committedPaths = splitNull(await gitRaw(lease.projectRoot, [
1792
- 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', headSha,
1793
- ]));
1794
- if (committedPaths.length === 0 || committedPaths.some((path) => !bundle.authorizedWriteSet.some((scope) => writeSetCovers(scope, path))))
1795
- return undefined;
1796
- return {
1797
- baseSha: parentSha,
1798
- headSha,
1799
- checkpointAuthority: {
1800
- revision: authorityRevision,
1801
- epoch: authorityEpoch === 'null' ? null : authorityEpoch,
1802
- storyStatus: authorityStoryStatus === 'null' ? null : authorityStoryStatus,
1803
- },
1804
- };
1805
- }
1806
- function readCommitTrailer(message, name) {
1807
- const prefix = `${name}: `;
1808
- const matches = message.split('\n').map((line) => line.trim()).filter((line) => line.startsWith(prefix));
1809
- return matches.length === 1 ? matches[0].slice(prefix.length) : undefined;
1810
- }
1811
- async function writeMarker(markerPath, childHeadSha, rootHeadSha, bundle, checkpoint, beforeCommit) {
1812
- const integratedRoot = dirname(markerPath);
1813
- await assertGitLifecyclePrivateDirectory(integratedRoot, dirname(integratedRoot));
1814
- try {
1815
- await assertGitLifecyclePrivateFile(markerPath, integratedRoot);
1816
- }
1817
- catch (error) {
1818
- if (!isNodeError(error, 'ENOENT'))
1819
- throw error;
1820
- }
1821
- await writeOptional(integratedRoot, basename(markerPath), Buffer.from(`${JSON.stringify({ childHeadSha, rootHeadSha, bundle, checkpoint })}\n`), beforeCommit);
1822
- await assertGitLifecyclePrivateFile(markerPath, integratedRoot);
1823
- }
49
+ `;function kr(e,r={}){return async(t,o,n={})=>Kt(e,t,o,n,r)}function Tt(e={}){let r=Promise.resolve();return{async prepare(t){if((e.platform??process.platform)==="win32")return d("continuous-sandbox-platform-unsupported");if(!/^[a-f0-9]{64}$/.test(t.dispatchId))return d("continuous-sandbox-dispatch-invalid");if(!oe(t.targetRef))return d("continuous-sandbox-target-invalid");if(!dt(t.executionBranch))return d("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(t.graphRevision))return d("continuous-graph-revision-invalid");const o=st(t.authorizedWriteSet);if(o.length===0||o.length!==t.authorizedWriteSet.length)return d("continuous-authorized-write-set-invalid");const n=Ie(o),i=r;let c=()=>{};r=new Promise(s=>{c=s}),await i;let a,u;try{const s=await et(t.projectRoot),v=await O(s,["rev-parse","HEAD"]),g=await ue(s,t.epicId,t.storyId),I=g.revision,b=await Ye(s),l=await Xe(b,t.dispatchId,(S,y)=>{a=S,u=y},e.beforeSandboxWriteCommit);if(!l.ok)return l;const{leasePath:N}=l.value,k=await xe(b,"sandboxes"),f=C(k,t.dispatchId.slice(0,20)),m=await Le(f,k);let A,h;const R=m?.preparedAt??new Date().toISOString(),x=m?.workspaceOwnerNonce??Ve(16).toString("hex");if(m){if(m.projectRoot!==s||m.storyId!==t.storyId||m.targetRef!==t.targetRef||m.dispatchId!==t.dispatchId||m.epicId!==t.epicId||m.executionBranch!==t.executionBranch||m.graphRevision!==t.graphRevision||m.claimRevision!==n||m.graphAuthorityRevision!==I||m.graphAuthorityEpoch!==g.epoch||m.graphAuthorityStoryStatus!==g.storyStatus||!ut(m.authorizedWriteSet,o)||(A=m.contextSnapshots.map(S=>({path:S.path,...S.contentBase64!==void 0?{content:Buffer.from(S.contentBase64,"base64")}:{}})),h=await Ze(f),h.dev!==m.workspaceIdentity.dev||h.ino!==m.workspaceIdentity.ino))return d("continuous-sandbox-recovery-mismatch")}else await ee(f,k),h=await je(k,$(f)),await L(f,k),await ae(k,$(f),h,["init","--quiet"]),await Ht(s,f),await qt(s,k,$(f),h),await ae(k,$(f),h,["remote","add","neocortex-root",s]),await ae(k,$(f),h,["fetch","--quiet","--no-tags","neocortex-root",v]),await ae(k,$(f),h,["checkout","--quiet","--detach","FETCH_HEAD"]),A=await Lt(s,f,t.epicId,t.targetRef,e.beforeSandboxWriteCommit),await sr(f,k,{schemaVersion:1,projectRoot:s,storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:I,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:o,claimRevision:n,dispatchId:t.dispatchId,baseSha:v,preparedAt:R,workspaceOwnerNonce:x,workspaceIdentity:h,contextSnapshots:A.map(S=>({path:S.path,...S.content!==void 0?{contentBase64:S.content.toString("base64")}:{}}))},e.beforeSandboxWriteCommit);return a=void 0,{ok:!0,value:{projectRoot:s,workspacePath:f,workspaceStrategy:"branchless_sandbox",storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:I,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:o,claimRevision:n,baseSha:m?.baseSha??v,dispatchId:t.dispatchId,preparedAt:R,leasePath:N,leaseOwnerNonce:l.value.owner.nonce,workspaceOwnerNonce:x,workspaceIdentity:h,contextSnapshots:A}}}catch{if(a&&u){const s=a,v=u;await ee(s,j(s),async g=>ht(await ne(g,j(s)),v)).catch(()=>{})}return d("continuous-sandbox-prepare-failed")}finally{c()}},async integrate(t,o){const n=await ne(t.leasePath,j(t.leasePath)).catch(()=>{}),i=await Le(t.workspacePath,j(t.workspacePath)).catch(()=>{});if(!n||n.nonce!==t.leaseOwnerNonce||i?.workspaceOwnerNonce!==t.workspaceOwnerNonce||i.dispatchId!==t.dispatchId||i.storyId!==t.storyId)return d("continuous-sandbox-owner-mismatch");const c=it(o?.nowIso??new Date().toISOString()),a=await At(t.projectRoot,{kind:"continuous",storyId:t.storyId,sessionId:t.dispatchId,idempotencyKey:t.dispatchId,expiresAt:new Date(Date.parse(c)+1800*1e3).toISOString(),persistent:!1,createdAt:c});if(!a.ok)return d(a.reasonCode==="git-lifecycle-integration-backpressure"?"continuous-integration-backpressure":"continuous-integration-lease-failed");let u=[],s=!1,v=!1;try{const g=(await ce(t,["status","--porcelain"])).trimEnd(),I=await Oe(t,["rev-parse","HEAD"]);if(await te(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.executionBranch)return d("continuous-execution-branch-mismatch");const l=j(j(t.leasePath)),N=await xe(l,"integrated"),k=C(N,t.dispatchId),f=await dr(k,N);if(f?.childHeadSha===I&&f.bundle.storyId===t.storyId&&f.bundle.epicId===t.epicId&&f.bundle.executionBranch===t.executionBranch&&f.bundle.graphRevision===t.graphRevision&&f.bundle.claimRevision===t.claimRevision&&ut(f.bundle.authorizedWriteSet,t.authorizedWriteSet)&&f.checkpoint.idempotencyKey===t.dispatchId&&f.checkpoint.bundleId===f.bundle.bundleId&&f.checkpoint.bundleDigest===f.bundle.bundleDigest&&f.checkpoint.graphRevision===t.graphRevision&&f.checkpoint.claimRevision===t.claimRevision&&await se(t.projectRoot,["merge-base","--is-ancestor",f.rootHeadSha,"HEAD"])&&await ur(t,f.checkpoint))return{ok:!0,value:{headSha:f.rootHeadSha,alreadyIntegrated:!0,bundle:f.bundle,checkpoint:f.checkpoint}};if(I!==t.baseSha)return d("continuous-sandbox-child-git-authority-denied");if(g.length===0)return d("continuous-bundle-empty");const m=g.split(`
50
+ `).some(w=>w.length>0&&w[0]!==" "&&w[0]!=="?");m||await Oe(t,["add","-A"]);const A=G(await ce(t,["diff","--cached","--name-only","-z",t.baseSha]));if(A.length===0||A.some(w=>!oe(w)))return d("continuous-integration-write-set-invalid");if(!await Jt(t,["merge-base","--is-ancestor",t.baseSha,I]))return d("continuous-bundle-base-not-ancestor");if(!await se(t.projectRoot,["merge-base","--is-ancestor",t.baseSha,"HEAD"]))return d("continuous-root-base-not-ancestor");const h=o?.nowIso??new Date().toISOString(),R=ir(o?.receiptRefs,t.dispatchId),x=await ce(t,["diff","--cached","--binary",t.baseSha]),S={schemaVersion:1,storyId:t.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:t.baseSha,bundleDigest:W("sha256").update(x).digest("hex"),graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,contextDigests:Object.fromEntries(t.contextSnapshots.map(w=>[w.path,W("sha256").update(w.content??Buffer.alloc(0)).digest("hex")])),validationRefs:R,createdAt:t.preparedAt,expiresAt:new Date(Date.parse(t.preparedAt)+1440*60*1e3).toISOString(),branchless:!0},y=Object.freeze({...S,bundleId:Ie(S)}),E=await fr(t,y);if(E){const w=await hr(t,y,E);if(w)return await He(k,I,E.headSha,y,w,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:y,checkpoint:w}}}if(!E&&await nr(t.projectRoot,t.epicId)!==t.graphAuthorityRevision)return d("continuous-graph-revision-stale");if(E){const w=await nt({lease:t,bundle:y,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:R,nowIso:h,qaRunner:e.storyQaRunner});if(!w.ok)return w;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:E.headSha});const _=await ot({lease:t,physicalLock:a,checkpointAuthority:E.checkpointAuthority,bundle:y,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:[...R,`bundle:${y.bundleId}`,w.value.qaReceipt.receiptRef,w.value.reviewReceipt.receiptRef],qaReceipt:w.value.qaReceipt,reviewReceipt:w.value.reviewReceipt,recordedAt:h,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return _.ok?(await He(k,I,E.headSha,y,_.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:y,checkpoint:_.value}}):_}if(m)return d("continuous-sandbox-child-git-authority-denied");if(G(await T(t.projectRoot,["diff","--cached","--name-only","-z"])).length>0)return d("continuous-integration-root-index-dirty");const J=new Set(t.contextSnapshots.map(w=>w.path));if(A.filter(w=>!t.authorizedWriteSet.some(_=>ve(_,w))).length>0)return d("continuous-bundle-write-set-unauthorized");const M=A.filter(w=>!J.has(w)),be=new Set(G(await T(t.projectRoot,["diff","--name-only","-z",`${t.baseSha}..HEAD`])));if(M.some(w=>be.has(w)))return d("continuous-bundle-intervening-conflict");const fe=new Set([...G(await T(t.projectRoot,["diff","--name-only","-z"])),...G(await T(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(M.some(w=>fe.has(w)))return d("continuous-integration-root-conflict");u=await Yt(t.projectRoot,[...new Set([...A,".neocortex/state.json"])]);const H=await Zt(t,h);if(!H.ok)return H;const K=vt({bundle:y,payload:Buffer.from(x),expected:{epicId:t.epicId,storyId:t.storyId,executionBranch:t.executionBranch,baseSha:t.baseSha,graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,nowIso:h},writerLease:H.value});if(K.length>0)return await Be(t.projectRoot,u),d(`continuous-bundle-admission-${K[0]}`);const pe=await O(t.projectRoot,["rev-parse","HEAD"]);let Q;await e.beforeRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:pe});try{await X(t.projectRoot,w=>{const _=p(we(w,t.epicId).branch_lease);if(_?.ownerStoryId!==t.storyId||_.sessionId!==t.dispatchId||_.idempotencyKey!==t.dispatchId||Date.parse(String(_.expiresAt))<=Date.now())throw new Error("continuous-checkpoint-writer-lease-lost")},{preCommit:async w=>{const _=await ue(t.projectRoot,t.epicId,t.storyId,w);if(_.revision!==t.graphAuthorityRevision||_.epoch!==t.graphAuthorityEpoch||_.storyStatus!==t.graphAuthorityStoryStatus)throw new Error("continuous-graph-revision-stale");if(!await Ae(a.path,a.owner))throw new Error("continuous-integration-lock-raced");const ft=await te(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),pt=await O(t.projectRoot,["rev-parse","HEAD"]);if(ft!==t.executionBranch||pt!==pe)throw new Error("continuous-integration-head-raced");const lt=G(await T(t.projectRoot,["diff","--cached","--name-only","-z"])),yt=new Set([...G(await T(t.projectRoot,["diff","--name-only","-z"])),...G(await T(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(lt.length>0)throw new Error("continuous-integration-root-index-dirty");if(M.some(P=>yt.has(P)))throw new Error("continuous-integration-root-conflict");if(v=!0,M.length>0){const P=await ce(t,["diff","--cached","--binary",t.baseSha,"--",...M]);if(P.length>0&&!await Ft(t.projectRoot,["apply","--index","--3way","--whitespace=nowarn"],P))throw new Error("continuous-integration-conflict")}for(const P of t.contextSnapshots){if(!A.includes(P.path))continue;const Je=await Ne(C(t.projectRoot,P.path)),Me=await Mt(t,P.path),Ke=P.path===".neocortex/state.json"?rr(P.content,Je,Xt(P.content,Me,t.storyId)):tr(P.content,Je,Me);if(!Ke.ok)throw new Error(P.path===".neocortex/state.json"?"continuous-state-merge-conflict":"continuous-context-merge-conflict");await re(t.projectRoot,P.path,Ke.value),await O(t.projectRoot,["add","-A","--",P.path])}if(A.includes(".neocortex/state.json")&&await O(t.projectRoot,["add","-A","--",".neocortex/state.json"]),await se(t.projectRoot,["diff","--cached","--quiet"]))throw new Error("continuous-integration-empty-after-admission");Q=await ue(t.projectRoot,t.epicId,t.storyId,w),await O(t.projectRoot,["commit","-m",`feat(yoloop): integrate ${t.storyId}`,"-m",`Neocortex-Story: ${t.storyId}`,"-m",`Neocortex-Epic: ${t.epicId}`,"-m",`Neocortex-Execution-Branch: ${t.executionBranch}`,"-m",`Neocortex-Prepared-Base: ${t.baseSha}`,"-m",`Neocortex-Dispatch: ${t.dispatchId}`,"-m",`Neocortex-Bundle: ${y.bundleId}`,"-m",`Neocortex-Bundle-Digest: ${y.bundleDigest}`,"-m",`Neocortex-Graph-Revision: ${t.graphRevision}`,"-m",`Neocortex-Claim-Revision: ${t.claimRevision}`,"-m",`Neocortex-Checkpoint-Authority: ${Q.revision}`,"-m",`Neocortex-Checkpoint-Epoch: ${Q.epoch??"null"}`,"-m",`Neocortex-Checkpoint-Story-Status: ${Q.storyStatus??"null"}`]),s=!0}})}catch(w){v&&!s&&await Be(t.projectRoot,u);const _=w instanceof Error&&/^continuous-/.test(w.message)?w.message:"continuous-integration-failed";return d(_)}const Y=await O(t.projectRoot,["rev-parse","HEAD"]);if(!Q)return d("continuous-checkpoint-authority-missing");await e.afterRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Y});const Z=await nt({lease:t,bundle:y,baseSha:pe,headSha:Y,receiptRefs:R,nowIso:h,qaRunner:e.storyQaRunner});if(!Z.ok)return Z;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Y});const le=await ot({lease:t,physicalLock:a,checkpointAuthority:Q,bundle:y,baseSha:pe,headSha:Y,receiptRefs:[...R,`bundle:${y.bundleId}`,Z.value.qaReceipt.receiptRef,Z.value.reviewReceipt.receiptRef],qaReceipt:Z.value.qaReceipt,reviewReceipt:Z.value.reviewReceipt,recordedAt:h,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return le.ok?(await He(k,I,Y,y,le.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:Y,alreadyIntegrated:!1,bundle:y,checkpoint:le.value}}):le}catch{return v&&!s&&u.length>0&&await Be(t.projectRoot,u),d("continuous-integration-failed")}finally{await Ut(t).catch(()=>{}),await Ot(a.path,a.owner).catch(()=>{})}},async release(t,o){o||await ee(t.workspacePath,j(t.workspacePath),async n=>{const i=await Le(n,j(t.workspacePath)).catch(()=>{});return i?.workspaceOwnerNonce===t.workspaceOwnerNonce&&i.dispatchId===t.dispatchId&&i.storyId===t.storyId}),await ee(t.leasePath,j(t.leasePath),async n=>(await ne(n,j(t.leasePath)).catch(()=>{}))?.nonce===t.leaseOwnerNonce)}}}const zt="story-worktree-integration-root-owned";function Wt(e={}){const r=e.storyWorktrees??(o=>new Et({projectRoot:o}));let t=Promise.resolve();return{async prepare(o){if(!/^[a-f0-9]{64}$/.test(o.dispatchId))return d("continuous-sandbox-dispatch-invalid");if(!oe(o.targetRef))return d("continuous-sandbox-target-invalid");if(!dt(o.executionBranch))return d("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(o.graphRevision))return d("continuous-graph-revision-invalid");const n=st(o.authorizedWriteSet);if(n.length===0||n.length!==o.authorizedWriteSet.length)return d("continuous-authorized-write-set-invalid");const i=Ie(n),c=t;let a=()=>{};t=new Promise(s=>{a=s}),await c;let u;try{const s=await et(o.projectRoot),v=await O(s,["rev-parse","--verify",`refs/heads/${o.executionBranch}^{commit}`]),g=await ue(s,o.epicId,o.storyId),I=await Ye(s),b=await Xe(I,o.dispatchId,(f,m)=>{u={leasePath:f,owner:m}},e.beforeSandboxWriteCommit);if(!b.ok)return b;const l=await r(s).create({epicId:o.epicId,storyId:o.storyId,dispatchId:o.dispatchId,baseSha:v,graphRevision:o.graphRevision});if(!l.ok||!l.privatePath||!ke(l.privatePath))return u=void 0,await De(b.value.leasePath,b.value.owner.nonce).catch(()=>{}),d(l.ok?"story-worktree-path-unavailable":l.reasonCode);const N=Qe(l.privatePath),k=await Ze(N);return u=void 0,{ok:!0,value:{projectRoot:s,workspacePath:N,workspaceStrategy:"story_worktree",storyWorktreeLeaseId:l.value.lease.leaseId,storyId:o.storyId,targetRef:o.targetRef,epicId:o.epicId,executionBranch:o.executionBranch,graphRevision:o.graphRevision,graphAuthorityRevision:g.revision,graphAuthorityEpoch:g.epoch,graphAuthorityStoryStatus:g.storyStatus,authorizedWriteSet:n,claimRevision:i,baseSha:l.value.baseSha,preparedAt:new Date().toISOString(),dispatchId:o.dispatchId,leasePath:b.value.leasePath,leaseOwnerNonce:b.value.owner.nonce,workspaceOwnerNonce:b.value.owner.nonce,workspaceIdentity:k,contextSnapshots:[]}}}catch{const s=u;return s&&await De(s.leasePath,s.owner.nonce).catch(()=>{}),d("story-worktree-prepare-failed")}finally{a()}},async integrate(o){return o.workspaceStrategy!=="story_worktree"?d("continuous-workspace-strategy-mismatch"):d(zt)},async release(o){await De(o.leasePath,o.leaseOwnerNonce)}}}function Gt(e){const r=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;return r?.version===4&&r.mode==="two_phase_worktree_dag"&&r.authorization==="server_authorized"&&r.workspaceMechanism==="client_managed_worktree"?"story_worktree":"branchless_sandbox"}function xr(e,r={}){const t=Gt(e);return t==="story_worktree"?{strategy:t,manager:r.storyWorktree??Wt()}:{strategy:t,manager:r.branchless??Tt()}}async function Xe(e,r,t,o){const n=await xe(e,"leases"),i=C(n,r);try{await je(n,r),await L(i,n)}catch(a){if(!q(a,"EEXIST"))throw a;await L(i,n);const u=await ne(i,n);if(u!==void 0&&cr(u.pid))return d("continuous-sandbox-lease-active");if(!u||!await ee(i,n,async s=>ht(await ne(s,n),u)))return d("continuous-sandbox-lease-owner-replaced");await je(n,r),await L(i,n)}const c=Object.freeze({pid:process.pid,createdAt:new Date().toISOString(),nonce:Ve(16).toString("hex")});return t(i,c),await re(i,"owner.json",Buffer.from(JSON.stringify(c)),o),await F(C(i,"owner.json"),i),{ok:!0,value:{leasePath:i,owner:c}}}async function De(e,r){await ee(e,j(e),async t=>(await ne(t,j(e)).catch(()=>{}))?.nonce===r)}async function Lt(e,r,t,o,n){const i=[...new Set([".neocortex/state.json",o,`docs/epics/epic-${ar(t)}.md`])],c=[];for(const a of i){if(!oe(a))continue;const u=await Ne(C(e,a));c.push({path:a,...u!==void 0?{content:u}:{}}),u!==void 0&&await re(r,a,u,n)}return c}async function et(e){const r=await O(e,["rev-parse","--show-toplevel"]),[t,o]=await Promise.all([U(r),U(e)]);if(t!==o)throw new Error("project root mismatch");return t}async function qt(e,r,t,o){for(const n of["user.name","user.email"]){const i=await te(e,["config","--get",n]);i&&await ae(r,t,o,["config",n,i])}}async function Ht(e,r){const t=await V(e);await X(r,o=>{for(const[n,i]of Object.entries(t.epics))o.epics[n]={...structuredClone(i),branch_lease:null};for(const[n,i]of Object.entries(t.stories))o.stories[n]=structuredClone(i)})}async function ae(e,r,t,o){return(await Ce(e,r,t,o)).toString("utf8").trim()}async function ce(e,r){return(await Ce(j(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,r)).toString("utf8")}async function Oe(e,r){return(await ce(e,r)).trim()}async function Jt(e,r){try{return await Oe(e,r),!0}catch{return!1}}async function Mt(e,r){try{return await Ce(j(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,["show",`:${r}`])}catch{return}}async function Kt(e,r,t,o,n){const i=Date.now(),c=b=>({exitCode:null,timedOut:!1,durationMs:Date.now()-i,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0,...b});if(o.signal?.aborted)return c({signal:"SIGTERM",cancelled:!0});if(!r||r.length>4096||r.includes("\0")||t.length>512||t.some(b=>b.length>32768||b.includes("\0")))return c({exitCode:73,stderr:"continuous-child-invocation-invalid",stderrBytes:35});const a=j(e.workspacePath),u=await ye(a,{bigint:!0}),s=await gt(a,{bigint:!0});if(!u.isDirectory()||u.isSymbolicLink()||!s.isDirectory()||u.dev!==s.dev||u.ino!==s.ino)return c({exitCode:73,stderr:"continuous-child-parent-invalid",stderrBytes:31});await n.beforeHandoff?.();const v=Buffer.from(JSON.stringify({command:r,args:[...t]})).toString("base64url"),g=o.maxOutputBytes??64e3,I=Math.max(1,Math.min(o.timeoutMs??600*1e3,1800*1e3));return await new Promise(b=>{const l=Fe(process.execPath,["-e",$t,String(s.dev),String(s.ino),$(e.workspacePath),e.workspaceIdentity.dev,e.workspaceIdentity.ino,v,n.afterHandoff?"1":"0"],{cwd:a,env:o.env??It({processEnv:process.env,platform:process.platform}),stdio:["pipe","pipe","pipe"]});let N="",k="",f=0,m=0,A=!1,h=!1,R=!1,x=!n.afterHandoff;const S=(D,J)=>{A||(A=!0,clearTimeout(E),o.signal?.removeEventListener("abort",y),b({exitCode:D,...J?{signal:J}:{},timedOut:h,...R?{cancelled:!0}:{},durationMs:Date.now()-i,stdout:N,stderr:k,stdoutBytes:f,stderrBytes:m}))},y=()=>{R=!0,l.kill("SIGTERM")};o.signal?.addEventListener("abort",y,{once:!0});const E=setTimeout(()=>{h=!0,l.kill("SIGTERM")},I);l.stdout.on("data",D=>{f+=D.length,f+m>g?l.kill("SIGTERM"):N+=D.toString("utf8")}),l.stderr.on("data",D=>{m+=D.length,f+m>g?l.kill("SIGTERM"):k+=D.toString("utf8"),!x&&k.includes(`continuous-child-handoff-ready
51
+ `)&&(x=!0,Promise.resolve(n.afterHandoff?.()).then(()=>l.stdin.end()).catch(()=>l.kill("SIGTERM")))}),l.once("error",()=>S(null)),l.once("close",(D,J)=>S(D,J)),n.afterHandoff||l.stdin.end()})}async function O(e,r){return(await T(e,r)).trim()}async function T(e,r){const t=await _e("git",r,{cwd:e,encoding:"utf8",maxBuffer:16777216});return String(t.stdout)}async function te(e,r){try{return await O(e,r)}catch(t){if(q(t,"ENOENT"))return;throw t}}async function se(e,r){try{return await O(e,r),!0}catch{return!1}}async function Ft(e,r,t){return await new Promise(o=>{const n=Fe("git",[...r],{cwd:e,stdio:["pipe","ignore","ignore"]});n.once("error",()=>o(!1)),n.once("close",i=>o(i===0)),n.stdin.end(t)})}async function Er(e,r,t){try{const o=await _e("git",["show",`${r}:${t}`],{cwd:e,encoding:"buffer",maxBuffer:16777216});return Buffer.from(o.stdout)}catch(o){if(q(o,"ENOENT"))return;throw o}}async function Ne(e){try{return await B(e)}catch(r){if(q(r,"ENOENT"))return;throw r}}async function re(e,r,t,o){const n=de(r);if(!oe(n))throw new Error("continuous-sandbox-write-path-invalid");const i=await U(e);if(i!==Qe(e))throw new Error("continuous-sandbox-write-root-symlink");const c=j(n)==="."?"":j(n),a=await Vt(i,c),u=await tt(a),s=C(a,$(n));if(await me(s,i,!0),t===void 0){await o?.({boundaryRoot:i,relativePath:n,destinationPath:s}),await rt(a,i,u),await me(s,i,!0),await Bt(a,$(n));return}await o?.({boundaryRoot:i,relativePath:n,destinationPath:s}),await rt(a,i,u),await me(s,i,!0),await Nt(a,$(n),t),await me(s,i,!1)}async function Vt(e,r){let t=e;for(const o of r.split("/").filter(Boolean)){t=C(t,o),await Pt(j(t),$(t));const n=await ye(t);if(!n.isDirectory()||n.isSymbolicLink()||await U(t)!==t)throw new Error("continuous-sandbox-write-component-unsafe");Pe(e,t)}return t}async function me(e,r,t){Pe(r,e);try{const o=await ye(e);if(o.isSymbolicLink()||!o.isFile())throw new Error("continuous-sandbox-write-destination-unsafe");if(await U(e)!==e)throw new Error("continuous-sandbox-write-destination-symlink")}catch(o){if(t&&q(o,"ENOENT"))return;throw o}}function Pe(e,r){const t=mt(e,r);if(t===""||t.startsWith("..")||ke(t))throw new Error("continuous-sandbox-write-containment-invalid")}async function tt(e){const r=await ye(e,{bigint:!0});if(!r.isDirectory()||r.isSymbolicLink())throw new Error("continuous-sandbox-write-parent-unsafe");return{dev:r.dev,ino:r.ino}}async function Qt(e,r,t){try{if(e!==r&&Pe(r,e),await U(e)!==e)return!1;const o=await tt(e);return o.dev===t.dev&&o.ino===t.ino}catch{return!1}}async function rt(e,r,t){if(!await Qt(e,r,t))throw new Error("continuous-sandbox-write-parent-raced")}async function Yt(e,r){return await Promise.all(r.map(async t=>{const o=await Ne(C(e,t));return{path:t,...o!==void 0?{content:o}:{}}}))}async function Be(e,r){const t=r.map(o=>o.path);t.length>0&&await se(e,["reset","--quiet","HEAD","--",...t]);for(const o of r)await re(e,o.path,o.content)}async function Zt(e,r){try{const t=C(e.projectRoot,".neocortex/state.json"),o=z(JSON.parse((await B(t)).toString("utf8"))),n=p(p(o.epics)?.[e.epicId]),i=p(n?.branch_lease),c=Object.freeze({schemaVersion:1,ownerStoryId:e.storyId,sessionId:e.dispatchId,idempotencyKey:e.dispatchId,acquiredAt:r,expiresAt:new Date(Date.parse(r)+600*1e3).toISOString()});let a=!1;return await X(e.projectRoot,u=>{const s=we(u,e.epicId),v=p(s.branch_lease)??i;if(v&&typeof v.expiresAt=="string"&&v.expiresAt>r&&(v.ownerStoryId!==e.storyId||v.idempotencyKey!==e.dispatchId)){a=!0;return}s.branch_mode="epic",s.execution_branch=e.executionBranch,s.branch_lease=c}),a?d("continuous-epic-checkout-writer-active"):{ok:!0,value:c}}catch{return d("continuous-writer-lease-persist-failed")}}async function Ut(e){await X(e.projectRoot,r=>{const t=we(r,e.epicId),o=p(t.branch_lease);o?.ownerStoryId===e.storyId&&o.idempotencyKey===e.dispatchId&&(t.branch_lease=null)})}async function ot(e){try{const r=C(e.lease.projectRoot,".neocortex/state.json"),t=Object.freeze({schemaVersion:1,storyId:e.lease.storyId,epicId:e.lease.epicId,branch:e.lease.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.lease.dispatchId,dispatchId:e.lease.dispatchId,bundleId:e.bundle.bundleId,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,claimRevision:e.lease.claimRevision,receiptRefs:Object.freeze([...new Set(e.receiptRefs)]),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:e.qaReceipt,reviewReceipt:e.reviewReceipt,recordedAt:e.recordedAt}),o=z(JSON.parse((await B(r)).toString("utf8"))),n=p(p(o.stories)?.[e.lease.storyId]);let i="persisted",c,a,u,s,v=!1,g;const I=async(h,R,x)=>{const S=await te(e.lease.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),y=await O(e.lease.projectRoot,["rev-parse","HEAD"]);if(S!==e.lease.executionBranch||y!==e.headSha)throw new Error("continuous-checkpoint-head-raced");if(h.graphRevision!==e.lease.graphRevision||h.claimRevision!==e.lease.claimRevision||h.bundleId!==e.bundle.bundleId||h.bundleDigest!==e.bundle.bundleDigest)throw new Error("continuous-checkpoint-graph-raced");const E=x??z(JSON.parse((await B(r)).toString("utf8"))),D=ie(E,R??await V(e.lease.projectRoot)),J=p(p(D.epics)?.[e.lease.epicId]),Re=p(p(D.stories)?.[e.lease.storyId]),M=Array.isArray(Re?.depends_on)?Re.depends_on.filter(H=>typeof H=="string"):[],be=p(D.stories);if(J?.execution_branch!==e.lease.executionBranch||M.some(H=>{const K=p(be?.[H]);return!K||!["done","completed","merged"].includes(String(K.status))}))throw new Error("continuous-checkpoint-dependency-raced");const fe=G(await T(e.lease.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha]));if(fe.length===0||fe.some(H=>!e.lease.authorizedWriteSet.some(K=>ve(K,H))))throw new Error("continuous-checkpoint-write-set-raced");if(!await Ee(e.lease.projectRoot,h,e.lease.storyId,e.lease.epicId,e.lease.executionBranch,void 0,e.lease.authorizedWriteSet))throw new Error("continuous-checkpoint-receipt-revalidation-failed")},b=await V(e.lease.projectRoot,{required:!0}),l=p(p(b.epics[e.lease.epicId])?.branch_lease);if(l?.ownerStoryId!==e.lease.storyId||l.idempotencyKey!==e.lease.dispatchId||l.sessionId!==e.lease.dispatchId||typeof l.expiresAt!="string"||Date.parse(l.expiresAt)<=(e.checkpointNow?.("before-mutation")??Date.now()))return d("continuous-checkpoint-writer-lease-lost");if(!await Ae(e.physicalLock.path,e.physicalLock.owner))return d("continuous-checkpoint-integration-lock-raced");const N=await B(r),k=W("sha256").update(N).digest("hex");await I(t,b);const f=We(z(JSON.parse(N.toString("utf8"))),b,e.lease.epicId,e.lease.storyId);if(f.revision!==e.checkpointAuthority.revision||f.epoch!==e.checkpointAuthority.epoch||f.storyStatus!==e.checkpointAuthority.storyStatus)return d("continuous-graph-revision-stale");const m=await X(e.lease.projectRoot,h=>{const R=we(h,e.lease.epicId),x=p(R.branch_lease);a=x===void 0?void 0:structuredClone(x),u=structuredClone(h),v=h.stories[e.lease.storyId]!==void 0,s=structuredClone(h.stories[e.lease.storyId]??{}),g=structuredClone(R.branch_lease);const S=_t(h,e.lease.storyId),y=p(S.checkpoint)??p(n?.checkpoint);if(y?.idempotencyKey===e.lease.dispatchId){y.baseSha!==e.baseSha||y.headSha!==e.headSha||y.bundleId!==e.bundle.bundleId||y.bundleDigest!==e.bundle.bundleDigest||y.graphRevision!==e.lease.graphRevision||y.claimRevision!==e.lease.claimRevision?i="conflict":(i="reused",c=y,R.branch_lease=null);return}if(x?.ownerStoryId!==e.lease.storyId||x.idempotencyKey!==e.lease.dispatchId||x.sessionId!==e.lease.dispatchId){i="lease-lost";return}S.checkpoint=t,S.status="done",S.last_step=ge;const E=Array.isArray(S.steps_completed)?S.steps_completed.filter(D=>typeof D=="string"):[];S.steps_completed=[...new Set([...E,Ue,ge])],R.branch_lease=null},{expectedRevision:b.revision,preCommit:async h=>{if(a?.ownerStoryId!==e.lease.storyId||a.idempotencyKey!==e.lease.dispatchId||a.sessionId!==e.lease.dispatchId||typeof a.expiresAt!="string"||Date.parse(a.expiresAt)<=(e.checkpointNow?.("pre-commit")??Date.now()))throw new Error("continuous-checkpoint-writer-lease-lost");if(await e.insideCheckpointPreCommit?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),!await Ae(e.physicalLock.path,e.physicalLock.owner))throw new Error("continuous-checkpoint-integration-lock-raced");await I(c??t,h);const R=await B(r);if(W("sha256").update(R).digest("hex")!==k)throw new Error("continuous-graph-revision-stale");if(!u)throw new Error("continuous-checkpoint-authority-missing");const x=z(JSON.parse(R.toString("utf8"))),S=We(x,u,e.lease.epicId,e.lease.storyId);if(S.revision!==e.checkpointAuthority.revision||S.epoch!==e.checkpointAuthority.epoch||S.storyStatus!==e.checkpointAuthority.storyStatus)throw new Error("continuous-graph-revision-stale");if(i==="persisted"&&!Ge(x,h,e.lease,t))throw new Error("continuous-checkpoint-projection-raced")}}),A=i;if(A==="conflict")return d("continuous-checkpoint-idempotency-conflict");if(A==="lease-lost")return d("continuous-checkpoint-writer-lease-lost");if(A==="reused"&&c)try{return await I(c),{ok:!0,value:c}}catch{return d("continuous-checkpoint-reused-evidence-invalid")}try{await e.afterCheckpointPersist?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha});const h=await V(e.lease.projectRoot,{required:!0});if(h.revision!==m.document.revision)throw new Error("continuous-checkpoint-post-persist-runtime-raced");await I(t,h);const R=await B(r);if(W("sha256").update(R).digest("hex")!==k)throw new Error("continuous-checkpoint-post-persist-authority-raced");const x=z(JSON.parse(R.toString("utf8")));if(!Ge(x,h,e.lease,t))throw new Error("continuous-checkpoint-post-persist-projection-raced")}catch{const h=await B(r).catch(()=>{}),R=h===void 0||W("sha256").update(h).digest("hex")!==k;return await X(e.lease.projectRoot,x=>{const S=p(x.epics[e.lease.epicId]),y=p(x.stories[e.lease.storyId]),E=h===void 0?void 0:z(JSON.parse(h.toString("utf8")));if(!S||!y||!E||!Ge(E,x,e.lease,t))throw new Error("continuous-checkpoint-cleanup-cas-conflict");if(R){v?or(y,s??{}):delete x.stories[e.lease.storyId],g===void 0?delete S.branch_lease:S.branch_lease=structuredClone(g);return}y.checkpoint=null,y.status="blocked",S.branch_lease=null},{expectedRevision:m.document.revision}).catch(()=>{}),d("continuous-checkpoint-post-persist-raced")}return{ok:!0,value:t}}catch(r){const t=r instanceof Error&&/^continuous-/.test(r.message)?r.message:"continuous-checkpoint-persist-failed";return d(t)}}async function nt(e){try{if(await O(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return d("continuous-story-evidence-head-raced");const r=await B(C(e.lease.projectRoot,"config","release-gates.v2.json"),"utf8"),t=JSON.parse(r),o=Array.isArray(t.requiredCompleteClasses)?t.requiredCompleteClasses.filter(h=>typeof h=="string"&&/^[a-z0-9-]+$/.test(h)):[];if(t.contract!=="P205-CI-02"||o.length===0)return d("continuous-story-qa-manifest-invalid");const n=xt({processEnv:process.env,platform:process.platform,contract:await kt(e.lease.projectRoot)});if(!n.ok)return d(n.reason);let i;try{i=String((await _e(process.execPath,["scripts/test-root.mjs","--gate","complete"],{cwd:e.lease.projectRoot,env:n.env,encoding:"utf8",maxBuffer:32*1024*1024,timeout:bt(t),killSignal:"SIGTERM"})).stdout)}catch(h){const R=h;return d(Rt({timedOut:R?.killed===!0&&!!R.signal,stderr:typeof R?.stderr=="string"?R.stderr:""}))}if(await e.qaRunner?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),await O(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return d("continuous-story-qa-head-raced");const c=it(e.nowIso),a=await O(e.lease.projectRoot,["rev-list","--count",`${e.baseSha}..${e.headSha}`]),u=await T(e.lease.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),s=G(await T(e.lease.projectRoot,["diff","--name-only","-z",`${e.baseSha}..${e.headSha}`])),v=jt({storyId:e.lease.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,commitBody:u,changedPaths:s}),g=W("sha256").update(r).digest("hex"),I=W("sha256").update(i).digest("hex"),b=Ct({gitEvidenceDigest:v,headSha:e.headSha,graphRevision:e.lease.graphRevision,manifestDigest:g,gateIds:o,resultDigest:I}),l=`story-qa:${b}`,N=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,contract:"P205-CI-02",command:Dt,manifestDigest:g,gateIds:Object.freeze(o),resultDigest:I,sourceEvidenceDigest:b,verdict:"passed",checkedAt:c,receiptRef:l}),k=[`Neocortex-Story: ${e.lease.storyId}`,`Neocortex-Epic: ${e.lease.epicId}`,`Neocortex-Bundle-Digest: ${e.bundle.bundleDigest}`,`Neocortex-Graph-Revision: ${e.lease.graphRevision}`];if(a!=="1"||!k.every(h=>u.includes(h))||s.length===0||s.some(h=>!e.lease.authorizedWriteSet.some(R=>ve(R,h))))return d("continuous-story-review-evidence-rejected");const f=W("sha256").update(["root-commit-range-review-v1",e.lease.storyId,e.baseSha,e.headSha,e.bundle.bundleDigest,e.lease.graphRevision,l,W("sha256").update(u).digest("hex"),[...s].sort().join(",")].join("\0")).digest("hex"),m=`story-review:${f}`,A=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,sourceEvidenceDigest:f,qaReceiptRef:l,verdict:"approved",reviewedAt:c,receiptRef:m});return{ok:!0,value:{qaReceipt:N,reviewReceipt:A}}}catch{return d("continuous-story-evidence-production-failed")}}function it(e){return Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function Xt(e,r,t){if(r!==void 0)try{const o=e===void 0?{}:z(JSON.parse(e.toString("utf8"))),n=z(JSON.parse(r.toString("utf8"))),i=structuredClone(o),c=p(p(o.stories)?.[t]),a=p(p(n.stories)?.[t]),u=er(i,"stories"),s=structuredClone(c??{});for(const v of["status","last_step","steps_completed","last_updated","blocked_reason","blocked_at","implementation_evidence","validation_evidence","qa_gate"])a&&Object.prototype.hasOwnProperty.call(a,v)&&(s[v]=structuredClone(a[v]));return u[t]=s,Buffer.from(`${JSON.stringify(i,null,2)}
52
+ `)}catch{return Buffer.from("{invalid-child-state")}}function er(e,r){const t=p(e[r]);if(t)return t;const o={};return e[r]=o,o}function z(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("record expected");return e}function p(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function tr(e,r,t){return ze(t,e)||ze(r,t)?{ok:!0,value:r}:ze(r,e)?{ok:!0,value:t}:d("continuous-context-merge-conflict")}function rr(e,r,t){try{const o=at($e(e),$e(r),$e(t));return o.ok?{ok:!0,value:o.value===void 0?void 0:Buffer.from(`${JSON.stringify(o.value,null,2)}
53
+ `)}:o}catch{return d("continuous-state-merge-invalid")}}function $e(e){return e===void 0?void 0:JSON.parse(e.toString("utf8"))}function at(e,r,t){if(Se(t,e)||Se(r,t))return{ok:!0,value:r};if(Se(r,e))return{ok:!0,value:t};if(Te(e)&&Te(r)&&Te(t)){const o={};for(const n of[...new Set([...Object.keys(e),...Object.keys(r),...Object.keys(t)])].sort()){const i=at(e[n],r[n],t[n]);if(!i.ok)return i;i.value!==void 0&&(o[n]=i.value)}return{ok:!0,value:o}}if(Array.isArray(e)&&Array.isArray(r)&&Array.isArray(t)&&ct(e,r)&&ct(e,t)){const o=[...e,...r.slice(e.length),...t.slice(e.length)],n=new Set;return{ok:!0,value:o.filter(i=>{const c=JSON.stringify(i);return n.has(c)?!1:(n.add(c),!0)})}}return d("continuous-state-merge-conflict")}function Te(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ct(e,r){return e.length<=r.length&&e.every((t,o)=>Se(t,r[o]))}function Se(e,r){return JSON.stringify(e)===JSON.stringify(r)}function ze(e,r){return e===void 0||r===void 0?e===r:e.equals(r)}function G(e){return e.split("\0").filter(Boolean)}function oe(e){const r=de(e);return r.length>0&&r.length<=1024&&!ke(r)&&!/^[A-Za-z]:\//.test(r)&&!r.split("/").includes("..")&&!r.includes("\0")&&!r.startsWith("/")}function de(e){return e.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/{2,}/g,"/")}function st(e){const r=e.map(de).filter(oe);return[...new Set(r)].sort()}function ve(e,r){const t=de(e),o=de(r);return t===o||t.endsWith("/")&&o.startsWith(t)}function dt(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!e.startsWith("/")&&!e.endsWith("/")&&!e.endsWith(".lock")&&!e.includes("..")&&!e.includes("\\")&&!e.includes("@{")&&!e.includes("//")&&/^[A-Za-z0-9._/-]+$/.test(e)}function ut(e,r){return e.length===r.length&&e.every((t,o)=>t===r[o])}async function ue(e,r,t,o){const n=z(JSON.parse(await B(C(e,".neocortex/state.json"),"utf8")));return We(n,o??await V(e),r,t)}function We(e,r,t,o){const n=ie(e,r),i=p(n.epics),c=p(n.stories),a=p(i?.[t])??{},u=(Array.isArray(a.stories)?a.stories:Array.isArray(a.story_ids)?a.story_ids:[]).filter(I=>typeof I=="string"),s=u.length>0?u:Object.entries(c??{}).filter(([I,b])=>p(b)?.epic_id===t||I.startsWith(`${t}.`)).map(([I])=>I).sort(),v=["status","depends_on","files_to_modify","contracts","contract_refs","shared_surfaces","steps_completed","last_step","branch_name","physicalMergeStatus","merged","checkpoint","planning","attempts","retry_count","rollback_receipt","cancelled_at"],g=Object.fromEntries(s.map(I=>{const b=p(c?.[I])??{};return[I,Object.fromEntries(v.filter(l=>Object.prototype.hasOwnProperty.call(b,l)).map(l=>[l,b[l]]))]}));return{revision:Ie({epicId:t,epic:{stories:s,status:a.status??null,branch_mode:a.branch_mode??null,execution_branch:a.execution_branch??null,graph_revision:a.graph_revision??null,depends_on:a.depends_on??null,planning:a.planning??null,execution_plan:a.execution_plan??null,waves:a.waves??null,current_wave:a.current_wave??null,replan:a.replan??null,replan_revision:a.replan_revision??null,dependency_graph:a.dependency_graph??null,scheduler:a.scheduler??null,attempts:a.attempts??null,retry_count:a.retry_count??null},stories:g}),epoch:typeof a.graph_revision=="string"?a.graph_revision:null,storyStatus:typeof p(c?.[o])?.status=="string"?String(p(c?.[o])?.status):null}}function Ge(e,r,t,o){const n=ie(e,r),i=p(p(n.epics)?.[t.epicId]),c=p(p(n.stories)?.[t.storyId]),a=Array.isArray(c?.steps_completed)?c.steps_completed.filter(u=>typeof u=="string"):[];return!!(i&&c&&i.branch_lease===null&&c.status==="done"&&c.last_step===ge&&a.includes(Ue)&&a.includes(ge)&&he(c.checkpoint)===he(o))}function or(e,r){for(const t of Object.keys(e))delete e[t];Object.assign(e,structuredClone(r))}async function nr(e,r){return(await ue(e,r,"")).revision}function Ie(e){return W("sha256").update(he(e)).digest("hex")}function he(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(he).join(",")}]`:`{${Object.entries(e).sort(([r],[t])=>r.localeCompare(t)).map(([r,t])=>`${JSON.stringify(r)}:${he(t)}`).join(",")}}`}function ir(e,r){const t=(e??[]).filter(o=>/^[A-Za-z0-9._/:@#-]{1,200}$/.test(o)&&!o.includes(".."));return Object.freeze([...new Set(t.length>0?t:[`dispatch:${r}`])].sort())}function ar(e){return e.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,80)}function d(e){return{ok:!1,reasonCode:e}}function q(e,r){return e instanceof Error&&"code"in e&&e.code===r}async function ne(e,r){try{await L(e,r);const t=C(e,"owner.json");await F(t,e);const o=JSON.parse(await B(t,"utf8"));if(!Number.isSafeInteger(o.pid)||Number(o.pid)<=0||typeof o.createdAt!="string"||!Number.isFinite(Date.parse(o.createdAt))||typeof o.nonce!="string"||!/^[a-f0-9]{32}$/.test(o.nonce))throw new Error("continuous-sandbox-lease-owner-invalid");return{pid:Number(o.pid),createdAt:o.createdAt,nonce:o.nonce}}catch(t){if(q(t,"ENOENT"))return;throw t}}function ht(e,r){return e?.pid===r.pid&&e.createdAt===r.createdAt&&e.nonce===r.nonce}function cr(e){try{return process.kill(e,0),!0}catch(r){return q(r,"EPERM")}}async function Le(e,r){try{await L(e,r);const t=C(e,".git");await L(t,e);const o=C(t,"neocortex-sandbox.json");await F(o,t);const n=JSON.parse(await B(o,"utf8"));if(n.schemaVersion!==1||typeof n.workspaceOwnerNonce!="string"||!/^[a-f0-9]{32}$/.test(n.workspaceOwnerNonce)||!/^[a-f0-9]{64}$/.test(n.graphAuthorityRevision)||!(n.graphAuthorityEpoch===null||/^[a-f0-9]{64}$/.test(n.graphAuthorityEpoch))||!(n.graphAuthorityStoryStatus===null||typeof n.graphAuthorityStoryStatus=="string"&&n.graphAuthorityStoryStatus.length<=80)||typeof n.workspaceIdentity?.dev!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.dev)||typeof n.workspaceIdentity?.ino!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.ino))throw new Error("continuous-sandbox-metadata-invalid");return n}catch(t){if(q(t,"ENOENT"))return;throw t}}async function sr(e,r,t,o){await L(e,r);const n=C(e,".git");await L(n,e);const i=C(n,"neocortex-sandbox.json");await re(e,".git/neocortex-sandbox.json",Buffer.from(`${JSON.stringify(t,null,2)}
54
+ `),o),await F(i,n)}async function dr(e,r){try{await F(e,r);const t=JSON.parse(await B(e,"utf8"));return typeof t.childHeadSha=="string"&&typeof t.rootHeadSha=="string"&&/^[a-f0-9]{40,64}$/.test(t.childHeadSha)&&/^[a-f0-9]{40,64}$/.test(t.rootHeadSha)&&t.bundle?.schemaVersion===1&&t.checkpoint?.schemaVersion===1?t:void 0}catch(t){if(q(t,"ENOENT"))return;throw t}}async function ur(e,r){try{const t=z(JSON.parse(await B(C(e.projectRoot,".neocortex/state.json"),"utf8"))),o=ie(t,await V(e.projectRoot)),n=p(p(o.stories)?.[e.storyId]),i=p(n?.checkpoint);return i?.idempotencyKey===r.idempotencyKey&&i.headSha===r.headSha&&i.bundleDigest===r.bundleDigest&&p(p(o.epics)?.[e.epicId])?.branch_lease===null&&await Ee(e.projectRoot,i,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)}catch{return!1}}async function hr(e,r,t){try{const o=z(JSON.parse(await B(C(e.projectRoot,".neocortex/state.json"),"utf8"))),n=ie(o,await V(e.projectRoot)),i=p(p(n.stories)?.[e.storyId]),c=p(i?.checkpoint);return c?.schemaVersion!==1||c.storyId!==e.storyId||c.epicId!==e.epicId||c.branch!==e.executionBranch||c.baseSha!==t.baseSha||c.headSha!==t.headSha||c.idempotencyKey!==e.dispatchId||c.dispatchId!==e.dispatchId||c.bundleId!==r.bundleId||c.bundleDigest!==r.bundleDigest||c.graphRevision!==e.graphRevision||c.claimRevision!==e.claimRevision||p(p(n.epics)?.[e.epicId])?.branch_lease!==null||!await Ee(e.projectRoot,c,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)?void 0:c}catch{return}}async function fr(e,r){const t=(await te(e.projectRoot,["log","--format=%H","--fixed-strings",`--grep=Neocortex-Dispatch: ${e.dispatchId}`]))?.split(`
55
+ `).filter(g=>/^[a-f0-9]{40,64}$/.test(g))??[];if(t.length!==1)return;const o=t[0];if(!await se(e.projectRoot,["merge-base","--is-ancestor",o,"HEAD"]))return;const n=await O(e.projectRoot,["show","-s","--format=%B",o]),i=new Set(n.split(`
56
+ `).map(g=>g.trim()));for(const g of[`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${e.epicId}`,`Neocortex-Execution-Branch: ${e.executionBranch}`,`Neocortex-Prepared-Base: ${e.baseSha}`,`Neocortex-Dispatch: ${e.dispatchId}`,`Neocortex-Bundle: ${r.bundleId}`,`Neocortex-Bundle-Digest: ${r.bundleDigest}`,`Neocortex-Graph-Revision: ${e.graphRevision}`,`Neocortex-Claim-Revision: ${e.claimRevision}`])if(!i.has(g))return;const c=qe(n,"Neocortex-Checkpoint-Authority"),a=qe(n,"Neocortex-Checkpoint-Epoch"),u=qe(n,"Neocortex-Checkpoint-Story-Status");if(!c||!/^[a-f0-9]{64}$/.test(c)||!a||!(a==="null"||/^[a-f0-9]{64}$/.test(a))||!u||u.length>80)return;const s=await te(e.projectRoot,["rev-parse",`${o}^`]);if(!s||!/^[a-f0-9]{40,64}$/.test(s))return;const v=G(await T(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!(v.length===0||v.some(g=>!r.authorizedWriteSet.some(I=>ve(I,g)))))return{baseSha:s,headSha:o,checkpointAuthority:{revision:c,epoch:a==="null"?null:a,storyStatus:u==="null"?null:u}}}function qe(e,r){const t=`${r}: `,o=e.split(`
57
+ `).map(n=>n.trim()).filter(n=>n.startsWith(t));return o.length===1?o[0].slice(t.length):void 0}async function He(e,r,t,o,n,i){const c=j(e);await L(c,j(c));try{await F(e,c)}catch(a){if(!q(a,"ENOENT"))throw a}await re(c,$(e),Buffer.from(`${JSON.stringify({childHeadSha:r,rootHeadSha:t,bundle:o,checkpoint:n})}
58
+ `),i),await F(e,c)}export{zt as STORY_WORKTREE_INTEGRATION_ROOT_OWNED,kr as createAnchoredContinuousStoryCommandRunner,Tt as createBranchlessContinuousStoryWorkspaceManager,Wt as createStoryWorktreeContinuousStoryWorkspaceManager,xr as selectContinuousStoryWorkspaceManager,Gt as selectContinuousStoryWorkspaceStrategy};