@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,9 +1,259 @@
1
- import{execFileSync as O}from"node:child_process";import{createHash as K,randomBytes as R}from"node:crypto";import{closeSync as G,constants as L,existsSync as Z,fstatSync as q,openSync as T,readFileSync as V,realpathSync as B}from"node:fs";import{join as k,resolve as Y}from"node:path";import{parseDocument as M}from"yaml";import{resolveBranchUnit as U}from"../../../shared/dist/yoloop/branch-unit.js";import{acquireGitLifecyclePhysicalIntegrationLock as Q,assertGitLifecyclePrivateFile as j,ensureGitLifecyclePrivateChildDirectory as X,gitLifecycleRuntimeDirectory as tt,releaseGitLifecyclePhysicalIntegrationLock as et}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as v}from"./git-lifecycle-step-ids.js";import{anchoredAtomicWriteFile as rt,anchoredCompareAndSwapFile as D}from"./secure-filesystem-boundary.js";import{readCompletedLegacyStoryBranchPlan as st}from"./legacy-story-branch-setup.js";function p(t){return{ok:!1,reasonCode:t}}function g(t){return K("sha256").update(t).digest("hex")}function S(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function l(t,c){return O("git",[...c],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],maxBuffer:4*1024*1024}).trim()}function C(t,c){return O("git",[...c],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","pipe"],maxBuffer:4*1024*1024})}function $(t){const c=T(t,L.O_RDONLY|(L.O_NOFOLLOW??0));try{const e=q(c);if(!e.isFile()||e.size>2*1024*1024)throw new Error("legacy-branch-checkpoint-file-unsafe");return V(c,"utf8")}finally{G(c)}}function ct(t){const e=l(t,["remote","get-url","origin"]).match(/^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/);if(!e||e[1].includes("..")||e[2].includes(".."))throw new Error("legacy-branch-issue-repository-invalid");return`${e[1]}/${e[2]}`}async function nt(t,c){const e=O("gh",["issue","view",String(c),"--repo",t,"--json","number,title,state,url"],{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","pipe"],maxBuffer:16384});return JSON.parse(e)}function ot(t,c,e,s,r){if(t.number!==s||t.title!==`[YOLO] Story ${e} - Workflow Run`||t.state!=="OPEN"&&!(r&&t.state==="CLOSED")||t.url.toLowerCase()!==`https://github.com/${c}/issues/${s}`.toLowerCase())throw new Error("legacy-branch-issue-evidence-invalid")}function at(t,c){const e=t.worktreePath,s=C(e,["show","HEAD:.neocortex/state.json"]);if(g(s)!==t.stateSha256)throw new Error("legacy-branch-checkpoint-base-state-mismatch");const r=S(JSON.parse(s)),h=S(r?.stories),o=S(r?.epics),a=S(h?.[t.storyId]),f=S(o?.[t.epicId]),i=Object.entries(h??{}).flatMap(([d,z])=>{const P=S(z);return P?.epic_id===t.epicId?[{...P,id:d}]:[]});if(!f||f.id!==t.epicId||f.branch_mode==="epic"||U(f,i).mode!=="story"||!a||a.id!==t.storyId||a.epic_id!==t.epicId||a.status!=="backlog"&&a.status!=="ready_to_start"||!Array.isArray(a.steps_completed)||a.steps_completed.length!==0||a.branch_name||a.issue_number||a.last_step)throw new Error("legacy-branch-checkpoint-state-conflict");a.status="branch-ready",a.steps_completed=[v],a.last_step=v,a.branch_name=t.branch,a.issue_number=c;const u=`${JSON.stringify(r,null,2)}
2
- `,b=`docs/stories/${t.storyId}.story.md`,y=C(e,["show",`HEAD:${b}`]),I=y.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);if(!I)throw new Error("legacy-branch-checkpoint-frontmatter-invalid");const n=M(I[1],{strict:!0,uniqueKeys:!0});if(n.errors.length>0||n.get("id")!==t.storyId||(n.get("epic_id")??n.get("epic"))!==t.epicId)throw new Error("legacy-branch-checkpoint-frontmatter-invalid");const w=S(n.toJS()),m=["stepsCompleted","steps_completed"].filter(d=>n.has(d)),A=["branchName","branch_name"].filter(d=>n.has(d)),_=["lastStep","last_step"].filter(d=>n.has(d)),N=["issueNumber","issue_number"].filter(d=>n.has(d));if(m.length>1||A.length>1||_.length>1||N.length>1||n.has("status")&&!["backlog","ready","ready_to_start"].includes(String(n.get("status")))||n.has("currentStatus")&&!["backlog","ready","ready_to_start"].includes(String(w?.currentStatus))||m.length===1&&(!Array.isArray(w?.[m[0]])||(w?.[m[0]]).length!==0)||A.length===1&&w?.[A[0]]!=null||_.length===1&&w?.[_[0]]!=null||N.length===1&&w?.[N[0]]!=null)throw new Error("legacy-branch-checkpoint-frontmatter-conflict");n.set("status","branch-ready"),n.has("currentStatus")&&n.set("currentStatus","branch-ready"),n.set(m[0]??"stepsCompleted",[v]),n.set(_[0]??"lastStep",v),n.set(A[0]??"branchName",t.branch),n.set(N[0]??"issueNumber",c);const F=`---
3
- ${n.toString({lineWidth:0})}---
4
- ${y.slice(I[0].length)}`;return{storyPath:b,stateBefore:s,stateAfter:u,storyBefore:y,storyAfter:F}}function E(t,c,e){const s=B(t.worktreePath);if(t.epicId!==t.storyId.split(".")[0]||t.branch!==`story/${t.epicId}/${t.storyId}`||!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(t.epicId)||!l(c,["check-ref-format","--branch",t.branch])||!l(c,["check-ref-format","--branch",t.baseBranch]))throw new Error("legacy-branch-checkpoint-plan-invalid");const r=i=>B(Y(i,l(i,["rev-parse","--git-common-dir"]))),h=l(c,["worktree","list","--porcelain"]).split(/\n\n+/).filter(i=>i.split(`
5
- `).includes(`branch refs/heads/${t.branch}`));if(s!==t.worktreePath||h.length!==1||!h[0].split(`
6
- `).includes(`worktree ${s}`)||h[0].split(`
7
- `).some(i=>i.startsWith("locked")||i.startsWith("prunable"))||r(s)!==r(c)||B(l(s,["rev-parse","--show-toplevel"]))!==s||l(s,["symbolic-ref","--quiet","--short","HEAD"])!==t.branch||l(s,["rev-parse","HEAD"])!==t.baseHeadSha||l(s,["rev-parse",`refs/heads/${t.branch}`])!==t.baseHeadSha||l(s,["rev-parse",`refs/remotes/origin/${t.baseBranch}`])!==t.baseHeadSha)throw new Error("legacy-branch-checkpoint-physical-mismatch");const o=$(k(s,".neocortex/state.json")),a=$(k(s,e.storyPath));if(![e.stateBefore,e.stateAfter].includes(o)||![e.storyBefore,e.storyAfter].includes(a))throw new Error("legacy-branch-checkpoint-preimage-conflict");if(C(s,["status","--porcelain=v1","-uall"]).split(`
8
- `).filter(Boolean).some(i=>{if(!i.startsWith(" M "))return!0;const u=i.slice(3);return u!==".neocortex/state.json"&&u!==e.storyPath}))throw new Error("legacy-branch-checkpoint-worktree-dirty");return{stateCurrent:o,storyCurrent:a}}async function it(t){return X(await tt(t),"legacy-story-branch-intents")}function x(t){return`${g(t)}.c01.json`}function J(t){return`${g(t)}.c01.accepted.json`}async function H(t,c){const e=k(t,c);if(!Z(e))return null;await j(e,t);const s=$(e);if(s.length>4096)throw new Error("legacy-branch-checkpoint-journal-invalid");return JSON.parse(s)}async function W(t,c,e){await rt(t,c,`${JSON.stringify(e)}
9
- `),await j(k(t,c),t)}async function wt(t){if(!Number.isSafeInteger(t.issueNumber)||t.issueNumber<=0)return p("legacy-branch-issue-number-invalid");const c=`legacy-c01-${R(16).toString("hex")}`,e=await Q(t.projectRoot,{kind:"direct",storyId:t.storyId,sessionId:c,idempotencyKey:c,expiresAt:new Date(Date.now()+5*6e4).toISOString(),persistent:!1});if(!e.ok)return p(e.reasonCode);try{const s=await st(t);if(!s.ok)return s;const r=s.value,h=B(t.projectRoot),o=at(r,t.issueNumber),a=E(r,h,o),f=ct(h),i=await it(h),u={schemaVersion:1,kind:"legacy-story-c01-acceptance-intent",storyId:r.storyId,planDigest:g(JSON.stringify(r)),repository:f,issueNumber:t.issueNumber,stateBefore:g(o.stateBefore),stateAfter:g(o.stateAfter),storyBefore:g(o.storyBefore),storyAfter:g(o.storyAfter)},b=await H(i,x(r.storyId));if(b&&JSON.stringify(b)!==JSON.stringify(u))return p("legacy-branch-checkpoint-journal-conflict");if(!b&&(a.stateCurrent!==o.stateBefore||a.storyCurrent!==o.storyBefore))return p("legacy-branch-checkpoint-unjournaled-drift");const y=await H(i,J(r.storyId));if(y&&JSON.stringify(y)!==JSON.stringify(u))return p("legacy-branch-checkpoint-accepted-conflict");const I=await(t.verifyIssue??nt)(f,t.issueNumber);ot(I,f,r.storyId,t.issueNumber,!!y),b||await W(i,x(r.storyId),u);const n=E(r,h,o);if(y&&(n.stateCurrent!==o.stateAfter||n.storyCurrent!==o.storyAfter))return p("legacy-branch-checkpoint-accepted-physical-mismatch");n.stateCurrent===o.stateBefore&&(await D(k(r.worktreePath,".neocortex"),"state.json",o.stateAfter,u.stateBefore),await t.afterStatePersist?.()),E(r,h,o).storyCurrent===o.storyBefore&&(await D(k(r.worktreePath,"docs/stories"),`${r.storyId}.story.md`,o.storyAfter,u.storyBefore),await t.afterStoryPersist?.());const m=E(r,h,o);return m.stateCurrent!==o.stateAfter||m.storyCurrent!==o.storyAfter?p("legacy-branch-checkpoint-post-write-mismatch"):(y||await W(i,J(r.storyId),u),{ok:!0,value:Object.freeze({schemaVersion:1,kind:"legacy-story-c01-checkpoint",storyId:r.storyId,epicId:r.epicId,branch:r.branch,issueNumber:t.issueNumber,repository:f,stateSha256:u.stateAfter,storySha256:u.storyAfter,reused:!!y,checkpointAccepted:!0,localOnly:!0})})}catch(s){const r=s instanceof Error?s.message:"";return p(r.startsWith("legacy-branch-")?r:r.includes("secure-filesystem-cas-conflict")?"legacy-branch-checkpoint-write-raced":"legacy-branch-checkpoint-failed")}finally{await et(e.path,e.owner).catch(()=>{})}}export{wt as acceptLegacyStoryBranchC01};
1
+ /** Root-owned, replayable C01 checkpoint for explicitly recorded story branches. */
2
+ import { execFileSync } from 'node:child_process';
3
+ import { createHash, randomBytes } from 'node:crypto';
4
+ import { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, realpathSync } from 'node:fs';
5
+ import { join, resolve } from 'node:path';
6
+ import { parseDocument } from 'yaml';
7
+ import { resolveBranchUnit } from '../../../shared/dist/yoloop/branch-unit.js';
8
+ import { acquireGitLifecyclePhysicalIntegrationLock, assertGitLifecyclePrivateFile, ensureGitLifecyclePrivateChildDirectory, gitLifecycleRuntimeDirectory, releaseGitLifecyclePhysicalIntegrationLock, } from './git-lifecycle-store.js';
9
+ import { GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID } from './git-lifecycle-step-ids.js';
10
+ import { anchoredAtomicWriteFile, anchoredCompareAndSwapFile } from './secure-filesystem-boundary.js';
11
+ import { readCompletedLegacyStoryBranchPlan } from './legacy-story-branch-setup.js';
12
+ function fail(reasonCode) { return { ok: false, reasonCode }; }
13
+ function digest(value) { return createHash('sha256').update(value).digest('hex'); }
14
+ function row(value) {
15
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
16
+ }
17
+ function git(cwd, args) {
18
+ return execFileSync('git', [...args], { cwd, encoding: 'utf8',
19
+ stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 * 1024 * 1024 }).trim();
20
+ }
21
+ function gitRaw(cwd, args) {
22
+ return execFileSync('git', [...args], { cwd, encoding: 'utf8',
23
+ stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 4 * 1024 * 1024 });
24
+ }
25
+ function safeRead(path) {
26
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
27
+ try {
28
+ const stat = fstatSync(fd);
29
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024)
30
+ throw new Error('legacy-branch-checkpoint-file-unsafe');
31
+ return readFileSync(fd, 'utf8');
32
+ }
33
+ finally {
34
+ closeSync(fd);
35
+ }
36
+ }
37
+ function repository(cwd) {
38
+ const remote = git(cwd, ['remote', 'get-url', 'origin']);
39
+ const match = remote.match(/^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/);
40
+ if (!match || match[1].includes('..') || match[2].includes('..')) {
41
+ throw new Error('legacy-branch-issue-repository-invalid');
42
+ }
43
+ return `${match[1]}/${match[2]}`;
44
+ }
45
+ async function ghIssueVerifier(repo, number) {
46
+ const raw = execFileSync('gh', ['issue', 'view', String(number), '--repo', repo,
47
+ '--json', 'number,title,state,url'], { encoding: 'utf8', timeout: 15_000,
48
+ stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 });
49
+ return JSON.parse(raw);
50
+ }
51
+ function validateIssue(issue, repo, storyId, number, replay) {
52
+ if (issue.number !== number || issue.title !== `[YOLO] Story ${storyId} - Workflow Run`
53
+ || (issue.state !== 'OPEN' && !(replay && issue.state === 'CLOSED'))
54
+ || issue.url.toLowerCase() !== `https://github.com/${repo}/issues/${number}`.toLowerCase()) {
55
+ throw new Error('legacy-branch-issue-evidence-invalid');
56
+ }
57
+ }
58
+ function project(plan, number) {
59
+ const cwd = plan.worktreePath;
60
+ const stateBefore = gitRaw(cwd, ['show', 'HEAD:.neocortex/state.json']);
61
+ if (digest(stateBefore) !== plan.stateSha256)
62
+ throw new Error('legacy-branch-checkpoint-base-state-mismatch');
63
+ const state = row(JSON.parse(stateBefore));
64
+ const stories = row(state?.stories);
65
+ const epics = row(state?.epics);
66
+ const story = row(stories?.[plan.storyId]);
67
+ const epic = row(epics?.[plan.epicId]);
68
+ const epicStories = Object.entries(stories ?? {}).flatMap(([id, value]) => {
69
+ const item = row(value);
70
+ return item?.epic_id === plan.epicId ? [{ ...item, id }] : [];
71
+ });
72
+ if (!epic || epic.id !== plan.epicId || epic.branch_mode === 'epic'
73
+ || resolveBranchUnit(epic, epicStories).mode !== 'story'
74
+ || !story || story.id !== plan.storyId || story.epic_id !== plan.epicId
75
+ || (story.status !== 'backlog' && story.status !== 'ready_to_start')
76
+ || !Array.isArray(story.steps_completed) || story.steps_completed.length !== 0
77
+ || story.branch_name || story.issue_number || story.last_step) {
78
+ throw new Error('legacy-branch-checkpoint-state-conflict');
79
+ }
80
+ story.status = 'branch-ready';
81
+ story.steps_completed = [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID];
82
+ story.last_step = GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID;
83
+ story.branch_name = plan.branch;
84
+ story.issue_number = number;
85
+ const stateAfter = `${JSON.stringify(state, null, 2)}\n`;
86
+ const storyPath = `docs/stories/${plan.storyId}.story.md`;
87
+ const storyBefore = gitRaw(cwd, ['show', `HEAD:${storyPath}`]);
88
+ const frontmatter = storyBefore.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
89
+ if (!frontmatter)
90
+ throw new Error('legacy-branch-checkpoint-frontmatter-invalid');
91
+ const document = parseDocument(frontmatter[1], { strict: true, uniqueKeys: true });
92
+ if (document.errors.length > 0 || document.get('id') !== plan.storyId
93
+ || (document.get('epic_id') ?? document.get('epic')) !== plan.epicId) {
94
+ throw new Error('legacy-branch-checkpoint-frontmatter-invalid');
95
+ }
96
+ const frontmatterData = row(document.toJS());
97
+ const stepKeys = ['stepsCompleted', 'steps_completed'].filter((key) => document.has(key));
98
+ const branchKeys = ['branchName', 'branch_name'].filter((key) => document.has(key));
99
+ const lastKeys = ['lastStep', 'last_step'].filter((key) => document.has(key));
100
+ const issueKeys = ['issueNumber', 'issue_number'].filter((key) => document.has(key));
101
+ if (stepKeys.length > 1 || branchKeys.length > 1 || lastKeys.length > 1 || issueKeys.length > 1
102
+ || (document.has('status') && !['backlog', 'ready', 'ready_to_start'].includes(String(document.get('status'))))
103
+ || (document.has('currentStatus')
104
+ && !['backlog', 'ready', 'ready_to_start'].includes(String(frontmatterData?.currentStatus)))
105
+ || (stepKeys.length === 1 && (!Array.isArray(frontmatterData?.[stepKeys[0]])
106
+ || (frontmatterData?.[stepKeys[0]]).length !== 0))
107
+ || (branchKeys.length === 1 && frontmatterData?.[branchKeys[0]] != null)
108
+ || (lastKeys.length === 1 && frontmatterData?.[lastKeys[0]] != null)
109
+ || (issueKeys.length === 1 && frontmatterData?.[issueKeys[0]] != null)) {
110
+ throw new Error('legacy-branch-checkpoint-frontmatter-conflict');
111
+ }
112
+ document.set('status', 'branch-ready');
113
+ if (document.has('currentStatus'))
114
+ document.set('currentStatus', 'branch-ready');
115
+ document.set(stepKeys[0] ?? 'stepsCompleted', [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID]);
116
+ document.set(lastKeys[0] ?? 'lastStep', GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID);
117
+ document.set(branchKeys[0] ?? 'branchName', plan.branch);
118
+ document.set(issueKeys[0] ?? 'issueNumber', number);
119
+ const storyAfter = `---\n${document.toString({ lineWidth: 0 })}---\n${storyBefore.slice(frontmatter[0].length)}`;
120
+ return { storyPath, stateBefore, stateAfter, storyBefore, storyAfter };
121
+ }
122
+ function physical(plan, sourceRoot, projection) {
123
+ const cwd = realpathSync(plan.worktreePath);
124
+ if (plan.epicId !== plan.storyId.split('.')[0]
125
+ || plan.branch !== `story/${plan.epicId}/${plan.storyId}`
126
+ || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(plan.epicId)
127
+ || !git(sourceRoot, ['check-ref-format', '--branch', plan.branch])
128
+ || !git(sourceRoot, ['check-ref-format', '--branch', plan.baseBranch])) {
129
+ throw new Error('legacy-branch-checkpoint-plan-invalid');
130
+ }
131
+ const common = (path) => realpathSync(resolve(path, git(path, ['rev-parse', '--git-common-dir'])));
132
+ const worktrees = git(sourceRoot, ['worktree', 'list', '--porcelain']).split(/\n\n+/)
133
+ .filter((block) => block.split('\n').includes(`branch refs/heads/${plan.branch}`));
134
+ if (cwd !== plan.worktreePath || worktrees.length !== 1
135
+ || !worktrees[0].split('\n').includes(`worktree ${cwd}`)
136
+ || worktrees[0].split('\n').some((line) => line.startsWith('locked') || line.startsWith('prunable'))
137
+ || common(cwd) !== common(sourceRoot)
138
+ || realpathSync(git(cwd, ['rev-parse', '--show-toplevel'])) !== cwd
139
+ || git(cwd, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== plan.branch
140
+ || git(cwd, ['rev-parse', 'HEAD']) !== plan.baseHeadSha
141
+ || git(cwd, ['rev-parse', `refs/heads/${plan.branch}`]) !== plan.baseHeadSha
142
+ || git(cwd, ['rev-parse', `refs/remotes/origin/${plan.baseBranch}`]) !== plan.baseHeadSha) {
143
+ throw new Error('legacy-branch-checkpoint-physical-mismatch');
144
+ }
145
+ const stateCurrent = safeRead(join(cwd, '.neocortex/state.json'));
146
+ const storyCurrent = safeRead(join(cwd, projection.storyPath));
147
+ if (![projection.stateBefore, projection.stateAfter].includes(stateCurrent)
148
+ || ![projection.storyBefore, projection.storyAfter].includes(storyCurrent)) {
149
+ throw new Error('legacy-branch-checkpoint-preimage-conflict');
150
+ }
151
+ const statuses = gitRaw(cwd, ['status', '--porcelain=v1', '-uall']);
152
+ if (statuses.split('\n').filter(Boolean).some((line) => {
153
+ if (!line.startsWith(' M '))
154
+ return true;
155
+ const path = line.slice(3);
156
+ return path !== '.neocortex/state.json' && path !== projection.storyPath;
157
+ }))
158
+ throw new Error('legacy-branch-checkpoint-worktree-dirty');
159
+ return { stateCurrent, storyCurrent };
160
+ }
161
+ async function privateDirectory(projectRoot) {
162
+ return ensureGitLifecyclePrivateChildDirectory(await gitLifecycleRuntimeDirectory(projectRoot), 'legacy-story-branch-intents');
163
+ }
164
+ function journalName(storyId) { return `${digest(storyId)}.c01.json`; }
165
+ function acceptedName(storyId) { return `${digest(storyId)}.c01.accepted.json`; }
166
+ async function readPrivateJson(directory, name) {
167
+ const path = join(directory, name);
168
+ if (!existsSync(path))
169
+ return null;
170
+ await assertGitLifecyclePrivateFile(path, directory);
171
+ const raw = safeRead(path);
172
+ if (raw.length > 4096)
173
+ throw new Error('legacy-branch-checkpoint-journal-invalid');
174
+ return JSON.parse(raw);
175
+ }
176
+ async function writePrivateJson(directory, name, value) {
177
+ await anchoredAtomicWriteFile(directory, name, `${JSON.stringify(value)}\n`);
178
+ await assertGitLifecyclePrivateFile(join(directory, name), directory);
179
+ }
180
+ export async function acceptLegacyStoryBranchC01(options) {
181
+ if (!Number.isSafeInteger(options.issueNumber) || options.issueNumber <= 0) {
182
+ return fail('legacy-branch-issue-number-invalid');
183
+ }
184
+ const sessionId = `legacy-c01-${randomBytes(16).toString('hex')}`;
185
+ const lock = await acquireGitLifecyclePhysicalIntegrationLock(options.projectRoot, {
186
+ kind: 'direct', storyId: options.storyId, sessionId, idempotencyKey: sessionId,
187
+ expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(), persistent: false,
188
+ });
189
+ if (!lock.ok)
190
+ return fail(lock.reasonCode);
191
+ try {
192
+ const completed = await readCompletedLegacyStoryBranchPlan(options);
193
+ if (!completed.ok)
194
+ return completed;
195
+ const plan = completed.value;
196
+ const sourceRoot = realpathSync(options.projectRoot);
197
+ const projection = project(plan, options.issueNumber);
198
+ const before = physical(plan, sourceRoot, projection);
199
+ const repo = repository(sourceRoot);
200
+ const directory = await privateDirectory(sourceRoot);
201
+ const journal = {
202
+ schemaVersion: 1, kind: 'legacy-story-c01-acceptance-intent', storyId: plan.storyId,
203
+ planDigest: digest(JSON.stringify(plan)), repository: repo, issueNumber: options.issueNumber,
204
+ stateBefore: digest(projection.stateBefore), stateAfter: digest(projection.stateAfter),
205
+ storyBefore: digest(projection.storyBefore), storyAfter: digest(projection.storyAfter),
206
+ };
207
+ const existing = await readPrivateJson(directory, journalName(plan.storyId));
208
+ if (existing && JSON.stringify(existing) !== JSON.stringify(journal)) {
209
+ return fail('legacy-branch-checkpoint-journal-conflict');
210
+ }
211
+ if (!existing && (before.stateCurrent !== projection.stateBefore
212
+ || before.storyCurrent !== projection.storyBefore)) {
213
+ return fail('legacy-branch-checkpoint-unjournaled-drift');
214
+ }
215
+ const accepted = await readPrivateJson(directory, acceptedName(plan.storyId));
216
+ if (accepted && JSON.stringify(accepted) !== JSON.stringify(journal)) {
217
+ return fail('legacy-branch-checkpoint-accepted-conflict');
218
+ }
219
+ const issue = await (options.verifyIssue ?? ghIssueVerifier)(repo, options.issueNumber);
220
+ validateIssue(issue, repo, plan.storyId, options.issueNumber, Boolean(accepted));
221
+ if (!existing)
222
+ await writePrivateJson(directory, journalName(plan.storyId), journal);
223
+ const beforeWrite = physical(plan, sourceRoot, projection);
224
+ if (accepted && (beforeWrite.stateCurrent !== projection.stateAfter
225
+ || beforeWrite.storyCurrent !== projection.storyAfter)) {
226
+ return fail('legacy-branch-checkpoint-accepted-physical-mismatch');
227
+ }
228
+ if (beforeWrite.stateCurrent === projection.stateBefore) {
229
+ await anchoredCompareAndSwapFile(join(plan.worktreePath, '.neocortex'), 'state.json', projection.stateAfter, journal.stateBefore);
230
+ await options.afterStatePersist?.();
231
+ }
232
+ const middle = physical(plan, sourceRoot, projection);
233
+ if (middle.storyCurrent === projection.storyBefore) {
234
+ await anchoredCompareAndSwapFile(join(plan.worktreePath, 'docs/stories'), `${plan.storyId}.story.md`, projection.storyAfter, journal.storyBefore);
235
+ await options.afterStoryPersist?.();
236
+ }
237
+ const after = physical(plan, sourceRoot, projection);
238
+ if (after.stateCurrent !== projection.stateAfter || after.storyCurrent !== projection.storyAfter) {
239
+ return fail('legacy-branch-checkpoint-post-write-mismatch');
240
+ }
241
+ if (!accepted)
242
+ await writePrivateJson(directory, acceptedName(plan.storyId), journal);
243
+ return { ok: true, value: Object.freeze({
244
+ schemaVersion: 1, kind: 'legacy-story-c01-checkpoint', storyId: plan.storyId,
245
+ epicId: plan.epicId, branch: plan.branch, issueNumber: options.issueNumber,
246
+ repository: repo, stateSha256: journal.stateAfter, storySha256: journal.storyAfter,
247
+ reused: Boolean(accepted), checkpointAccepted: true, localOnly: true,
248
+ }) };
249
+ }
250
+ catch (error) {
251
+ const message = error instanceof Error ? error.message : '';
252
+ return fail(message.startsWith('legacy-branch-') ? message
253
+ : message.includes('secure-filesystem-cas-conflict') ? 'legacy-branch-checkpoint-write-raced'
254
+ : 'legacy-branch-checkpoint-failed');
255
+ }
256
+ finally {
257
+ await releaseGitLifecyclePhysicalIntegrationLock(lock.path, lock.owner).catch(() => undefined);
258
+ }
259
+ }