@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,13 +1,399 @@
1
- import{createHash as Q}from"node:crypto";import{closeSync as _,constants as E,existsSync as X,fsyncSync as W,lstatSync as V,openSync as P,readFileSync as q,realpathSync as K,writeFileSync as tt}from"node:fs";import{join as $,resolve as H}from"node:path";import{mutationQaGit as y}from"./mutation-qa-git.js";import{privateRefactorDirectory as x,readPrivateRefactorAdmission as F,refactorSidecarDigest as j,verifyRootRefactor as et}from"./refactor-root.js";import{readRootRefactorSemanticReview as rt}from"./refactor-review.js";const S=/^[a-f0-9]{64}$/,T=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;function w(o){return Q("sha256").update(o).digest("hex")}function g(o,e){return y(o,e).toString("utf8").trim()}function b(o,e){return y(o,e).toString("utf8").split("\0").filter(Boolean)}function I(o){return[...o].sort((e,r)=>Buffer.from(e).compare(Buffer.from(r)))}function N(o,e){return o!==null&&typeof o=="object"&&!Array.isArray(o)&&Object.keys(o).sort().join("\0")===[...e].sort().join("\0")}function R(o,e){const r=$(o,e),t=V(r);if(!t.isFile()||t.isSymbolicLink()||K(r)!==r||t.size<1||t.size>8*1024*1024)throw new Error("refactor-root-commit-physical-drift");const n=q(r);if(n.length!==t.size)throw new Error("refactor-root-commit-physical-drift");return Object.freeze({sha256:w(n),mode:t.mode&511})}function L(o,e){if(!S.test(e))throw new Error("refactor-root-commit-plan-invalid");return $(x(o),`commit-plan-${e}.json`)}function C(o,e){if(!S.test(e))throw new Error("refactor-root-commit-plan-invalid");return $(x(o),`commit-checkpoint-${e}.json`)}function v(o,e){const r=V(o);if(!r.isFile()||r.isSymbolicLink()||r.uid!==process.getuid?.()||(r.mode&63)!==0||r.size<100||r.size>e)throw new Error("refactor-root-commit-plan-invalid");const t=q(o);if(t.length!==r.size)throw new Error("refactor-root-commit-plan-invalid");return t}function Y(o,e,r){if(X(e)){if(!v(e,128*1024).equals(r))throw new Error("refactor-root-commit-plan-conflict");return}const t=P(e,E.O_WRONLY|E.O_CREAT|E.O_EXCL|(E.O_NOFOLLOW??0),384);try{tt(t,r),W(t)}finally{_(t)}const n=P(x(o),E.O_RDONLY|(E.O_DIRECTORY??0));try{W(n)}finally{_(n)}}function A(o,e){const r=v(L(o,e),131072);let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new Error("refactor-root-commit-plan-invalid")}if(!N(t,["schemaVersion","kind","storyId","baseHead","branchRef","admissionSha256","baselineSha256","candidateSha256","reviewSha256","reviewRecordSha256","sidecarSha256","files","planSha256"])||t.schemaVersion!==1||t.kind!=="private-root-refactor-commit-plan"||typeof t.storyId!="string"||!/^P[0-9]+(?:\.[0-9]+)+$/.test(t.storyId)||typeof t.baseHead!="string"||!T.test(t.baseHead)||typeof t.branchRef!="string"||![`refs/heads/epic/${t.storyId.split(".")[0]}`,`refs/heads/story/${t.storyId.split(".")[0]}/${t.storyId}`].includes(t.branchRef)||![t.admissionSha256,t.baselineSha256,t.candidateSha256,t.reviewSha256,t.reviewRecordSha256,t.sidecarSha256].every(a=>typeof a=="string"&&S.test(a))||!Array.isArray(t.files)||t.files.length<2||t.files.length>256||!t.files.every(a=>N(a,["path","sha256","mode"])&&typeof a.path=="string"&&/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(a.path)&&typeof a.sha256=="string"&&S.test(a.sha256)&&Number.isSafeInteger(a.mode)&&Number(a.mode)>=0&&Number(a.mode)<=511)||t.files.map(a=>a.path).join("\0")!==I(t.files.map(a=>a.path)).join("\0")||new Set(t.files.map(a=>a.path)).size!==t.files.length||t.planSha256!==e)throw new Error("refactor-root-commit-plan-invalid");const{planSha256:n,...c}=t;if(w(JSON.stringify(c))!==e||!r.equals(Buffer.from(`${JSON.stringify(t)}
2
- `)))throw new Error("refactor-root-commit-plan-invalid");const i=F(o,t.admissionSha256),m=new Set([...i.files.map(a=>a.path),...i.schemaVersion===2?i.newFiles.map(a=>a.path):[]]);if(i.storyId!==t.storyId||i.sourceHead!==t.baseHead||i.sidecarSha256!==t.sidecarSha256||t.files.some(a=>!m.has(a.path)))throw new Error("refactor-root-commit-plan-invalid");return t}function B(o,e){return $(x(o),`review-${e.admissionSha256}-${e.candidateSha256}.json`)}function G(o){return`refactor(${o}): characterized change`}function U(o){return`Neocortex-Refactor-Plan: ${o}`}function k(o){return g(o,["symbolic-ref","-q","HEAD"])}function ot(o){return b(o,["status","--porcelain=v1","-z","--untracked-files=all"]).every(e=>e.length>=4&&e[2]===" "&&e.slice(3).startsWith(".neocortex/"))}function it(o,e,r,t){if(!t)throw new Error("refactor-root-commit-authorization-required");try{const n=H(o),c=rt(n,e,r),i=F(n,e),m=et(n,e),a=k(n),s=i.storyId.split(".")[0];if(![`refs/heads/epic/${s}`,`refs/heads/story/${s}/${i.storyId}`].includes(a))throw new Error("refactor-root-commit-branch-invalid");const u=b(n,["diff","--name-only","-z","--no-ext-diff","--no-textconv"]),d=b(n,["ls-files","--others","--exclude-standard","-z"]),l=I([...u,...d].filter(f=>!f.startsWith(".neocortex/"))),h=new Set([...i.files.map(f=>f.path),...i.schemaVersion===2?i.newFiles.map(f=>f.path):[]]);if(l.length!==m.changedFileCount||l.some(f=>!h.has(f)))throw new Error("refactor-root-commit-delta-invalid");const p=l.map(f=>Object.freeze({path:f,...R(n,f)})),z=w(v(B(n,{admissionSha256:e,candidateSha256:c.candidateSha256}),128*1024)),D={schemaVersion:1,kind:"private-root-refactor-commit-plan",storyId:i.storyId,baseHead:i.sourceHead,branchRef:a,admissionSha256:e,baselineSha256:r,candidateSha256:c.candidateSha256,reviewSha256:c.reviewSha256,reviewRecordSha256:z,sidecarSha256:i.sidecarSha256,files:p},O=w(JSON.stringify(D)),M={...D,planSha256:O};if(g(n,["rev-parse","--verify","HEAD"])!==i.sourceHead||j(n)!==i.sidecarSha256||p.some(f=>{const J=R(n,f.path);return J.sha256!==f.sha256||J.mode!==f.mode}))throw new Error("refactor-root-commit-physical-drift");return Y(n,L(n,O),Buffer.from(`${JSON.stringify(M)}
3
- `)),A(n,O),Object.freeze({schemaVersion:1,kind:"root-refactor-commit-plan",storyId:i.storyId,baseHead:i.sourceHead,branchRef:a,planSha256:O,fileCount:p.length,commitSubject:G(i.storyId),commitTrailer:U(O),gitCommitAuthorized:!1,checkpointAccepted:!1,publicSafe:!0})}catch(n){throw n instanceof Error&&n.message.startsWith("refactor-root-commit-")?n:new Error("refactor-root-commit-unverified")}}function at(o,e){try{const r=H(o),t=A(r,e);if(k(r)!==t.branchRef||g(r,["rev-parse","--verify","HEAD"])!==t.baseHead||j(r)!==t.sidecarSha256||w(v(B(r,t),128*1024))!==t.reviewRecordSha256)throw new Error("refactor-root-commit-physical-drift");const n=I(b(r,["diff","--cached","--name-only","-z","--no-renames"])),c=t.files.map(a=>a.path),i=b(r,["diff","--name-only","-z","--no-renames"]).filter(a=>!a.startsWith(".neocortex/")),m=b(r,["ls-files","--others","--exclude-standard","-z"]).filter(a=>!a.startsWith(".neocortex/"));if(n.join("\0")!==c.join("\0")||i.length||m.length)throw new Error("refactor-root-commit-staged-invalid");for(const a of t.files){const u=y(r,["ls-files","--stage","-z","--",a.path]).toString("utf8").match(/^(100644|100755) [a-f0-9]{40,64} 0\t([^\0]+)\0$/);if(!u||u[2]!==a.path||u[1]!==(a.mode&73?"100755":"100644")||w(y(r,["show",`:${a.path}`]))!==a.sha256||R(r,a.path).sha256!==a.sha256||R(r,a.path).mode!==a.mode)throw new Error("refactor-root-commit-staged-invalid")}if(k(r)!==t.branchRef||g(r,["rev-parse","--verify","HEAD"])!==t.baseHead||j(r)!==t.sidecarSha256)throw new Error("refactor-root-commit-physical-drift");return Object.freeze({schemaVersion:1,kind:"root-refactor-staged-verification",planSha256:e,baseHead:t.baseHead,fileCount:t.files.length,stagedWriteSetSha256:w(JSON.stringify(t.files)),gitCommitAuthorized:!0,checkpointAccepted:!1,publicSafe:!0})}catch(r){throw r instanceof Error&&r.message.startsWith("refactor-root-commit-")?r:new Error("refactor-root-commit-unverified")}}function Z(o,e){const r=g(o,["rev-parse","--verify","HEAD"]),t=g(o,["show","-s","--format=%P",r]),n=y(o,["cat-file","commit",r]),c=n.indexOf(Buffer.from(`
4
-
5
- `)),i=c<0?Buffer.alloc(0):n.subarray(c+2),m=Buffer.from(`${G(e.storyId)}
6
-
7
- ${U(e.planSha256)}
8
- `);if(!T.test(r)||t!==e.baseHead||!i.equals(m)||k(o)!==e.branchRef||!ot(o)||j(o)!==e.sidecarSha256||w(v(B(o,e),128*1024))!==e.reviewRecordSha256)throw new Error("refactor-root-commit-physical-drift");if(I(b(o,["diff-tree","--no-commit-id","--name-only","--no-renames","-r","-z",r])).join("\0")!==e.files.map(s=>s.path).join("\0"))throw new Error("refactor-root-commit-physical-drift");for(const s of e.files){const d=y(o,["ls-tree","-z",r,"--",s.path]).toString("utf8").match(/^(100644|100755) blob [a-f0-9]{40,64}\t([^\0]+)\0$/);if(!d||d[2]!==s.path||d[1]!==(s.mode&73?"100755":"100644")||w(y(o,["show",`${r}:${s.path}`]))!==s.sha256||R(o,s.path).sha256!==s.sha256||R(o,s.path).mode!==s.mode)throw new Error("refactor-root-commit-physical-drift")}if(g(o,["rev-parse","--verify","HEAD"])!==r||k(o)!==e.branchRef)throw new Error("refactor-root-commit-physical-drift");return r}function nt(o,e,r){if(!r)throw new Error("refactor-root-commit-authorization-required");try{const t=H(o),n=A(t,e),c=Z(t,n),i=Object.freeze({schemaVersion:1,kind:"root-refactor-commit-checkpoint",storyId:n.storyId,baseHead:n.baseHead,commitSha:c,branchRef:n.branchRef,planSha256:e,candidateSha256:n.candidateSha256,reviewSha256:n.reviewSha256,fileCount:n.files.length,checkpointAccepted:!0,graphExecution:"NOT_RUN",publicSafe:!0});if(Y(t,C(t,e),Buffer.from(`${JSON.stringify(i)}
9
- `)),!v(C(t,e),8*1024).equals(Buffer.from(`${JSON.stringify(i)}
10
- `)))throw new Error("refactor-root-commit-checkpoint-invalid");return i}catch(t){throw t instanceof Error&&t.message.startsWith("refactor-root-commit-")?t:new Error("refactor-root-commit-unverified")}}function ct(o,e){try{const r=H(o),t=A(r,e),n=Z(r,t),c=v(C(r,e),8*1024),i=JSON.parse(c.toString("utf8"));if(!N(i,["schemaVersion","kind","storyId","baseHead","commitSha","branchRef","planSha256","candidateSha256","reviewSha256","fileCount","checkpointAccepted","graphExecution","publicSafe"])||i.schemaVersion!==1||i.kind!=="root-refactor-commit-checkpoint"||i.commitSha!==n||i.planSha256!==e||i.storyId!==t.storyId||i.baseHead!==t.baseHead||i.branchRef!==t.branchRef||i.candidateSha256!==t.candidateSha256||i.reviewSha256!==t.reviewSha256||i.fileCount!==t.files.length||i.checkpointAccepted!==!0||i.graphExecution!=="NOT_RUN"||i.publicSafe!==!0||!c.equals(Buffer.from(`${JSON.stringify(i)}
11
- `)))throw new Error("refactor-root-commit-checkpoint-invalid");return i}catch{throw new Error("refactor-root-commit-checkpoint-invalid")}}function ut(o){const e=o[0];let r="",t="",n="",c="",i=!1,m=!1,a=!1,s="plain";const u=new Set;try{if(!["commit-plan","commit-staged","commit-seal","commit-status"].includes(e??""))throw new Error("refactor-root-commit-arguments-invalid");for(let l=1;l<o.length;l++){const h=o[l];if(u.has(h))throw new Error("refactor-root-commit-arguments-invalid");u.add(h);const p=()=>{const z=o[++l];if(!z||z.startsWith("--"))throw new Error("refactor-root-commit-arguments-invalid");return z};if(h==="--project-root")r=p();else if(h==="--admission-sha")t=p();else if(h==="--baseline-sha")n=p();else if(h==="--plan-sha")c=p();else if(h==="--authorize-run")i=!0;else if(h==="--authorize-root-commit-plan")m=!0;else if(h==="--authorize-root-seal")a=!0;else if(h==="--format")s=p();else throw new Error("refactor-root-commit-arguments-invalid")}if(!r||!["plain","json"].includes(s)||e==="commit-plan"&&(!S.test(t)||!S.test(n)||c||!i||!m||a)||e!=="commit-plan"&&(!S.test(c)||t||n||i||m||a!==(e==="commit-seal")))throw new Error("refactor-root-commit-arguments-invalid");const d=e==="commit-plan"?it(r,t,n,m):e==="commit-staged"?at(r,c):e==="commit-seal"?nt(r,c,a):ct(r,c);return process.stdout.write(`${JSON.stringify({ok:!0,result:d})}
12
- `),0}catch(d){const l=d instanceof Error&&/^refactor-root-[a-z-]+$/.test(d.message)?d.message:"refactor-root-commit-unverified";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:l})}
13
- `),1}}export{it as prepareRootRefactorCommit,ct as readRootRefactorCommitCheckpoint,ut as refactorCommitCliHandler,nt as sealRootRefactorCommit,at as verifyRootRefactorStaged};
1
+ /** Root-owned, two-phase Git checkpoint for an accepted characterized refactor. */
2
+ import { createHash } from 'node:crypto';
3
+ import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
4
+ import { join, resolve } from 'node:path';
5
+ import { mutationQaGit } from './mutation-qa-git.js';
6
+ import { privateRefactorDirectory, readPrivateRefactorAdmission, refactorSidecarDigest, verifyRootRefactor } from './refactor-root.js';
7
+ import { readRootRefactorSemanticReview } from './refactor-review.js';
8
+ const SHA256 = /^[a-f0-9]{64}$/;
9
+ const GIT_SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
10
+ function sha(value) {
11
+ return createHash('sha256').update(value).digest('hex');
12
+ }
13
+ function git(root, args) {
14
+ return mutationQaGit(root, args).toString('utf8').trim();
15
+ }
16
+ function names(root, args) {
17
+ return mutationQaGit(root, args).toString('utf8').split('\0').filter(Boolean);
18
+ }
19
+ function ordered(paths) {
20
+ return [...paths].sort((a, b) => Buffer.from(a).compare(Buffer.from(b)));
21
+ }
22
+ function exact(value, keys) {
23
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
24
+ && Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
25
+ }
26
+ function physical(root, path) {
27
+ const target = join(root, path);
28
+ const stat = lstatSync(target);
29
+ if (!stat.isFile() || stat.isSymbolicLink() || realpathSync(target) !== target
30
+ || stat.size < 1 || stat.size > 8 * 1024 * 1024) {
31
+ throw new Error('refactor-root-commit-physical-drift');
32
+ }
33
+ const bytes = readFileSync(target);
34
+ if (bytes.length !== stat.size)
35
+ throw new Error('refactor-root-commit-physical-drift');
36
+ return Object.freeze({ sha256: sha(bytes), mode: stat.mode & 0o777 });
37
+ }
38
+ function planPath(root, planSha256) {
39
+ if (!SHA256.test(planSha256))
40
+ throw new Error('refactor-root-commit-plan-invalid');
41
+ return join(privateRefactorDirectory(root), `commit-plan-${planSha256}.json`);
42
+ }
43
+ function checkpointPath(root, planSha256) {
44
+ if (!SHA256.test(planSha256))
45
+ throw new Error('refactor-root-commit-plan-invalid');
46
+ return join(privateRefactorDirectory(root), `commit-checkpoint-${planSha256}.json`);
47
+ }
48
+ function privateBytes(path, maximum) {
49
+ const stat = lstatSync(path);
50
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.()
51
+ || (stat.mode & 0o077) !== 0 || stat.size < 100 || stat.size > maximum) {
52
+ throw new Error('refactor-root-commit-plan-invalid');
53
+ }
54
+ const bytes = readFileSync(path);
55
+ if (bytes.length !== stat.size)
56
+ throw new Error('refactor-root-commit-plan-invalid');
57
+ return bytes;
58
+ }
59
+ function persist(root, path, bytes) {
60
+ if (existsSync(path)) {
61
+ if (!privateBytes(path, 128 * 1024).equals(bytes)) {
62
+ throw new Error('refactor-root-commit-plan-conflict');
63
+ }
64
+ return;
65
+ }
66
+ const handle = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL
67
+ | (constants.O_NOFOLLOW ?? 0), 0o600);
68
+ try {
69
+ writeFileSync(handle, bytes);
70
+ fsyncSync(handle);
71
+ }
72
+ finally {
73
+ closeSync(handle);
74
+ }
75
+ const directory = openSync(privateRefactorDirectory(root), constants.O_RDONLY
76
+ | (constants.O_DIRECTORY ?? 0));
77
+ try {
78
+ fsyncSync(directory);
79
+ }
80
+ finally {
81
+ closeSync(directory);
82
+ }
83
+ }
84
+ function readPlan(root, planSha256) {
85
+ const raw = privateBytes(planPath(root, planSha256), 128 * 1024);
86
+ let parsed;
87
+ try {
88
+ parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
89
+ }
90
+ catch {
91
+ throw new Error('refactor-root-commit-plan-invalid');
92
+ }
93
+ if (!exact(parsed, ['schemaVersion', 'kind', 'storyId', 'baseHead', 'branchRef',
94
+ 'admissionSha256', 'baselineSha256', 'candidateSha256', 'reviewSha256',
95
+ 'reviewRecordSha256', 'sidecarSha256', 'files', 'planSha256'])
96
+ || parsed.schemaVersion !== 1 || parsed.kind !== 'private-root-refactor-commit-plan'
97
+ || typeof parsed.storyId !== 'string' || !/^P[0-9]+(?:\.[0-9]+)+$/.test(parsed.storyId)
98
+ || typeof parsed.baseHead !== 'string' || !GIT_SHA.test(parsed.baseHead)
99
+ || typeof parsed.branchRef !== 'string'
100
+ || ![`refs/heads/epic/${parsed.storyId.split('.')[0]}`,
101
+ `refs/heads/story/${parsed.storyId.split('.')[0]}/${parsed.storyId}`].includes(parsed.branchRef)
102
+ || ![parsed.admissionSha256, parsed.baselineSha256, parsed.candidateSha256,
103
+ parsed.reviewSha256, parsed.reviewRecordSha256, parsed.sidecarSha256]
104
+ .every((value) => typeof value === 'string' && SHA256.test(value))
105
+ || !Array.isArray(parsed.files) || parsed.files.length < 2 || parsed.files.length > 256
106
+ || !parsed.files.every((file) => exact(file, ['path', 'sha256', 'mode'])
107
+ && typeof file.path === 'string' && /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(file.path)
108
+ && typeof file.sha256 === 'string' && SHA256.test(file.sha256)
109
+ && Number.isSafeInteger(file.mode) && Number(file.mode) >= 0 && Number(file.mode) <= 0o777)
110
+ || parsed.files.map((file) => file.path).join('\0')
111
+ !== ordered(parsed.files.map((file) => file.path)).join('\0')
112
+ || new Set(parsed.files.map((file) => file.path)).size !== parsed.files.length
113
+ || parsed.planSha256 !== planSha256) {
114
+ throw new Error('refactor-root-commit-plan-invalid');
115
+ }
116
+ const { planSha256: _digest, ...body } = parsed;
117
+ if (sha(JSON.stringify(body)) !== planSha256
118
+ || !raw.equals(Buffer.from(`${JSON.stringify(parsed)}\n`))) {
119
+ throw new Error('refactor-root-commit-plan-invalid');
120
+ }
121
+ const admission = readPrivateRefactorAdmission(root, parsed.admissionSha256);
122
+ const admitted = new Set([...admission.files.map((file) => file.path),
123
+ ...(admission.schemaVersion === 2 ? admission.newFiles.map((file) => file.path) : [])]);
124
+ if (admission.storyId !== parsed.storyId || admission.sourceHead !== parsed.baseHead
125
+ || admission.sidecarSha256 !== parsed.sidecarSha256
126
+ || parsed.files.some((file) => !admitted.has(file.path))) {
127
+ throw new Error('refactor-root-commit-plan-invalid');
128
+ }
129
+ return parsed;
130
+ }
131
+ function reviewRecordPath(root, plan) {
132
+ return join(privateRefactorDirectory(root), `review-${plan.admissionSha256}-${plan.candidateSha256}.json`);
133
+ }
134
+ function commitSubject(storyId) {
135
+ return `refactor(${storyId}): characterized change`;
136
+ }
137
+ function commitTrailer(planSha256) {
138
+ return `Neocortex-Refactor-Plan: ${planSha256}`;
139
+ }
140
+ function branch(root) {
141
+ return git(root, ['symbolic-ref', '-q', 'HEAD']);
142
+ }
143
+ function allowedDirty(root) {
144
+ return names(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])
145
+ .every((entry) => entry.length >= 4 && entry[2] === ' ' && entry.slice(3).startsWith('.neocortex/'));
146
+ }
147
+ export function prepareRootRefactorCommit(projectRoot, admissionSha256, baselineSha256, authorizeRootPlan) {
148
+ if (!authorizeRootPlan)
149
+ throw new Error('refactor-root-commit-authorization-required');
150
+ try {
151
+ const root = resolve(projectRoot);
152
+ const accepted = readRootRefactorSemanticReview(root, admissionSha256, baselineSha256);
153
+ const admission = readPrivateRefactorAdmission(root, admissionSha256);
154
+ const containment = verifyRootRefactor(root, admissionSha256);
155
+ const branchRef = branch(root);
156
+ const epicId = admission.storyId.split('.')[0];
157
+ if (![`refs/heads/epic/${epicId}`,
158
+ `refs/heads/story/${epicId}/${admission.storyId}`].includes(branchRef)) {
159
+ throw new Error('refactor-root-commit-branch-invalid');
160
+ }
161
+ const tracked = names(root, ['diff', '--name-only', '-z', '--no-ext-diff', '--no-textconv']);
162
+ const untracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z']);
163
+ const paths = ordered([...tracked, ...untracked].filter((path) => !path.startsWith('.neocortex/')));
164
+ const admitted = new Set([...admission.files.map((file) => file.path),
165
+ ...(admission.schemaVersion === 2 ? admission.newFiles.map((file) => file.path) : [])]);
166
+ if (paths.length !== containment.changedFileCount || paths.some((path) => !admitted.has(path))) {
167
+ throw new Error('refactor-root-commit-delta-invalid');
168
+ }
169
+ const files = paths.map((path) => Object.freeze({ path, ...physical(root, path) }));
170
+ const reviewRecordSha256 = sha(privateBytes(reviewRecordPath(root, {
171
+ admissionSha256, candidateSha256: accepted.candidateSha256,
172
+ }), 128 * 1024));
173
+ const body = { schemaVersion: 1, kind: 'private-root-refactor-commit-plan',
174
+ storyId: admission.storyId, baseHead: admission.sourceHead, branchRef,
175
+ admissionSha256, baselineSha256, candidateSha256: accepted.candidateSha256,
176
+ reviewSha256: accepted.reviewSha256, reviewRecordSha256,
177
+ sidecarSha256: admission.sidecarSha256, files };
178
+ const planSha256 = sha(JSON.stringify(body));
179
+ const record = { ...body, planSha256 };
180
+ if (git(root, ['rev-parse', '--verify', 'HEAD']) !== admission.sourceHead
181
+ || refactorSidecarDigest(root) !== admission.sidecarSha256
182
+ || files.some((file) => {
183
+ const current = physical(root, file.path);
184
+ return current.sha256 !== file.sha256 || current.mode !== file.mode;
185
+ })) {
186
+ throw new Error('refactor-root-commit-physical-drift');
187
+ }
188
+ persist(root, planPath(root, planSha256), Buffer.from(`${JSON.stringify(record)}\n`));
189
+ readPlan(root, planSha256);
190
+ return Object.freeze({ schemaVersion: 1, kind: 'root-refactor-commit-plan',
191
+ storyId: admission.storyId, baseHead: admission.sourceHead, branchRef,
192
+ planSha256, fileCount: files.length, commitSubject: commitSubject(admission.storyId),
193
+ commitTrailer: commitTrailer(planSha256), gitCommitAuthorized: false,
194
+ checkpointAccepted: false, publicSafe: true });
195
+ }
196
+ catch (error) {
197
+ if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
198
+ throw error;
199
+ throw new Error('refactor-root-commit-unverified');
200
+ }
201
+ }
202
+ export function verifyRootRefactorStaged(projectRoot, planSha256) {
203
+ try {
204
+ const root = resolve(projectRoot);
205
+ const plan = readPlan(root, planSha256);
206
+ if (branch(root) !== plan.branchRef || git(root, ['rev-parse', '--verify', 'HEAD']) !== plan.baseHead
207
+ || refactorSidecarDigest(root) !== plan.sidecarSha256
208
+ || sha(privateBytes(reviewRecordPath(root, plan), 128 * 1024)) !== plan.reviewRecordSha256) {
209
+ throw new Error('refactor-root-commit-physical-drift');
210
+ }
211
+ const staged = ordered(names(root, ['diff', '--cached', '--name-only', '-z', '--no-renames']));
212
+ const expected = plan.files.map((file) => file.path);
213
+ const unstaged = names(root, ['diff', '--name-only', '-z', '--no-renames'])
214
+ .filter((path) => !path.startsWith('.neocortex/'));
215
+ const untracked = names(root, ['ls-files', '--others', '--exclude-standard', '-z'])
216
+ .filter((path) => !path.startsWith('.neocortex/'));
217
+ if (staged.join('\0') !== expected.join('\0') || unstaged.length || untracked.length) {
218
+ throw new Error('refactor-root-commit-staged-invalid');
219
+ }
220
+ for (const file of plan.files) {
221
+ const index = mutationQaGit(root, ['ls-files', '--stage', '-z', '--', file.path]).toString('utf8');
222
+ const match = index.match(/^(100644|100755) [a-f0-9]{40,64} 0\t([^\0]+)\0$/);
223
+ if (!match || match[2] !== file.path
224
+ || match[1] !== ((file.mode & 0o111) ? '100755' : '100644')
225
+ || sha(mutationQaGit(root, ['show', `:${file.path}`])) !== file.sha256
226
+ || physical(root, file.path).sha256 !== file.sha256
227
+ || physical(root, file.path).mode !== file.mode) {
228
+ throw new Error('refactor-root-commit-staged-invalid');
229
+ }
230
+ }
231
+ if (branch(root) !== plan.branchRef || git(root, ['rev-parse', '--verify', 'HEAD']) !== plan.baseHead
232
+ || refactorSidecarDigest(root) !== plan.sidecarSha256) {
233
+ throw new Error('refactor-root-commit-physical-drift');
234
+ }
235
+ return Object.freeze({ schemaVersion: 1, kind: 'root-refactor-staged-verification',
236
+ planSha256, baseHead: plan.baseHead, fileCount: plan.files.length,
237
+ stagedWriteSetSha256: sha(JSON.stringify(plan.files)), gitCommitAuthorized: true,
238
+ checkpointAccepted: false, publicSafe: true });
239
+ }
240
+ catch (error) {
241
+ if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
242
+ throw error;
243
+ throw new Error('refactor-root-commit-unverified');
244
+ }
245
+ }
246
+ function physicalCommit(root, plan) {
247
+ const head = git(root, ['rev-parse', '--verify', 'HEAD']);
248
+ const parents = git(root, ['show', '-s', '--format=%P', head]);
249
+ const object = mutationQaGit(root, ['cat-file', 'commit', head]);
250
+ const bodyOffset = object.indexOf(Buffer.from('\n\n'));
251
+ const message = bodyOffset < 0 ? Buffer.alloc(0) : object.subarray(bodyOffset + 2);
252
+ const expectedMessage = Buffer.from(`${commitSubject(plan.storyId)}\n\n${commitTrailer(plan.planSha256)}\n`);
253
+ if (!GIT_SHA.test(head) || parents !== plan.baseHead || !message.equals(expectedMessage)
254
+ || branch(root) !== plan.branchRef || !allowedDirty(root)
255
+ || refactorSidecarDigest(root) !== plan.sidecarSha256
256
+ || sha(privateBytes(reviewRecordPath(root, plan), 128 * 1024)) !== plan.reviewRecordSha256) {
257
+ throw new Error('refactor-root-commit-physical-drift');
258
+ }
259
+ const changed = ordered(names(root, ['diff-tree', '--no-commit-id', '--name-only',
260
+ '--no-renames', '-r', '-z', head]));
261
+ if (changed.join('\0') !== plan.files.map((file) => file.path).join('\0')) {
262
+ throw new Error('refactor-root-commit-physical-drift');
263
+ }
264
+ for (const file of plan.files) {
265
+ const entry = mutationQaGit(root, ['ls-tree', '-z', head, '--', file.path]).toString('utf8');
266
+ const match = entry.match(/^(100644|100755) blob [a-f0-9]{40,64}\t([^\0]+)\0$/);
267
+ if (!match || match[2] !== file.path
268
+ || match[1] !== ((file.mode & 0o111) ? '100755' : '100644')
269
+ || sha(mutationQaGit(root, ['show', `${head}:${file.path}`])) !== file.sha256
270
+ || physical(root, file.path).sha256 !== file.sha256
271
+ || physical(root, file.path).mode !== file.mode) {
272
+ throw new Error('refactor-root-commit-physical-drift');
273
+ }
274
+ }
275
+ if (git(root, ['rev-parse', '--verify', 'HEAD']) !== head || branch(root) !== plan.branchRef) {
276
+ throw new Error('refactor-root-commit-physical-drift');
277
+ }
278
+ return head;
279
+ }
280
+ export function sealRootRefactorCommit(projectRoot, planSha256, authorizeRootSeal) {
281
+ if (!authorizeRootSeal)
282
+ throw new Error('refactor-root-commit-authorization-required');
283
+ try {
284
+ const root = resolve(projectRoot);
285
+ const plan = readPlan(root, planSha256);
286
+ const commitSha = physicalCommit(root, plan);
287
+ const receipt = Object.freeze({ schemaVersion: 1,
288
+ kind: 'root-refactor-commit-checkpoint', storyId: plan.storyId,
289
+ baseHead: plan.baseHead, commitSha, branchRef: plan.branchRef,
290
+ planSha256, candidateSha256: plan.candidateSha256, reviewSha256: plan.reviewSha256,
291
+ fileCount: plan.files.length, checkpointAccepted: true,
292
+ graphExecution: 'NOT_RUN', publicSafe: true });
293
+ persist(root, checkpointPath(root, planSha256), Buffer.from(`${JSON.stringify(receipt)}\n`));
294
+ if (!privateBytes(checkpointPath(root, planSha256), 8 * 1024)
295
+ .equals(Buffer.from(`${JSON.stringify(receipt)}\n`))) {
296
+ throw new Error('refactor-root-commit-checkpoint-invalid');
297
+ }
298
+ return receipt;
299
+ }
300
+ catch (error) {
301
+ if (error instanceof Error && error.message.startsWith('refactor-root-commit-'))
302
+ throw error;
303
+ throw new Error('refactor-root-commit-unverified');
304
+ }
305
+ }
306
+ export function readRootRefactorCommitCheckpoint(projectRoot, planSha256) {
307
+ try {
308
+ const root = resolve(projectRoot);
309
+ const plan = readPlan(root, planSha256);
310
+ const commitSha = physicalCommit(root, plan);
311
+ const bytes = privateBytes(checkpointPath(root, planSha256), 8 * 1024);
312
+ const receipt = JSON.parse(bytes.toString('utf8'));
313
+ if (!exact(receipt, ['schemaVersion', 'kind', 'storyId', 'baseHead', 'commitSha',
314
+ 'branchRef', 'planSha256', 'candidateSha256', 'reviewSha256', 'fileCount',
315
+ 'checkpointAccepted', 'graphExecution', 'publicSafe'])
316
+ || receipt.schemaVersion !== 1 || receipt.kind !== 'root-refactor-commit-checkpoint'
317
+ || receipt.commitSha !== commitSha || receipt.planSha256 !== planSha256
318
+ || receipt.storyId !== plan.storyId || receipt.baseHead !== plan.baseHead
319
+ || receipt.branchRef !== plan.branchRef || receipt.candidateSha256 !== plan.candidateSha256
320
+ || receipt.reviewSha256 !== plan.reviewSha256 || receipt.fileCount !== plan.files.length
321
+ || receipt.checkpointAccepted !== true || receipt.graphExecution !== 'NOT_RUN'
322
+ || receipt.publicSafe !== true || !bytes.equals(Buffer.from(`${JSON.stringify(receipt)}\n`))) {
323
+ throw new Error('refactor-root-commit-checkpoint-invalid');
324
+ }
325
+ return receipt;
326
+ }
327
+ catch {
328
+ throw new Error('refactor-root-commit-checkpoint-invalid');
329
+ }
330
+ }
331
+ export function refactorCommitCliHandler(args) {
332
+ const action = args[0];
333
+ let projectRoot = '';
334
+ let admissionSha256 = '';
335
+ let baselineSha256 = '';
336
+ let planSha256 = '';
337
+ let authorizeRun = false;
338
+ let authorizePlan = false;
339
+ let authorizeSeal = false;
340
+ let format = 'plain';
341
+ const seen = new Set();
342
+ try {
343
+ if (!['commit-plan', 'commit-staged', 'commit-seal', 'commit-status'].includes(action ?? '')) {
344
+ throw new Error('refactor-root-commit-arguments-invalid');
345
+ }
346
+ for (let index = 1; index < args.length; index++) {
347
+ const token = args[index];
348
+ if (seen.has(token))
349
+ throw new Error('refactor-root-commit-arguments-invalid');
350
+ seen.add(token);
351
+ const next = () => {
352
+ const value = args[++index];
353
+ if (!value || value.startsWith('--'))
354
+ throw new Error('refactor-root-commit-arguments-invalid');
355
+ return value;
356
+ };
357
+ if (token === '--project-root')
358
+ projectRoot = next();
359
+ else if (token === '--admission-sha')
360
+ admissionSha256 = next();
361
+ else if (token === '--baseline-sha')
362
+ baselineSha256 = next();
363
+ else if (token === '--plan-sha')
364
+ planSha256 = next();
365
+ else if (token === '--authorize-run')
366
+ authorizeRun = true;
367
+ else if (token === '--authorize-root-commit-plan')
368
+ authorizePlan = true;
369
+ else if (token === '--authorize-root-seal')
370
+ authorizeSeal = true;
371
+ else if (token === '--format')
372
+ format = next();
373
+ else
374
+ throw new Error('refactor-root-commit-arguments-invalid');
375
+ }
376
+ if (!projectRoot || !['plain', 'json'].includes(format)
377
+ || (action === 'commit-plan' && (!SHA256.test(admissionSha256)
378
+ || !SHA256.test(baselineSha256) || planSha256 || !authorizeRun
379
+ || !authorizePlan || authorizeSeal))
380
+ || (action !== 'commit-plan' && (!SHA256.test(planSha256)
381
+ || admissionSha256 || baselineSha256 || authorizeRun || authorizePlan
382
+ || authorizeSeal !== (action === 'commit-seal')))) {
383
+ throw new Error('refactor-root-commit-arguments-invalid');
384
+ }
385
+ const result = action === 'commit-plan'
386
+ ? prepareRootRefactorCommit(projectRoot, admissionSha256, baselineSha256, authorizePlan)
387
+ : action === 'commit-staged' ? verifyRootRefactorStaged(projectRoot, planSha256)
388
+ : action === 'commit-seal' ? sealRootRefactorCommit(projectRoot, planSha256, authorizeSeal)
389
+ : readRootRefactorCommitCheckpoint(projectRoot, planSha256);
390
+ process.stdout.write(`${JSON.stringify({ ok: true, result })}\n`);
391
+ return 0;
392
+ }
393
+ catch (error) {
394
+ const reasonCode = error instanceof Error && /^refactor-root-[a-z-]+$/.test(error.message)
395
+ ? error.message : 'refactor-root-commit-unverified';
396
+ process.stdout.write(`${JSON.stringify({ ok: false, reasonCode })}\n`);
397
+ return 1;
398
+ }
399
+ }
@@ -1,3 +1,142 @@
1
- import{lstatSync as S,readFileSync as v,realpathSync as R}from"node:fs";import{join as w,resolve as g}from"node:path";import{signNxInvokeRequest as k}from"../../../shared/dist/nx-invoke-signature.js";import{COMMAND_REGISTRY_VERSION as q,COMMAND_REGISTRY_CHECKSUM as C}from"../generated/command-registry.generated.js";import{CLIENT_VERSION as N}from"../version.js";import{loadSecureConfig as b}from"../config/secure-config.js";import{neocortexProfileDirectory as _}from"../config/profile-directory.js";import{EncryptedCache as A}from"../cache/encrypted-cache.js";import{LicenseClient as T}from"../license/license-client.js";import{detectPlatform as I}from"../adapters/platform-detector.js";const y=new Set(["refactor-control-input-invalid","refactor-control-auth-required","refactor-control-tier-required","refactor-control-read-only","refactor-control-signature-required","refactor-control-client-unsupported","refactor-control-registry-mismatch","refactor-control-executor-unavailable"]),L=new Set(["arguments-invalid","authorization-required","host-unsupported","project-unbound","auth-required","response-invalid","request-refused","outcome-unknown"].map(e=>`refactor-root-control-${e}`));async function j(e){const o=e.body?.getReader();if(!o)throw new Error("refactor-root-control-response-invalid");let n=!1;try{const t=[];let c=0;for(;;){const a=await o.read();if(a.done){n=!0;break}if(c+=a.value.byteLength,c>16384)throw new Error("refactor-root-control-response-invalid");t.push(Buffer.from(a.value))}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(t,c)))}catch{throw new Error("refactor-root-control-response-invalid")}finally{n||await o.cancel().catch(()=>{}),o.releaseLock()}}async function E(e,o,n=fetch){if(e!=="refactor"&&e!=="qa")throw new Error("refactor-root-control-arguments-invalid");const t=`/api/v1/invoke/${e}/control`,c=k({method:"POST",target:t,body:Buffer.from(JSON.stringify({projectId:o.projectId,storyId:o.storyId,platformTarget:o.platformTarget,registryVersion:q,registryChecksum:C})),bearerToken:o.token,clientVersion:N}),a=await n(`${o.serverUrl.replace(/\/+$/,"")}${t}`,{method:"POST",redirect:"error",signal:AbortSignal.timeout(2e5),headers:{...c.headers,Authorization:`Bearer ${o.token}`},body:c.body}),r=await j(a);if(!a.ok)throw new Error(typeof r?.error_code=="string"&&y.has(r.error_code.replace(/^qa-/,"refactor-"))&&r.error_code.startsWith(`${e}-`)?r.error_code:"refactor-root-control-request-refused");const l=["schemaVersion","kind","status","completedStages","authority","qaAccepted","gitAuthority","billingAuthority","publicSafe"];if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>!l.includes(s))||r.schemaVersion!==1||r.kind!==`root-${e}-control`||typeof r.status!="string"||!["advanced","waiting","blocked","candidate-ready",...e==="qa"?["debt"]:[]].includes(r.status)||r.authority!==(e==="qa"?"LOCAL_ROOT_QA_CANDIDATE_ONLY":"LOCAL_ROOT_CANDIDATE_ONLY")||r.qaAccepted!==!1||r.gitAuthority!=="NONE"||r.billingAuthority!=="NONE"||r.publicSafe!==!0||r.completedStages!==void 0&&(typeof r.completedStages!="number"||!Number.isInteger(r.completedStages)||r.completedStages<0||r.completedStages>(e==="qa"?3:7)))throw new Error("refactor-root-control-response-invalid");return r}async function B(e,o=fetch){return E("refactor",e,o)}async function Y(e,o="refactor"){try{let n="",t="",c=!1,a="json";const r=[...e];if(r.shift()!=="control")throw new Error("refactor-root-control-arguments-invalid");for(let i=0;i<r.length;i++){const d=r[i];if(d==="--authorize-root-control")c=!0;else if(d==="--project-root")n=r[++i]??"";else if(d==="--story")t=r[++i]??"";else if(d==="--format")a=r[++i]??"";else throw new Error("refactor-root-control-arguments-invalid")}if(!c||!n||a!=="json"||!/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/.test(t))throw new Error("refactor-root-control-authorization-required");const l=I({cwd:g(n),env:process.env}).targetId;if(l!=="codex")throw new Error("refactor-root-control-host-unsupported");const s=w(g(n),".neocortex","state.json"),u=S(s);if(!u.isFile()||u.isSymbolicLink()||R(s)!==s||u.size>16*1024*1024)throw new Error("refactor-root-control-project-unbound");const p=JSON.parse(v(s,"utf8")).config?.project_id;if(typeof p!="string"||!/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(p))throw new Error("refactor-root-control-project-unbound");const f=b({strictReadOnly:!0});if(!f?.licenseKey)throw new Error("refactor-root-control-auth-required");const h=process.env.NEOCORTEX_SERVER_URL??f.serverUrl;if(!h)throw new Error("refactor-root-control-auth-required");const m=await new T({serverUrl:h,licenseKey:f.licenseKey,cacheProvider:new A({cacheDir:w(_(),"cache"),passphrase:f.licenseKey})}).getToken();if(!m)throw new Error("refactor-root-control-auth-required");const O=await E(o,{serverUrl:h,token:m,projectId:p,storyId:t,platformTarget:l});return process.stdout.write(`${JSON.stringify({ok:!0,control:O})}
2
- `),0}catch(n){const t=n instanceof Error?n.message.replace(/^qa-/,"refactor-"):"",c=L.has(t)||y.has(t)?t:"refactor-root-control-outcome-unknown";return process.stdout.write(`${JSON.stringify({ok:!1,reasonCode:o==="qa"?c.replace(/^refactor-/,"qa-"):c})}
3
- `),1}}export{Y as refactorControlCliHandler,B as requestRefactorControl,E as requestRootControl};
1
+ /** Mechanical authenticated control transport; workflow decisions stay server-side. */
2
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { signNxInvokeRequest } from '../../../shared/dist/nx-invoke-signature.js';
5
+ import { COMMAND_REGISTRY_VERSION, COMMAND_REGISTRY_CHECKSUM } from '../generated/command-registry.generated.js';
6
+ import { CLIENT_VERSION } from '../version.js';
7
+ import { loadSecureConfig } from '../config/secure-config.js';
8
+ import { neocortexProfileDirectory } from '../config/profile-directory.js';
9
+ import { EncryptedCache } from '../cache/encrypted-cache.js';
10
+ import { LicenseClient } from '../license/license-client.js';
11
+ import { detectPlatform } from '../adapters/platform-detector.js';
12
+ const CONTROL_ERRORS = new Set([
13
+ 'refactor-control-input-invalid', 'refactor-control-auth-required',
14
+ 'refactor-control-tier-required', 'refactor-control-read-only',
15
+ 'refactor-control-signature-required', 'refactor-control-client-unsupported',
16
+ 'refactor-control-registry-mismatch', 'refactor-control-executor-unavailable',
17
+ ]);
18
+ const CLIENT_CONTROL_ERRORS = new Set(['arguments-invalid', 'authorization-required', 'host-unsupported',
19
+ 'project-unbound', 'auth-required', 'response-invalid', 'request-refused', 'outcome-unknown']
20
+ .map(code => `refactor-root-control-${code}`));
21
+ /** Enforce the byte budget while receiving; do not buffer an unbounded body. */
22
+ async function readControlResponse(response) {
23
+ const reader = response.body?.getReader();
24
+ if (!reader)
25
+ throw new Error('refactor-root-control-response-invalid');
26
+ let complete = false;
27
+ try {
28
+ const chunks = [];
29
+ let size = 0;
30
+ for (;;) {
31
+ const next = await reader.read();
32
+ if (next.done) {
33
+ complete = true;
34
+ break;
35
+ }
36
+ size += next.value.byteLength;
37
+ if (size > 16384)
38
+ throw new Error('refactor-root-control-response-invalid');
39
+ chunks.push(Buffer.from(next.value));
40
+ }
41
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size)));
42
+ }
43
+ catch {
44
+ throw new Error('refactor-root-control-response-invalid');
45
+ }
46
+ finally {
47
+ if (!complete)
48
+ await reader.cancel().catch(() => undefined);
49
+ reader.releaseLock();
50
+ }
51
+ }
52
+ export async function requestRootControl(family, input, fetchFn = fetch) {
53
+ if (family !== 'refactor' && family !== 'qa')
54
+ throw new Error('refactor-root-control-arguments-invalid');
55
+ const target = `/api/v1/invoke/${family}/control`;
56
+ const attempt = signNxInvokeRequest({ method: 'POST', target,
57
+ body: Buffer.from(JSON.stringify({ projectId: input.projectId, storyId: input.storyId,
58
+ platformTarget: input.platformTarget, registryVersion: COMMAND_REGISTRY_VERSION, registryChecksum: COMMAND_REGISTRY_CHECKSUM })),
59
+ bearerToken: input.token, clientVersion: CLIENT_VERSION });
60
+ const response = await fetchFn(`${input.serverUrl.replace(/\/+$/, '')}${target}`, {
61
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(200000),
62
+ headers: { ...attempt.headers, Authorization: `Bearer ${input.token}` }, body: attempt.body,
63
+ });
64
+ const value = await readControlResponse(response);
65
+ if (!response.ok)
66
+ throw new Error(typeof value?.error_code === 'string'
67
+ && CONTROL_ERRORS.has(value.error_code.replace(/^qa-/, 'refactor-')) && value.error_code.startsWith(`${family}-`) ? value.error_code : 'refactor-root-control-request-refused');
68
+ const keys = ['schemaVersion', 'kind', 'status', 'completedStages', 'authority', 'qaAccepted', 'gitAuthority', 'billingAuthority', 'publicSafe'];
69
+ if (!value || typeof value !== 'object' || Array.isArray(value)
70
+ || Object.keys(value).some(key => !keys.includes(key))
71
+ || value.schemaVersion !== 1 || value.kind !== `root-${family}-control`
72
+ || typeof value.status !== 'string' || !['advanced', 'waiting', 'blocked', 'candidate-ready', ...(family === 'qa' ? ['debt'] : [])].includes(value.status)
73
+ || value.authority !== (family === 'qa' ? 'LOCAL_ROOT_QA_CANDIDATE_ONLY' : 'LOCAL_ROOT_CANDIDATE_ONLY') || value.qaAccepted !== false
74
+ || value.gitAuthority !== 'NONE' || value.billingAuthority !== 'NONE' || value.publicSafe !== true
75
+ || value.completedStages !== undefined && (typeof value.completedStages !== 'number' || !Number.isInteger(value.completedStages)
76
+ || value.completedStages < 0 || value.completedStages > (family === 'qa' ? 3 : 7))) {
77
+ throw new Error('refactor-root-control-response-invalid');
78
+ }
79
+ return value;
80
+ }
81
+ export async function requestRefactorControl(input, fetchFn = fetch) {
82
+ return requestRootControl('refactor', input, fetchFn);
83
+ }
84
+ export async function refactorControlCliHandler(args, family = 'refactor') {
85
+ try {
86
+ let root = '';
87
+ let storyId = '';
88
+ let authorized = false;
89
+ let format = 'json';
90
+ const tokens = [...args];
91
+ if (tokens.shift() !== 'control')
92
+ throw new Error('refactor-root-control-arguments-invalid');
93
+ for (let i = 0; i < tokens.length; i++) {
94
+ const token = tokens[i];
95
+ if (token === '--authorize-root-control')
96
+ authorized = true;
97
+ else if (token === '--project-root')
98
+ root = tokens[++i] ?? '';
99
+ else if (token === '--story')
100
+ storyId = tokens[++i] ?? '';
101
+ else if (token === '--format')
102
+ format = tokens[++i] ?? '';
103
+ else
104
+ throw new Error('refactor-root-control-arguments-invalid');
105
+ }
106
+ if (!authorized || !root || format !== 'json' || !/^P[0-9]{1,12}(?:\.[0-9]{1,12}){1,3}$/.test(storyId)) {
107
+ throw new Error('refactor-root-control-authorization-required');
108
+ }
109
+ const platformTarget = detectPlatform({ cwd: resolve(root), env: process.env }).targetId;
110
+ if (platformTarget !== 'codex')
111
+ throw new Error('refactor-root-control-host-unsupported');
112
+ const path = join(resolve(root), '.neocortex', 'state.json');
113
+ const stat = lstatSync(path);
114
+ if (!stat.isFile() || stat.isSymbolicLink() || realpathSync(path) !== path || stat.size > 16 * 1024 * 1024) {
115
+ throw new Error('refactor-root-control-project-unbound');
116
+ }
117
+ const projectId = JSON.parse(readFileSync(path, 'utf8')).config?.project_id;
118
+ if (typeof projectId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{15,127}$/.test(projectId)) {
119
+ throw new Error('refactor-root-control-project-unbound');
120
+ }
121
+ const config = loadSecureConfig({ strictReadOnly: true });
122
+ if (!config?.licenseKey)
123
+ throw new Error('refactor-root-control-auth-required');
124
+ const serverUrl = process.env.NEOCORTEX_SERVER_URL ?? config.serverUrl;
125
+ if (!serverUrl)
126
+ throw new Error('refactor-root-control-auth-required');
127
+ const token = await new LicenseClient({ serverUrl, licenseKey: config.licenseKey,
128
+ cacheProvider: new EncryptedCache({ cacheDir: join(neocortexProfileDirectory(), 'cache'), passphrase: config.licenseKey }) }).getToken();
129
+ if (!token)
130
+ throw new Error('refactor-root-control-auth-required');
131
+ const result = await requestRootControl(family, { serverUrl, token, projectId, storyId, platformTarget });
132
+ process.stdout.write(`${JSON.stringify({ ok: true, control: result })}\n`);
133
+ return 0;
134
+ }
135
+ catch (error) {
136
+ const message = error instanceof Error ? error.message.replace(/^qa-/, 'refactor-') : '';
137
+ const reasonCode = CLIENT_CONTROL_ERRORS.has(message) || CONTROL_ERRORS.has(message)
138
+ ? message : 'refactor-root-control-outcome-unknown';
139
+ process.stdout.write(`${JSON.stringify({ ok: false, reasonCode: family === 'qa' ? reasonCode.replace(/^refactor-/, 'qa-') : reasonCode })}\n`);
140
+ return 1;
141
+ }
142
+ }