@ornexus/neocortex 4.60.71 → 4.60.73

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 (243) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1211 -1217
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +212 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +417 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +251 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +108 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +358 -5
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.js +635 -2
  37. package/packages/client/dist/commands/invoke.js +7200 -143
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  39. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  40. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  42. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  43. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  44. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  45. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  47. package/packages/client/dist/commands/mutation-qa.js +220 -1
  48. package/packages/client/dist/commands/native-agent.js +136 -2
  49. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  50. package/packages/client/dist/commands/planning-generation.js +53 -1
  51. package/packages/client/dist/commands/planning-memory.js +40 -1
  52. package/packages/client/dist/commands/planning-research.js +42 -1
  53. package/packages/client/dist/commands/private-session.js +75 -1
  54. package/packages/client/dist/commands/property-qa.js +139 -1
  55. package/packages/client/dist/commands/qa-control.js +16 -1
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  58. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  59. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  60. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  66. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  67. package/packages/client/dist/commands/refactor-commit.js +399 -13
  68. package/packages/client/dist/commands/refactor-control.js +142 -3
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  70. package/packages/client/dist/commands/refactor-review.js +283 -5
  71. package/packages/client/dist/commands/refactor-root.js +588 -7
  72. package/packages/client/dist/commands/refresh-memory.js +156 -3
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  74. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  75. package/packages/client/dist/config/profile-directory.js +13 -1
  76. package/packages/client/dist/config/resolver-selection.js +278 -1
  77. package/packages/client/dist/config/secure-config.js +281 -12
  78. package/packages/client/dist/config.js +223 -2
  79. package/packages/client/dist/constants.js +25 -1
  80. package/packages/client/dist/context/context-collector.js +222 -2
  81. package/packages/client/dist/context/context-sanitizer.js +145 -1
  82. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  83. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  84. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  85. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  86. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  87. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  88. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  90. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  91. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  92. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  93. package/packages/client/dist/continuity/outbox.js +117 -1
  94. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  95. package/packages/client/dist/continuity/sqlite-store.d.ts +22 -1
  96. package/packages/client/dist/continuity/sqlite-store.js +2612 -81
  97. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  98. package/packages/client/dist/errors/error-messages.js +228 -2
  99. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  100. package/packages/client/dist/evidence/collector.js +347 -1
  101. package/packages/client/dist/evidence/index.js +1 -1
  102. package/packages/client/dist/evidence/types.js +2 -0
  103. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  104. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  105. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  106. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  107. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  108. package/packages/client/dist/git/epic-operational-state.d.ts +198 -0
  109. package/packages/client/dist/git/epic-operational-state.js +672 -0
  110. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  111. package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -1
  112. package/packages/client/dist/git/git-lifecycle-store.js +1981 -9
  113. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  114. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  115. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  116. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  117. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  118. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  119. package/packages/client/dist/i18n/first-run.js +60 -2
  120. package/packages/client/dist/index.js +47 -1
  121. package/packages/client/dist/invocation/invoke-input.js +24 -1
  122. package/packages/client/dist/license/index.js +5 -1
  123. package/packages/client/dist/license/license-client.js +304 -1
  124. package/packages/client/dist/machine/fingerprint.js +163 -2
  125. package/packages/client/dist/machine/index.js +5 -1
  126. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  127. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  128. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  129. package/packages/client/dist/migrations/epic-lifecycle-backfill.d.ts +97 -0
  130. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -0
  131. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  132. package/packages/client/dist/migrations/project-identity.js +493 -7
  133. package/packages/client/dist/migrations/state-json.d.ts +22 -0
  134. package/packages/client/dist/migrations/state-json.js +393 -4
  135. package/packages/client/dist/policy/architecture-policy.js +184 -2
  136. package/packages/client/dist/policy/index.js +7 -1
  137. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  138. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  139. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  140. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  141. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  142. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  143. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  144. package/packages/client/dist/private-execution/delivery.js +410 -13
  145. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  146. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  147. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  148. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  149. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  150. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  151. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  152. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  153. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  154. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  155. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  156. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  157. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  158. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  159. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  160. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  161. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  162. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  163. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  164. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  165. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  166. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  167. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  168. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  169. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  170. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  171. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  172. package/packages/client/dist/private-execution/session-lease.js +63 -1
  173. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  174. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  175. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  176. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  177. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  178. package/packages/client/dist/registry/registry-reconciliation.js +234 -1
  179. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  180. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  181. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  182. package/packages/client/dist/resilience/index.js +8 -1
  183. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  184. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  185. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  186. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  187. package/packages/client/dist/runner/binary.js +404 -1
  188. package/packages/client/dist/runner/cli.js +1571 -17
  189. package/packages/client/dist/runner/headless/adapters.js +49 -1
  190. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  191. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  192. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  193. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  195. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  196. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  197. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  198. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  199. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  200. package/packages/client/dist/runner/headless/resolver.js +231 -1
  201. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  202. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  203. package/packages/client/dist/runner/headless/types.js +574 -2
  204. package/packages/client/dist/runner/local-console.js +396 -13
  205. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  206. package/packages/client/dist/runner/project-identity.js +106 -1
  207. package/packages/client/dist/runner/scheduler.js +995 -7
  208. package/packages/client/dist/runner-cli.js +18 -2
  209. package/packages/client/dist/state/invocation-shape.js +13 -1
  210. package/packages/client/dist/state/project-state-snapshot.d.ts +8 -0
  211. package/packages/client/dist/state/project-state-snapshot.js +1731 -1
  212. package/packages/client/dist/state/state-json-repair.js +785 -3
  213. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  214. package/packages/client/dist/telemetry/index.js +5 -1
  215. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  216. package/packages/client/dist/tier/index.js +5 -1
  217. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  218. package/packages/client/dist/types/index.js +38 -1
  219. package/packages/client/dist/version.js +27 -1
  220. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  221. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  222. package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
  223. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  224. package/packages/client/dist/yoloop/index.js +8 -1
  225. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  226. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  227. package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +65 -1
  228. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  229. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  230. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +8 -0
  231. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
  232. package/packages/shared/dist/yolo/spec-envelope.js +3 -6
  233. package/targets-stubs/antigravity/gemini.md +1 -1
  234. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  235. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  237. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  238. package/targets-stubs/claude-code/neocortex.md +2 -2
  239. package/targets-stubs/codex/AGENTS.md +1 -1
  240. package/targets-stubs/cursor/agent.md +2 -2
  241. package/targets-stubs/gemini-cli/agent.md +2 -2
  242. package/targets-stubs/opencode/neocortex-root.md +1 -1
  243. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,4 +1,348 @@
1
- import{execFileSync as T}from"node:child_process";import{createHash as w,randomBytes as V}from"node:crypto";import{closeSync as G,constants as B,existsSync as L,fstatSync as U,openSync as M,readFileSync as Y,realpathSync as y}from"node:fs";import{join as d,resolve as O}from"node:path";import{resolveBranchUnit as K}from"../../../shared/dist/yoloop/branch-unit.js";import{acquireGitLifecyclePhysicalIntegrationLock as Q,assertGitLifecyclePrivateFile as S,ensureGitLifecyclePrivateChildDirectory as X,gitLifecycleRuntimeDirectory as ee,releaseGitLifecyclePhysicalIntegrationLock as re}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as te}from"./git-lifecycle-step-ids.js";import{anchoredAtomicWriteFile as N}from"./secure-filesystem-boundary.js";const ae="legacy-story-branch-intents";function x(r){return`${w("sha256").update(r).digest("hex")}.json`}function _(r){return`${w("sha256").update(r).digest("hex")}.completed.json`}function P(r){return w("sha256").update(JSON.stringify(r)).digest("hex")}async function k(r){return X(await ee(r),ae)}function ne(r,e){const t=f(r);if(!t||Object.keys(t).sort().join(",")!==["baseBranch","baseHeadSha","branch","currentHeadSha","epicId","existingBranchHeadSha","kind","localOnly","schemaVersion","stateSha256","storyId","worktreePath"].sort().join(",")||t.schemaVersion!==1||t.kind!=="legacy-story-branch-plan"||t.storyId!==e||t.localOnly!==!0||t.existingBranchHeadSha!==null||typeof t.epicId!="string"||typeof t.branch!="string"||typeof t.baseBranch!="string"||typeof t.worktreePath!="string"||![t.baseHeadSha,t.currentHeadSha,t.stateSha256].every(a=>typeof a=="string"&&/^[0-9a-f]{40,64}$/.test(a)))throw new Error("legacy-branch-intent-invalid");return t}async function R(r,e){const t=await k(r),a=d(t,x(e));if(!L(a))return null;await S(a,t);const c=b(a);if(c.length>4096)throw new Error("legacy-branch-intent-invalid");return ne(JSON.parse(c),e)}async function ce(r,e){const t=await k(r),a=await R(r,e.storyId);if(a){if(JSON.stringify(a)!==JSON.stringify(e))throw new Error("legacy-branch-intent-conflict");return}await N(t,x(e.storyId),`${JSON.stringify(e)}
2
- `),await S(d(t,x(e.storyId)),t)}async function z(r,e){const t=await k(r),a=d(t,_(e.storyId));if(!L(a))return!1;await S(a,t);const c=b(a);if(c.length>512)throw new Error("legacy-branch-completion-invalid");const n=f(JSON.parse(c));if(!n||Object.keys(n).sort().join(",")!=="kind,planDigest,schemaVersion,storyId"||n.schemaVersion!==1||n.kind!=="legacy-story-branch-switch-completed"||n.storyId!==e.storyId||n.planDigest!==P(e))throw new Error("legacy-branch-completion-invalid");return!0}async function oe(r,e){if(await z(r,e))return;const t=await k(r);await N(t,_(e.storyId),`${JSON.stringify({schemaVersion:1,kind:"legacy-story-branch-switch-completed",storyId:e.storyId,planDigest:P(e)})}
3
- `),await S(d(t,_(e.storyId)),t)}function i(r){return{ok:!1,reasonCode:r}}function A(r,e){return T("git",[...e],{cwd:r,encoding:"utf8",stdio:["ignore","pipe","pipe"],maxBuffer:4*1024*1024})}function o(r,e){return A(r,e).trim()}function H(r,e){try{return o(r,e),!0}catch{return!1}}function f(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function m(r,e){return e.length>0&&e.length<=200&&!e.startsWith("-")&&!e.includes("..")&&!e.includes("@{")&&H(r,["check-ref-format","--branch",e])}function b(r){const e=M(r,B.O_RDONLY|(B.O_NOFOLLOW??0));try{const t=U(e);if(!t.isFile()||t.size>2*1024*1024)throw new Error("legacy-branch-state-unsafe");return Y(e,"utf8")}finally{G(e)}}function W(r){return o(r,["worktree","list","--porcelain"]).split(/\n\n+/).flatMap(e=>{const t=e.split(`
4
- `),a=t.find(n=>n.startsWith("worktree ")),c=t.find(n=>n.startsWith("branch refs/heads/"));return!a||!c?[]:[{path:a.slice(9),branch:c.slice(18),unsafe:t.some(n=>n.startsWith("prunable")||n.startsWith("locked"))}]})}function se(r){const e=y(r.projectRoot);if(!/^[A-Za-z0-9][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(r.storyId))throw new Error("legacy-branch-story-id-invalid");if(y(o(e,["rev-parse","--show-toplevel"]))!==e)throw new Error("legacy-branch-project-root-invalid");const t=d(e,".neocortex/state.json"),a=b(t),c=f(JSON.parse(a)),n=f(c?.stories),u=f(c?.epics),h=f(n?.[r.storyId]),s=h?.epic_id,g=typeof s=="string"?f(u?.[s]):null;if(!h||h.id!==r.storyId||typeof s!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(s)||!g||g.id!==s)throw new Error("legacy-branch-story-state-invalid");const J=Object.entries(n??{}).flatMap(([p,q])=>{const D=f(q);return D?.epic_id===s?[{...D,id:p}]:[]});if(K(g,J).mode!=="story"||g.branch_mode==="epic")throw new Error("legacy-branch-mode-invalid");if(h.status!=="backlog"&&h.status!=="ready_to_start")throw new Error("legacy-branch-story-status-invalid");if(!Array.isArray(h.steps_completed)||h.steps_completed.includes(te)||h.branch_name)throw new Error("legacy-branch-story-already-started");const v=f(c?.config)?.default_branch,I=`story/${s}/${r.storyId}`;if(typeof v!="string"||!m(e,v)||!m(e,I)||!m(e,`epic/${s}`))throw new Error("legacy-branch-ref-invalid");const E=W(e).filter(p=>p.branch===`epic/${s}`);if(E.length!==1||E[0].unsafe)throw new Error("legacy-branch-epic-worktree-unavailable");const l=y(E[0].path);if(typeof g.worktree_path=="string"&&y(O(e,g.worktree_path))!==l)throw new Error("legacy-branch-epic-worktree-mismatch");const $=p=>y(O(p,o(p,["rev-parse","--git-common-dir"])));if($(l)!==$(e)||y(o(l,["rev-parse","--show-toplevel"]))!==l||o(l,["symbolic-ref","--quiet","--short","HEAD"])!==`epic/${s}`)throw new Error("legacy-branch-worktree-identity-invalid");const Z=d(l,".neocortex/state.json");if(b(Z)!==a)throw new Error("legacy-branch-worktree-state-mismatch");if(o(l,["status","--porcelain=v1","-uall"])!=="")throw new Error("legacy-branch-worktree-dirty");const j=`refs/remotes/origin/${v}`;if(!H(l,["show-ref","--verify","--quiet",j]))throw new Error("legacy-branch-origin-ref-missing");if(A(l,["show",`${j}:.neocortex/state.json`])!==a)throw new Error("legacy-branch-origin-state-mismatch");const F=`refs/heads/${I}`;if(H(l,["show-ref","--verify","--quiet",F]))throw new Error("legacy-branch-existing-ref-needs-review");return Object.freeze({schemaVersion:1,kind:"legacy-story-branch-plan",storyId:r.storyId,epicId:s,worktreePath:l,branch:I,baseBranch:v,baseHeadSha:o(l,["rev-parse",j]),currentHeadSha:o(l,["rev-parse","HEAD"]),existingBranchHeadSha:null,stateSha256:w("sha256").update(a).digest("hex"),localOnly:!0})}function C(r){try{return{ok:!0,value:se(r)}}catch(e){return i(e instanceof Error&&e.message.startsWith("legacy-branch-")?e.message:"legacy-branch-preflight-failed")}}async function ie(r){try{const e=y(r.projectRoot);if(y(o(e,["rev-parse","--show-toplevel"]))!==e||!/^[A-Za-z0-9][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(r.storyId))return i("legacy-branch-project-root-invalid");const t=await R(e,r.storyId);return t?await z(e,t)?{ok:!0,value:t}:i("legacy-branch-completion-missing"):i("legacy-branch-intent-missing")}catch(e){return i(e instanceof Error&&e.message.startsWith("legacy-branch-")?e.message:"legacy-branch-completion-read-failed")}}async function he(r){try{const e=y(r.projectRoot),t=await ie(r);if(!t.ok)return t;const a=t.value;if(a.epicId!==r.storyId.split(".")[0]||a.branch!==`story/${a.epicId}/${r.storyId}`||!m(e,a.branch)||!m(e,a.baseBranch)||y(a.worktreePath)!==a.worktreePath)return i("legacy-branch-intent-invalid");const c=W(e).filter(s=>s.branch===a.branch);if(c.length!==1||c[0].unsafe||y(c[0].path)!==a.worktreePath)return i("legacy-branch-story-worktree-mismatch");const n=a.worktreePath,u=s=>y(O(s,o(s,["rev-parse","--git-common-dir"])));if(u(n)!==u(e)||y(o(n,["rev-parse","--show-toplevel"]))!==n||o(n,["symbolic-ref","--quiet","--short","HEAD"])!==a.branch||o(n,["rev-parse","HEAD"])!==a.baseHeadSha||o(n,["rev-parse",`refs/heads/${a.branch}`])!==a.baseHeadSha||o(n,["rev-parse",`refs/remotes/origin/${a.baseBranch}`])!==a.baseHeadSha)return i("legacy-branch-physical-identity-mismatch");const h=b(d(n,".neocortex/state.json"));return w("sha256").update(h).digest("hex")!==a.stateSha256||A(n,["show","HEAD:.neocortex/state.json"])!==h||o(n,["status","--porcelain=v1","-uall"])!==""?i("legacy-branch-physical-state-mismatch"):{ok:!0,value:Object.freeze({...a,kind:"legacy-story-branch-setup-receipt",headSha:a.baseHeadSha,reused:!0,checkpointAccepted:!1})}}catch(e){return i(e instanceof Error&&e.message.startsWith("legacy-branch-")?e.message:"legacy-branch-verification-failed")}}async function ve(r){const e=C(r);if(!e.ok){if(e.reasonCode==="legacy-branch-epic-worktree-unavailable"){const c=await he(r);return c.ok?c:e}return e}const t=`legacy-setup-${V(16).toString("hex")}`,a=await Q(r.projectRoot,{kind:"direct",storyId:r.storyId,sessionId:t,idempotencyKey:t,expiresAt:new Date(Date.now()+5*6e4).toISOString(),persistent:!1});if(!a.ok)return i(a.reasonCode);try{const c=C(r);if(!c.ok||JSON.stringify(c.value)!==JSON.stringify(e.value))return i("legacy-branch-preflight-raced");const{worktreePath:n,branch:u,baseBranch:h}=c.value;await ce(r.projectRoot,c.value),o(n,["switch","-c",u,`refs/remotes/origin/${h}`]);const s=o(n,["rev-parse","HEAD"]);return o(n,["symbolic-ref","--quiet","--short","HEAD"])!==u||s!==c.value.baseHeadSha||o(n,["status","--porcelain=v1","-uall"])!==""||w("sha256").update(b(d(n,".neocortex/state.json"))).digest("hex")!==c.value.stateSha256?i("legacy-branch-post-switch-invalid"):(await oe(r.projectRoot,c.value),{ok:!0,value:Object.freeze({...c.value,kind:"legacy-story-branch-setup-receipt",headSha:s,reused:!1,checkpointAccepted:!1})})}catch(c){return i(c instanceof Error&&c.message.startsWith("legacy-branch-")?c.message:"legacy-branch-switch-failed")}finally{await re(a.path,a.owner).catch(()=>{})}}export{C as planLegacyStoryBranchSetup,ve as prepareLegacyStoryBranchSetup,ie as readCompletedLegacyStoryBranchPlan,he as verifyLegacyStoryBranchSetup};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * Root-owned physical branch preparation for projects that recorded the
6
+ * legacy story-branch topology. It deliberately leaves state and story
7
+ * checkpoint acceptance to a separate root transaction.
8
+ */
9
+ import { execFileSync } from 'node:child_process';
10
+ import { createHash, randomBytes } from 'node:crypto';
11
+ import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from 'node:fs';
12
+ import { join, resolve } from 'node:path';
13
+ import { resolveBranchUnit } from '../../../shared/dist/yoloop/branch-unit.js';
14
+ import { acquireGitLifecyclePhysicalIntegrationLock, assertGitLifecyclePrivateFile, ensureGitLifecyclePrivateChildDirectory, gitLifecycleRuntimeDirectory, releaseGitLifecyclePhysicalIntegrationLock, } from './git-lifecycle-store.js';
15
+ import { GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID } from './git-lifecycle-step-ids.js';
16
+ import { anchoredAtomicWriteFile } from './secure-filesystem-boundary.js';
17
+ const INTENT_DIRECTORY = 'legacy-story-branch-intents';
18
+ function intentName(storyId) {
19
+ return `${createHash('sha256').update(storyId).digest('hex')}.json`;
20
+ }
21
+ function completionName(storyId) {
22
+ return `${createHash('sha256').update(storyId).digest('hex')}.completed.json`;
23
+ }
24
+ function planDigest(plan) {
25
+ return createHash('sha256').update(JSON.stringify(plan)).digest('hex');
26
+ }
27
+ async function intentDirectory(projectRoot) {
28
+ return ensureGitLifecyclePrivateChildDirectory(await gitLifecycleRuntimeDirectory(projectRoot), INTENT_DIRECTORY);
29
+ }
30
+ function validatedIntent(value, storyId) {
31
+ const row = record(value);
32
+ if (!row || Object.keys(row).sort().join(',') !== [
33
+ 'baseBranch', 'baseHeadSha', 'branch', 'currentHeadSha', 'epicId',
34
+ 'existingBranchHeadSha', 'kind', 'localOnly', 'schemaVersion',
35
+ 'stateSha256', 'storyId', 'worktreePath',
36
+ ].sort().join(',') || row.schemaVersion !== 1 || row.kind !== 'legacy-story-branch-plan'
37
+ || row.storyId !== storyId || row.localOnly !== true || row.existingBranchHeadSha !== null
38
+ || typeof row.epicId !== 'string' || typeof row.branch !== 'string'
39
+ || typeof row.baseBranch !== 'string' || typeof row.worktreePath !== 'string'
40
+ || ![row.baseHeadSha, row.currentHeadSha, row.stateSha256].every((item) => typeof item === 'string' && /^[0-9a-f]{40,64}$/.test(item))) {
41
+ throw new Error('legacy-branch-intent-invalid');
42
+ }
43
+ return row;
44
+ }
45
+ async function readIntent(projectRoot, storyId) {
46
+ const directory = await intentDirectory(projectRoot);
47
+ const path = join(directory, intentName(storyId));
48
+ if (!existsSync(path))
49
+ return null;
50
+ await assertGitLifecyclePrivateFile(path, directory);
51
+ const raw = readSafeState(path);
52
+ if (raw.length > 4096)
53
+ throw new Error('legacy-branch-intent-invalid');
54
+ return validatedIntent(JSON.parse(raw), storyId);
55
+ }
56
+ async function persistIntent(projectRoot, plan) {
57
+ const directory = await intentDirectory(projectRoot);
58
+ const prior = await readIntent(projectRoot, plan.storyId);
59
+ if (prior) {
60
+ if (JSON.stringify(prior) !== JSON.stringify(plan))
61
+ throw new Error('legacy-branch-intent-conflict');
62
+ return;
63
+ }
64
+ await anchoredAtomicWriteFile(directory, intentName(plan.storyId), `${JSON.stringify(plan)}\n`);
65
+ await assertGitLifecyclePrivateFile(join(directory, intentName(plan.storyId)), directory);
66
+ }
67
+ async function hasMatchingCompletion(projectRoot, plan) {
68
+ const directory = await intentDirectory(projectRoot);
69
+ const path = join(directory, completionName(plan.storyId));
70
+ if (!existsSync(path))
71
+ return false;
72
+ await assertGitLifecyclePrivateFile(path, directory);
73
+ const raw = readSafeState(path);
74
+ if (raw.length > 512)
75
+ throw new Error('legacy-branch-completion-invalid');
76
+ const row = record(JSON.parse(raw));
77
+ if (!row || Object.keys(row).sort().join(',') !== 'kind,planDigest,schemaVersion,storyId'
78
+ || row.schemaVersion !== 1 || row.kind !== 'legacy-story-branch-switch-completed'
79
+ || row.storyId !== plan.storyId || row.planDigest !== planDigest(plan)) {
80
+ throw new Error('legacy-branch-completion-invalid');
81
+ }
82
+ return true;
83
+ }
84
+ async function persistCompletion(projectRoot, plan) {
85
+ if (await hasMatchingCompletion(projectRoot, plan))
86
+ return;
87
+ const directory = await intentDirectory(projectRoot);
88
+ await anchoredAtomicWriteFile(directory, completionName(plan.storyId), `${JSON.stringify({
89
+ schemaVersion: 1, kind: 'legacy-story-branch-switch-completed',
90
+ storyId: plan.storyId, planDigest: planDigest(plan),
91
+ })}\n`);
92
+ await assertGitLifecyclePrivateFile(join(directory, completionName(plan.storyId)), directory);
93
+ }
94
+ function failure(reasonCode) {
95
+ return { ok: false, reasonCode };
96
+ }
97
+ function gitRaw(cwd, args) {
98
+ return execFileSync('git', [...args], { cwd, encoding: 'utf8',
99
+ stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 * 1024 * 1024 });
100
+ }
101
+ function git(cwd, args) {
102
+ return gitRaw(cwd, args).trim();
103
+ }
104
+ function gitOk(cwd, args) {
105
+ try {
106
+ git(cwd, args);
107
+ return true;
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
113
+ function record(value) {
114
+ return value && typeof value === 'object' && !Array.isArray(value)
115
+ ? value : null;
116
+ }
117
+ function safeBranch(cwd, name) {
118
+ return name.length > 0 && name.length <= 200 && !name.startsWith('-')
119
+ && !name.includes('..') && !name.includes('@{')
120
+ && gitOk(cwd, ['check-ref-format', '--branch', name]);
121
+ }
122
+ function readSafeState(path) {
123
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
124
+ try {
125
+ const stat = fstatSync(fd);
126
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024)
127
+ throw new Error('legacy-branch-state-unsafe');
128
+ return readFileSync(fd, 'utf8');
129
+ }
130
+ finally {
131
+ closeSync(fd);
132
+ }
133
+ }
134
+ function worktrees(cwd) {
135
+ return git(cwd, ['worktree', 'list', '--porcelain']).split(/\n\n+/).flatMap((block) => {
136
+ const lines = block.split('\n');
137
+ const pathLine = lines.find((line) => line.startsWith('worktree '));
138
+ const branchLine = lines.find((line) => line.startsWith('branch refs/heads/'));
139
+ if (!pathLine || !branchLine)
140
+ return [];
141
+ return [{ path: pathLine.slice('worktree '.length),
142
+ branch: branchLine.slice('branch refs/heads/'.length),
143
+ unsafe: lines.some((line) => line.startsWith('prunable') || line.startsWith('locked')) }];
144
+ });
145
+ }
146
+ function inspect(options) {
147
+ const projectRoot = realpathSync(options.projectRoot);
148
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(options.storyId)) {
149
+ throw new Error('legacy-branch-story-id-invalid');
150
+ }
151
+ if (realpathSync(git(projectRoot, ['rev-parse', '--show-toplevel'])) !== projectRoot) {
152
+ throw new Error('legacy-branch-project-root-invalid');
153
+ }
154
+ const statePath = join(projectRoot, '.neocortex/state.json');
155
+ const rawState = readSafeState(statePath);
156
+ const state = record(JSON.parse(rawState));
157
+ const stories = record(state?.stories);
158
+ const epics = record(state?.epics);
159
+ const story = record(stories?.[options.storyId]);
160
+ const epicId = story?.epic_id;
161
+ const epic = typeof epicId === 'string' ? record(epics?.[epicId]) : null;
162
+ if (!story || story.id !== options.storyId || typeof epicId !== 'string'
163
+ || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(epicId) || !epic || epic.id !== epicId) {
164
+ throw new Error('legacy-branch-story-state-invalid');
165
+ }
166
+ const epicStories = Object.entries(stories ?? {}).flatMap(([id, value]) => {
167
+ const row = record(value);
168
+ return row?.epic_id === epicId ? [{ ...row, id }] : [];
169
+ });
170
+ const branchUnit = resolveBranchUnit(epic, epicStories);
171
+ if (branchUnit.mode !== 'story' || epic.branch_mode === 'epic') {
172
+ throw new Error('legacy-branch-mode-invalid');
173
+ }
174
+ if (story.status !== 'backlog' && story.status !== 'ready_to_start') {
175
+ throw new Error('legacy-branch-story-status-invalid');
176
+ }
177
+ if (!Array.isArray(story.steps_completed)
178
+ || story.steps_completed.includes(GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID) || story.branch_name) {
179
+ throw new Error('legacy-branch-story-already-started');
180
+ }
181
+ const config = record(state?.config);
182
+ const baseBranch = config?.default_branch;
183
+ const branch = `story/${epicId}/${options.storyId}`;
184
+ if (typeof baseBranch !== 'string' || !safeBranch(projectRoot, baseBranch)
185
+ || !safeBranch(projectRoot, branch) || !safeBranch(projectRoot, `epic/${epicId}`)) {
186
+ throw new Error('legacy-branch-ref-invalid');
187
+ }
188
+ const candidates = worktrees(projectRoot).filter((item) => item.branch === `epic/${epicId}`);
189
+ if (candidates.length !== 1 || candidates[0].unsafe)
190
+ throw new Error('legacy-branch-epic-worktree-unavailable');
191
+ const worktreePath = realpathSync(candidates[0].path);
192
+ if (typeof epic.worktree_path === 'string'
193
+ && realpathSync(resolve(projectRoot, epic.worktree_path)) !== worktreePath) {
194
+ throw new Error('legacy-branch-epic-worktree-mismatch');
195
+ }
196
+ const common = (cwd) => realpathSync(resolve(cwd, git(cwd, ['rev-parse', '--git-common-dir'])));
197
+ if (common(worktreePath) !== common(projectRoot)
198
+ || realpathSync(git(worktreePath, ['rev-parse', '--show-toplevel'])) !== worktreePath
199
+ || git(worktreePath, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== `epic/${epicId}`) {
200
+ throw new Error('legacy-branch-worktree-identity-invalid');
201
+ }
202
+ const worktreeStatePath = join(worktreePath, '.neocortex/state.json');
203
+ if (readSafeState(worktreeStatePath) !== rawState) {
204
+ throw new Error('legacy-branch-worktree-state-mismatch');
205
+ }
206
+ if (git(worktreePath, ['status', '--porcelain=v1', '-uall']) !== '') {
207
+ throw new Error('legacy-branch-worktree-dirty');
208
+ }
209
+ const baseRef = `refs/remotes/origin/${baseBranch}`;
210
+ if (!gitOk(worktreePath, ['show-ref', '--verify', '--quiet', baseRef])) {
211
+ throw new Error('legacy-branch-origin-ref-missing');
212
+ }
213
+ if (gitRaw(worktreePath, ['show', `${baseRef}:.neocortex/state.json`]) !== rawState) {
214
+ throw new Error('legacy-branch-origin-state-mismatch');
215
+ }
216
+ const existingRef = `refs/heads/${branch}`;
217
+ // A same-named ref is not a provenance receipt. It may belong to a previous
218
+ // attempt or another worktree, so manual reconciliation is required.
219
+ if (gitOk(worktreePath, ['show-ref', '--verify', '--quiet', existingRef])) {
220
+ throw new Error('legacy-branch-existing-ref-needs-review');
221
+ }
222
+ return Object.freeze({ schemaVersion: 1, kind: 'legacy-story-branch-plan',
223
+ storyId: options.storyId, epicId, worktreePath, branch, baseBranch,
224
+ baseHeadSha: git(worktreePath, ['rev-parse', baseRef]),
225
+ currentHeadSha: git(worktreePath, ['rev-parse', 'HEAD']),
226
+ existingBranchHeadSha: null, stateSha256: createHash('sha256').update(rawState).digest('hex'),
227
+ localOnly: true });
228
+ }
229
+ /** Read-only physical planning; no fetch, checkout, issue creation or state write. */
230
+ export function planLegacyStoryBranchSetup(options) {
231
+ try {
232
+ return { ok: true, value: inspect(options) };
233
+ }
234
+ catch (error) {
235
+ return failure(error instanceof Error && error.message.startsWith('legacy-branch-')
236
+ ? error.message : 'legacy-branch-preflight-failed');
237
+ }
238
+ }
239
+ /** Local-only completion record; callers must still recompute physical truth. */
240
+ export async function readCompletedLegacyStoryBranchPlan(options) {
241
+ try {
242
+ const projectRoot = realpathSync(options.projectRoot);
243
+ if (realpathSync(git(projectRoot, ['rev-parse', '--show-toplevel'])) !== projectRoot
244
+ || !/^[A-Za-z0-9][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(options.storyId)) {
245
+ return failure('legacy-branch-project-root-invalid');
246
+ }
247
+ const plan = await readIntent(projectRoot, options.storyId);
248
+ if (!plan)
249
+ return failure('legacy-branch-intent-missing');
250
+ if (!await hasMatchingCompletion(projectRoot, plan))
251
+ return failure('legacy-branch-completion-missing');
252
+ return { ok: true, value: plan };
253
+ }
254
+ catch (error) {
255
+ return failure(error instanceof Error && error.message.startsWith('legacy-branch-')
256
+ ? error.message : 'legacy-branch-completion-read-failed');
257
+ }
258
+ }
259
+ /** Proves a switched branch against the private intent durably written before switch. */
260
+ export async function verifyLegacyStoryBranchSetup(options) {
261
+ try {
262
+ const projectRoot = realpathSync(options.projectRoot);
263
+ const completed = await readCompletedLegacyStoryBranchPlan(options);
264
+ if (!completed.ok)
265
+ return completed;
266
+ const plan = completed.value;
267
+ if (plan.epicId !== options.storyId.split('.')[0]
268
+ || plan.branch !== `story/${plan.epicId}/${options.storyId}`
269
+ || !safeBranch(projectRoot, plan.branch) || !safeBranch(projectRoot, plan.baseBranch)
270
+ || realpathSync(plan.worktreePath) !== plan.worktreePath) {
271
+ return failure('legacy-branch-intent-invalid');
272
+ }
273
+ const candidates = worktrees(projectRoot).filter((item) => item.branch === plan.branch);
274
+ if (candidates.length !== 1 || candidates[0].unsafe
275
+ || realpathSync(candidates[0].path) !== plan.worktreePath) {
276
+ return failure('legacy-branch-story-worktree-mismatch');
277
+ }
278
+ const cwd = plan.worktreePath;
279
+ const common = (path) => realpathSync(resolve(path, git(path, ['rev-parse', '--git-common-dir'])));
280
+ if (common(cwd) !== common(projectRoot)
281
+ || realpathSync(git(cwd, ['rev-parse', '--show-toplevel'])) !== cwd
282
+ || git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== plan.branch
283
+ || git(cwd, ['rev-parse', 'HEAD']) !== plan.baseHeadSha
284
+ || git(cwd, ['rev-parse', `refs/heads/${plan.branch}`]) !== plan.baseHeadSha
285
+ || git(cwd, ['rev-parse', `refs/remotes/origin/${plan.baseBranch}`]) !== plan.baseHeadSha) {
286
+ return failure('legacy-branch-physical-identity-mismatch');
287
+ }
288
+ const rawState = readSafeState(join(cwd, '.neocortex/state.json'));
289
+ if (createHash('sha256').update(rawState).digest('hex') !== plan.stateSha256
290
+ || gitRaw(cwd, ['show', 'HEAD:.neocortex/state.json']) !== rawState
291
+ || git(cwd, ['status', '--porcelain=v1', '-uall']) !== '') {
292
+ return failure('legacy-branch-physical-state-mismatch');
293
+ }
294
+ return { ok: true, value: Object.freeze({ ...plan,
295
+ kind: 'legacy-story-branch-setup-receipt', headSha: plan.baseHeadSha,
296
+ reused: true, checkpointAccepted: false }) };
297
+ }
298
+ catch (error) {
299
+ return failure(error instanceof Error && error.message.startsWith('legacy-branch-')
300
+ ? error.message : 'legacy-branch-verification-failed');
301
+ }
302
+ }
303
+ /** Switches only the proven epic worktree; root checkpoint acceptance is separate. */
304
+ export async function prepareLegacyStoryBranchSetup(options) {
305
+ const initial = planLegacyStoryBranchSetup(options);
306
+ if (!initial.ok) {
307
+ if (initial.reasonCode === 'legacy-branch-epic-worktree-unavailable') {
308
+ const recovered = await verifyLegacyStoryBranchSetup(options);
309
+ return recovered.ok ? recovered : initial;
310
+ }
311
+ return initial;
312
+ }
313
+ const sessionId = `legacy-setup-${randomBytes(16).toString('hex')}`;
314
+ const lock = await acquireGitLifecyclePhysicalIntegrationLock(options.projectRoot, {
315
+ kind: 'direct', storyId: options.storyId, sessionId, idempotencyKey: sessionId,
316
+ expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), persistent: false,
317
+ });
318
+ if (!lock.ok)
319
+ return failure(lock.reasonCode);
320
+ try {
321
+ const checked = planLegacyStoryBranchSetup(options);
322
+ if (!checked.ok || JSON.stringify(checked.value) !== JSON.stringify(initial.value)) {
323
+ return failure('legacy-branch-preflight-raced');
324
+ }
325
+ const { worktreePath, branch, baseBranch } = checked.value;
326
+ await persistIntent(options.projectRoot, checked.value);
327
+ git(worktreePath, ['switch', '-c', branch, `refs/remotes/origin/${baseBranch}`]);
328
+ const headSha = git(worktreePath, ['rev-parse', 'HEAD']);
329
+ if (git(worktreePath, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== branch
330
+ || headSha !== checked.value.baseHeadSha
331
+ || git(worktreePath, ['status', '--porcelain=v1', '-uall']) !== ''
332
+ || createHash('sha256').update(readSafeState(join(worktreePath, '.neocortex/state.json'))).digest('hex')
333
+ !== checked.value.stateSha256) {
334
+ return failure('legacy-branch-post-switch-invalid');
335
+ }
336
+ await persistCompletion(options.projectRoot, checked.value);
337
+ return { ok: true, value: Object.freeze({ ...checked.value,
338
+ kind: 'legacy-story-branch-setup-receipt', headSha,
339
+ reused: false, checkpointAccepted: false }) };
340
+ }
341
+ catch (error) {
342
+ return failure(error instanceof Error && error.message.startsWith('legacy-branch-')
343
+ ? error.message : 'legacy-branch-switch-failed');
344
+ }
345
+ finally {
346
+ await releaseGitLifecyclePhysicalIntegrationLock(lock.path, lock.owner).catch(() => undefined);
347
+ }
348
+ }