@ornexus/neocortex 4.60.73 → 4.60.75

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 (269) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -212
  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 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.d.ts +27 -0
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  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 -358
  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 +38 -1
  39. package/packages/client/dist/commands/invoke.js +143 -7200
  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 -156
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  77. package/packages/client/dist/config/host-auth-broker.d.ts +31 -0
  78. package/packages/client/dist/config/host-auth-broker.js +1 -0
  79. package/packages/client/dist/config/host-auth-reference.d.ts +32 -0
  80. package/packages/client/dist/config/host-auth-reference.js +1 -0
  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 -223
  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.d.ts +11 -0
  99. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  100. package/packages/client/dist/continuity/outbox.js +1 -117
  101. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  102. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  103. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  104. package/packages/client/dist/errors/error-messages.d.ts +3 -0
  105. package/packages/client/dist/errors/error-messages.js +2 -228
  106. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  107. package/packages/client/dist/evidence/collector.js +1 -347
  108. package/packages/client/dist/evidence/index.js +1 -1
  109. package/packages/client/dist/evidence/types.js +0 -2
  110. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  111. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  112. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  113. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  114. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +11 -1
  115. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  116. package/packages/client/dist/git/epic-operational-state.js +2 -672
  117. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  118. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  119. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  120. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  121. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  122. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  123. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  124. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  125. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  126. package/packages/client/dist/i18n/first-run.js +2 -60
  127. package/packages/client/dist/index.d.ts +2 -0
  128. package/packages/client/dist/index.js +1 -47
  129. package/packages/client/dist/invocation/invoke-input.js +1 -24
  130. package/packages/client/dist/license/host-auth-recovery.d.ts +158 -0
  131. package/packages/client/dist/license/host-auth-recovery.js +1 -0
  132. package/packages/client/dist/license/index.js +1 -5
  133. package/packages/client/dist/license/license-client.d.ts +10 -1
  134. package/packages/client/dist/license/license-client.js +1 -304
  135. package/packages/client/dist/machine/fingerprint.js +2 -163
  136. package/packages/client/dist/machine/index.js +1 -5
  137. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  138. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  139. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  140. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  141. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  142. package/packages/client/dist/migrations/project-identity.js +7 -493
  143. package/packages/client/dist/migrations/state-json.js +4 -393
  144. package/packages/client/dist/policy/architecture-policy.js +2 -184
  145. package/packages/client/dist/policy/index.js +1 -7
  146. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  147. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  148. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  149. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  150. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  151. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  152. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  153. package/packages/client/dist/private-execution/delivery.js +13 -410
  154. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  155. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  156. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  157. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  158. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  159. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  160. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  161. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  162. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  163. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  164. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  165. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  166. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  167. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  168. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  169. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  170. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  171. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  172. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  173. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  174. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  175. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  176. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  177. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  178. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  179. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  180. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  181. package/packages/client/dist/private-execution/session-lease.js +1 -63
  182. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  183. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  184. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  185. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  186. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  187. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  188. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  189. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  190. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  191. package/packages/client/dist/resilience/index.js +1 -8
  192. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  193. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  194. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  195. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  196. package/packages/client/dist/runner/binary.js +1 -404
  197. package/packages/client/dist/runner/cli.js +17 -1571
  198. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +61 -0
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -0
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.d.ts +65 -0
  202. package/packages/client/dist/runner/headless/background-root.js +1 -0
  203. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  204. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  205. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  206. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  207. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  208. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  209. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  210. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +27 -2
  211. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  212. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  213. package/packages/client/dist/runner/headless/managed-environment-cleanup.d.ts +95 -0
  214. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -0
  215. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  216. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  217. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  218. package/packages/client/dist/runner/headless/resolver.js +1 -231
  219. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  220. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  221. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  222. package/packages/client/dist/runner/headless/types.js +2 -574
  223. package/packages/client/dist/runner/local-console.js +13 -396
  224. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  225. package/packages/client/dist/runner/project-identity.js +1 -106
  226. package/packages/client/dist/runner/scheduler.js +7 -995
  227. package/packages/client/dist/runner-cli.js +2 -18
  228. package/packages/client/dist/state/invocation-shape.js +1 -13
  229. package/packages/client/dist/state/project-state-snapshot.d.ts +7 -0
  230. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  231. package/packages/client/dist/state/state-json-repair.js +3 -785
  232. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  233. package/packages/client/dist/telemetry/index.js +1 -5
  234. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  235. package/packages/client/dist/tier/index.js +1 -5
  236. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  237. package/packages/client/dist/types/index.js +1 -38
  238. package/packages/client/dist/version.js +1 -27
  239. package/packages/client/dist/yolo/change-evidence-collector.d.ts +21 -1
  240. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  241. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  242. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  243. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  244. package/packages/client/dist/yoloop/index.js +1 -8
  245. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  246. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  247. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  248. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  249. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  250. package/packages/shared/dist/invocation/explicit-intent-recovery.d.ts +83 -0
  251. package/packages/shared/dist/invocation/explicit-intent-recovery.js +187 -0
  252. package/packages/shared/dist/invocation/index.d.ts +7 -0
  253. package/packages/shared/dist/invocation/index.js +22 -0
  254. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  255. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  256. package/targets-stubs/antigravity/gemini.md +1 -1
  257. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  258. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  259. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  260. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  261. package/targets-stubs/claude-code/neocortex.md +2 -2
  262. package/targets-stubs/codex/AGENTS.md +24 -21
  263. package/targets-stubs/codex/README.md +6 -1
  264. package/targets-stubs/codex/neocortex.toml +7 -2
  265. package/targets-stubs/cursor/agent.md +2 -2
  266. package/targets-stubs/gemini-cli/agent.md +2 -2
  267. package/targets-stubs/opencode/neocortex-root.md +16 -1
  268. package/targets-stubs/opencode/neocortex.md +6 -0
  269. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,348 +1,4 @@
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
- }
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};