@ornexus/neocortex 4.60.66 → 4.60.68

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 (236) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1598 -1640
  3. package/install.ps1 +1 -1
  4. package/install.sh +2 -1
  5. package/package.json +10 -7
  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 +303 -3
  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.d.ts +135 -0
  37. package/packages/client/dist/commands/doctor.js +635 -0
  38. package/packages/client/dist/commands/invoke.d.ts +18 -0
  39. package/packages/client/dist/commands/invoke.js +7140 -142
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  41. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  42. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  44. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  45. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  46. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  47. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  49. package/packages/client/dist/commands/mutation-qa.js +220 -1
  50. package/packages/client/dist/commands/native-agent.js +136 -2
  51. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  52. package/packages/client/dist/commands/planning-generation.js +53 -1
  53. package/packages/client/dist/commands/planning-memory.js +40 -1
  54. package/packages/client/dist/commands/planning-research.js +42 -1
  55. package/packages/client/dist/commands/private-session.js +75 -1
  56. package/packages/client/dist/commands/property-qa.js +139 -1
  57. package/packages/client/dist/commands/qa-control.js +16 -1
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  60. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  61. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  62. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  68. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  69. package/packages/client/dist/commands/refactor-commit.js +399 -13
  70. package/packages/client/dist/commands/refactor-control.js +142 -3
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  72. package/packages/client/dist/commands/refactor-review.js +283 -5
  73. package/packages/client/dist/commands/refactor-root.js +588 -7
  74. package/packages/client/dist/commands/refresh-memory.js +156 -3
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  76. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  77. package/packages/client/dist/config/profile-directory.js +13 -1
  78. package/packages/client/dist/config/resolver-selection.js +278 -1
  79. package/packages/client/dist/config/secure-config.js +281 -12
  80. package/packages/client/dist/config.js +223 -2
  81. package/packages/client/dist/constants.js +25 -1
  82. package/packages/client/dist/context/context-collector.js +222 -2
  83. package/packages/client/dist/context/context-sanitizer.js +145 -1
  84. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  85. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  86. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  87. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  88. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  89. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  90. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  91. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  92. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  93. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  94. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  95. package/packages/client/dist/continuity/outbox.js +117 -1
  96. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  97. package/packages/client/dist/continuity/sqlite-store.js +2536 -81
  98. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  99. package/packages/client/dist/errors/error-messages.js +228 -2
  100. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  101. package/packages/client/dist/evidence/collector.js +347 -1
  102. package/packages/client/dist/evidence/index.js +1 -1
  103. package/packages/client/dist/evidence/types.js +2 -0
  104. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  105. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  106. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  107. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  108. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  109. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  110. package/packages/client/dist/git/git-lifecycle-store.js +1938 -9
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  113. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  117. package/packages/client/dist/i18n/first-run.js +60 -2
  118. package/packages/client/dist/index.js +47 -1
  119. package/packages/client/dist/invocation/invoke-input.js +24 -1
  120. package/packages/client/dist/license/index.js +5 -1
  121. package/packages/client/dist/license/license-client.js +304 -1
  122. package/packages/client/dist/machine/fingerprint.js +163 -2
  123. package/packages/client/dist/machine/index.js +5 -1
  124. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  125. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  126. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  127. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  128. package/packages/client/dist/migrations/project-identity.js +493 -7
  129. package/packages/client/dist/migrations/state-json.js +344 -4
  130. package/packages/client/dist/policy/architecture-policy.js +184 -2
  131. package/packages/client/dist/policy/index.js +7 -1
  132. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  133. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  134. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  135. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  136. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  137. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  138. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  139. package/packages/client/dist/private-execution/delivery.js +410 -13
  140. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  141. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  142. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  143. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  144. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  145. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  146. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  147. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  148. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  149. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  150. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  151. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  152. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  153. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  154. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  155. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  156. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  157. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  158. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  159. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  160. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  161. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  162. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  163. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  164. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  165. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  166. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  167. package/packages/client/dist/private-execution/session-lease.js +63 -1
  168. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  169. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  170. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  171. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  172. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  173. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  174. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  175. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  176. package/packages/client/dist/resilience/index.js +8 -1
  177. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  178. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  179. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  180. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  181. package/packages/client/dist/runner/binary.js +404 -1
  182. package/packages/client/dist/runner/cli.js +1571 -17
  183. package/packages/client/dist/runner/headless/adapters.js +49 -1
  184. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  185. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  186. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  187. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  188. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  189. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  190. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  191. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  192. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  193. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  194. package/packages/client/dist/runner/headless/resolver.js +231 -1
  195. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  196. package/packages/client/dist/runner/headless/run-yoloop.d.ts +4 -1
  197. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  198. package/packages/client/dist/runner/headless/types.js +574 -2
  199. package/packages/client/dist/runner/local-console.js +396 -13
  200. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  201. package/packages/client/dist/runner/project-identity.js +106 -1
  202. package/packages/client/dist/runner/scheduler.js +995 -7
  203. package/packages/client/dist/runner-cli.js +18 -2
  204. package/packages/client/dist/state/invocation-shape.js +13 -1
  205. package/packages/client/dist/state/project-state-snapshot.js +1677 -1
  206. package/packages/client/dist/state/state-json-repair.js +785 -3
  207. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  208. package/packages/client/dist/telemetry/index.js +5 -1
  209. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  210. package/packages/client/dist/tier/index.js +5 -1
  211. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  212. package/packages/client/dist/types/index.js +38 -1
  213. package/packages/client/dist/version.js +27 -1
  214. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  215. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  216. package/packages/client/dist/yolo/spec-envelope-collector.js +185 -5
  217. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  218. package/packages/client/dist/yoloop/index.js +8 -1
  219. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  220. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  221. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  222. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  223. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1723 -1
  224. package/packages/shared/dist/compatibility/index.js +476 -0
  225. package/packages/shared/dist/yoloop/release-blocked.js +653 -0
  226. package/targets-stubs/antigravity/gemini.md +1 -1
  227. package/targets-stubs/antigravity/skill/SKILL.md +3 -2
  228. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  229. package/targets-stubs/claude-code/neocortex-root.md +5 -5
  230. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  231. package/targets-stubs/claude-code/neocortex.md +8 -9
  232. package/targets-stubs/codex/AGENTS.md +3 -3
  233. package/targets-stubs/cursor/agent.md +4 -3
  234. package/targets-stubs/gemini-cli/agent.md +5 -4
  235. package/targets-stubs/opencode/neocortex-root.md +3 -3
  236. package/targets-stubs/vscode/neocortex.agent.md +5 -4
@@ -1,4 +1,344 @@
1
- import{createHash as q,randomUUID as N}from"node:crypto";import{existsSync as S,linkSync as J,lstatSync as E,mkdirSync as z,readFileSync as h,realpathSync as G,statSync as j,unlinkSync as v}from"node:fs";import{dirname as A,join as d,resolve as K}from"node:path";import{assertStateMigrationPlanV1 as X,assertStateMigrationReceiptV1 as Y,planStateMigration as T,stateMigrationDigest as Q,STATE_MIGRATION_RECEIPT_SCHEMA as W,StateMigrationHardStopError as B}from"../../../shared/dist/state/index.js";import{atomicReplaceUtf8 as M,durableCreateUtf8 as L,fsyncDirectoryBestEffort as O,recoverAtomicReplaceUtf8 as V}from"../fs/atomic-state-replace.js";const D=d(".neocortex","state.json"),R=d(".neocortex","state-migration.json"),Z=d(".neocortex","state-migration.lock"),P=4*1024*1024;class o extends Error{reasonCode;receipt;constructor(e,a=e,t){super(a),this.reasonCode=e,this.receipt=t,this.name="StateMigrationApplyError"}}const _=i=>q("sha256").update(i).digest("hex"),tt=i=>`${JSON.stringify(i,null,2)}
2
- `;function $(i){let e;try{e=G(K(i))}catch{throw new o("state_migration_root_invalid")}if(!j(e).isDirectory())throw new o("state_migration_root_invalid");for(const a of[".neocortex",D,R]){const t=d(e,a);if(!S(t))continue;const s=E(t);if(s.isSymbolicLink()||a!==".neocortex"&&!s.isFile()||a===".neocortex"&&!s.isDirectory())throw new o("state_migration_symlink_or_type_rejected")}return e}function U(i){try{const e=JSON.parse(i);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}throw new o("state_migration_state_corrupt")}function F(i){const e=d(i,D);if(!S(e))throw new o("state_migration_state_missing");const a=j(e).size;if(a>P)throw new o("state_migration_input_too_large");const t=h(e,"utf8"),s=Buffer.byteLength(t,"utf8");if(s!==a||s>P)throw new o("state_migration_source_changed");return{state:U(t),raw:t,digest:_(t),bytes:s}}function ct(i){const e=F($(i));let a;try{a=T(e.state)}catch(l){throw l instanceof B?new o(l.reasonCode,l.message):l}const t=a.kind==="migrate"?a.plan.targetState:e.state,s=(l,p)=>{const n=l[p];return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).length:0},c=a.kind==="migrate"?(({targetState:l,...p})=>p)(a.plan):null;return Object.freeze({schemaVersion:"StateMigrationAuthority/1.0",sourceByteDigest:e.digest,sourceCanonicalHash:a.kind==="migrate"?a.plan.sourceCanonicalHash:a.sourceCanonicalHash,sourceByteLength:e.bytes,before:{epics:s(e.state,"epics"),stories:s(e.state,"stories")},after:{epics:s(t,"epics"),stories:s(t,"stories")},outcome:a.kind,plan:c,publicSafe:!0})}function et(i){const e=d(i,Z);z(A(e),{recursive:!0,mode:448});const a=N(),t=`${process.pid}:${a}
3
- `,s=()=>{const c=`${e}.${process.pid}.${N()}.owner`;L(c,t);try{J(c,e)}finally{try{v(c)}catch{}O(A(e))}};try{s()}catch(c){if(c.code!=="EEXIST")throw new o("state_migration_lock_failed");const l=E(e);if(l.isSymbolicLink()||!l.isFile())throw new o("state_migration_lock_corrupt");const p=h(e,"utf8"),n=p.match(/^([1-9][0-9]*):([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\n$/i);if(!n||p.length>64)throw new o("state_migration_lock_corrupt");let f=!0;try{process.kill(Number(n[1]),0)}catch(r){f=r.code!=="ESRCH"}if(f)throw new o("state_migration_locked");try{v(e),s()}catch{throw new o("state_migration_locked")}}return()=>{try{if(h(e,"utf8")!==t)return;v(e),O(A(e))}catch{}}}function rt(i){const e=d(i,R);if(V(e),!S(e))return null;let a;try{a=JSON.parse(h(e,"utf8"))}catch{throw new o("state_migration_manifest_corrupt")}if(!a||typeof a!="object"||Array.isArray(a))throw new o("state_migration_manifest_corrupt");const t=a;if(t.schemaVersion!==1||typeof t.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(t.operationId)||!["prepared","applied","rolled-back"].includes(String(t.phase))||typeof t.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(t.sourceCanonicalHash)||typeof t.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(t.sourceByteDigest)||typeof t.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(t.targetCanonicalHash)||typeof t.targetByteDigest!="string"||!/^[a-f0-9]{64}$/.test(t.targetByteDigest)||!Number.isSafeInteger(t.migratedEpicCount)||(t.migratedEpicCount??-1)<0||!Number.isSafeInteger(t.migratedStoryCount)||(t.migratedStoryCount??-1)<0||!Number.isSafeInteger(t.preservedUnknownFieldCount)||(t.preservedUnknownFieldCount??-1)<0||typeof t.backupPath!="string"||t.backupPath!==d(".neocortex",`state.json.migration-backup-${t.operationId}`))throw new o("state_migration_manifest_corrupt");return t}function b(i,e){M(d(i,R),`${JSON.stringify(e,null,2)}
4
- `)}function k(i,e,a,t,s,c,l,p,n,f,r,g){const m={schemaVersion:W,operationId:e,outcome:i,sourceBytesHash:a,targetBytesHash:t,sourceCanonicalHash:s,targetCanonicalHash:c,backupHash:l,rollbackStatus:p,migratedEpicCount:n,migratedStoryCount:f,preservedUnknownFieldCount:r,reasonCodes:g,publicSafe:!0};return Y(m),m}function lt(i){const e=$(i);let a;try{a=T(F(e).state)}catch(t){throw t instanceof B?new o(t.reasonCode,t.message):t}return a.kind==="migrate"?a.plan:null}function pt(i,e,a={}){const t=$(i),s=et(t);try{const c=d(t,D);try{V(c)}catch{throw new o("state_migration_atomic_recovery_failed")}if(!S(c))throw new o("state_migration_state_missing");const l=F(t).raw;if(e?.sourceByteDigest&&_(l)!==e.sourceByteDigest)throw new o("state_migration_expected_bytes_conflict");let p;try{p=T(U(l))}catch(u){throw u instanceof B?new o(u.reasonCode,u.message):u}const n=rt(t),f=_(l);if(p.kind==="unchanged"){if(e&&p.sourceCanonicalHash!==e.targetCanonicalHash)throw new o("state_migration_expected_plan_conflict");if(n&&n.targetCanonicalHash===p.sourceCanonicalHash){if(n.targetByteDigest!==f)throw new o("state_migration_state_drift");if(n.phase==="prepared"&&b(t,{...n,phase:"applied"}),n.phase==="rolled-back")throw new o("state_migration_state_drift");return k("already-applied",n.operationId,n.sourceByteDigest,n.targetByteDigest,n.sourceCanonicalHash,n.targetCanonicalHash,n.sourceByteDigest,"not-required",n.migratedEpicCount,n.migratedStoryCount,n.preservedUnknownFieldCount,["migration_replay_verified"])}if(n)throw new o("state_migration_state_drift");return k("already-applied",e?.operationId??"smig_00000000000000000000000000000000",f,f,p.sourceCanonicalHash,p.sourceCanonicalHash,null,"not-required",0,0,0,["canonical_state_unchanged"])}const r=p.plan;if(X(r),e&&(e.operationId!==r.operationId||e.sourceCanonicalHash!==r.sourceCanonicalHash||e.targetCanonicalHash!==r.targetCanonicalHash))throw new o("state_migration_expected_plan_conflict");if(n&&n.operationId!==r.operationId)throw new o("state_migration_operation_conflict");const g=f,m=tt(r.targetState),w=_(m),x=d(".neocortex",`state.json.migration-backup-${r.operationId}`),y=d(t,x);if(S(y)){const u=E(y);if(u.isSymbolicLink()||!u.isFile()||_(h(y))!==g)throw new o("state_migration_backup_conflict")}else L(y,l);const I={schemaVersion:1,operationId:r.operationId,phase:"prepared",sourceCanonicalHash:r.sourceCanonicalHash,sourceByteDigest:g,targetCanonicalHash:r.targetCanonicalHash,targetByteDigest:w,migratedEpicCount:r.migratedEpicIds.length,migratedStoryCount:r.migratedStoryIds.length,preservedUnknownFieldCount:r.preservedUnknownFieldCount,backupPath:x};if(b(t,I),a.afterPrepared?.(c),_(h(c))!==g)throw new o("state_migration_source_cas_conflict");try{M(c,m),a.afterReplace?.(c);const u=h(c,"utf8"),H=U(u);if(_(u)!==w||Q(H)!==r.targetCanonicalHash)throw new Error("readback-digest-mismatch");b(t,{...I,phase:"applied"})}catch(u){try{const C=h(y,"utf8");if(_(C)!==g)throw new Error("rollback-backup-digest-mismatch");if(M(c,C),_(h(c))!==g)throw new Error("rollback-digest-mismatch");b(t,{...I,phase:"rolled-back"})}catch{const C=k("blocked",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"unverified",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["apply_failed","rollback_unverified"]);throw new o("state_migration_rollback_failed",String(u),C)}const H=k("blocked",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"restored",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["apply_failed","rollback_verified"]);throw new o("state_migration_apply_rolled_back",String(u),H)}return k("applied",r.operationId,g,w,r.sourceCanonicalHash,r.targetCanonicalHash,g,"not-required",r.migratedEpicIds.length,r.migratedStoryIds.length,r.preservedUnknownFieldCount,["lock_acquired","source_cas_verified","backup_verified","atomic_replace_verified"])}finally{s()}}export{P as STATE_MIGRATION_INPUT_LIMIT_BYTES,o as StateMigrationApplyError,pt as applyStateMigration,ct as collectStateMigrationAuthority,lt as previewStateMigration};
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, unlinkSync, } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { assertStateMigrationPlanV1, assertStateMigrationReceiptV1, planStateMigration, stateMigrationDigest, STATE_MIGRATION_RECEIPT_SCHEMA, StateMigrationHardStopError, } from '../../../shared/dist/state/index.js';
5
+ import { atomicReplaceUtf8, durableCreateUtf8, fsyncDirectoryBestEffort, recoverAtomicReplaceUtf8, } from '../fs/atomic-state-replace.js';
6
+ const STATE_RELATIVE_PATH = join('.neocortex', 'state.json');
7
+ const MANIFEST_RELATIVE_PATH = join('.neocortex', 'state-migration.json');
8
+ const LOCK_RELATIVE_PATH = join('.neocortex', 'state-migration.lock');
9
+ export const STATE_MIGRATION_INPUT_LIMIT_BYTES = 4 * 1024 * 1024;
10
+ export class StateMigrationApplyError extends Error {
11
+ reasonCode;
12
+ receipt;
13
+ constructor(reasonCode, message = reasonCode, receipt) {
14
+ super(message);
15
+ this.reasonCode = reasonCode;
16
+ this.receipt = receipt;
17
+ this.name = 'StateMigrationApplyError';
18
+ }
19
+ }
20
+ const sha256Bytes = (value) => createHash('sha256').update(value).digest('hex');
21
+ const stateRaw = (state) => `${JSON.stringify(state, null, 2)}\n`;
22
+ function safeRoot(projectRoot) {
23
+ let root;
24
+ try {
25
+ root = realpathSync(resolve(projectRoot));
26
+ }
27
+ catch {
28
+ throw new StateMigrationApplyError('state_migration_root_invalid');
29
+ }
30
+ if (!statSync(root).isDirectory())
31
+ throw new StateMigrationApplyError('state_migration_root_invalid');
32
+ for (const relative of ['.neocortex', STATE_RELATIVE_PATH, MANIFEST_RELATIVE_PATH]) {
33
+ const path = join(root, relative);
34
+ if (!existsSync(path))
35
+ continue;
36
+ const stat = lstatSync(path);
37
+ if (stat.isSymbolicLink() || (relative !== '.neocortex' && !stat.isFile()) || (relative === '.neocortex' && !stat.isDirectory())) {
38
+ throw new StateMigrationApplyError('state_migration_symlink_or_type_rejected');
39
+ }
40
+ }
41
+ return root;
42
+ }
43
+ function parseState(raw) {
44
+ try {
45
+ const parsed = JSON.parse(raw);
46
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
47
+ return parsed;
48
+ }
49
+ catch { /* normalized below */ }
50
+ throw new StateMigrationApplyError('state_migration_state_corrupt');
51
+ }
52
+ function readBoundedState(root) {
53
+ const statePath = join(root, STATE_RELATIVE_PATH);
54
+ if (!existsSync(statePath))
55
+ throw new StateMigrationApplyError('state_migration_state_missing');
56
+ const size = statSync(statePath).size;
57
+ if (size > STATE_MIGRATION_INPUT_LIMIT_BYTES)
58
+ throw new StateMigrationApplyError('state_migration_input_too_large');
59
+ const raw = readFileSync(statePath, 'utf8');
60
+ const bytes = Buffer.byteLength(raw, 'utf8');
61
+ if (bytes !== size || bytes > STATE_MIGRATION_INPUT_LIMIT_BYTES) {
62
+ throw new StateMigrationApplyError('state_migration_source_changed');
63
+ }
64
+ return { state: parseState(raw), raw, digest: sha256Bytes(raw), bytes };
65
+ }
66
+ export function collectStateMigrationAuthority(projectRoot) {
67
+ const source = readBoundedState(safeRoot(projectRoot));
68
+ let decision;
69
+ try {
70
+ decision = planStateMigration(source.state);
71
+ }
72
+ catch (error) {
73
+ if (error instanceof StateMigrationHardStopError)
74
+ throw new StateMigrationApplyError(error.reasonCode, error.message);
75
+ throw error;
76
+ }
77
+ const target = decision.kind === 'migrate' ? decision.plan.targetState : source.state;
78
+ const count = (record, key) => {
79
+ const value = record[key];
80
+ return value && typeof value === 'object' && !Array.isArray(value) ? Object.keys(value).length : 0;
81
+ };
82
+ const plan = decision.kind === 'migrate'
83
+ ? (({ targetState: _privateTargetState, ...publicPlan }) => publicPlan)(decision.plan)
84
+ : null;
85
+ return Object.freeze({
86
+ schemaVersion: 'StateMigrationAuthority/1.0',
87
+ sourceByteDigest: source.digest,
88
+ sourceCanonicalHash: decision.kind === 'migrate' ? decision.plan.sourceCanonicalHash : decision.sourceCanonicalHash,
89
+ sourceByteLength: source.bytes,
90
+ before: { epics: count(source.state, 'epics'), stories: count(source.state, 'stories') },
91
+ after: { epics: count(target, 'epics'), stories: count(target, 'stories') },
92
+ outcome: decision.kind,
93
+ plan,
94
+ publicSafe: true,
95
+ });
96
+ }
97
+ function claimLock(root) {
98
+ const lockPath = join(root, LOCK_RELATIVE_PATH);
99
+ mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
100
+ const ownerToken = randomUUID();
101
+ const ownerContents = `${process.pid}:${ownerToken}\n`;
102
+ const acquire = () => {
103
+ const ownerPath = `${lockPath}.${process.pid}.${randomUUID()}.owner`;
104
+ durableCreateUtf8(ownerPath, ownerContents);
105
+ try {
106
+ linkSync(ownerPath, lockPath);
107
+ }
108
+ finally {
109
+ try {
110
+ unlinkSync(ownerPath);
111
+ }
112
+ catch { /* orphan owners have no authority */ }
113
+ fsyncDirectoryBestEffort(dirname(lockPath));
114
+ }
115
+ };
116
+ try {
117
+ acquire();
118
+ }
119
+ catch (error) {
120
+ if (error.code !== 'EEXIST')
121
+ throw new StateMigrationApplyError('state_migration_lock_failed');
122
+ const stat = lstatSync(lockPath);
123
+ if (stat.isSymbolicLink() || !stat.isFile())
124
+ throw new StateMigrationApplyError('state_migration_lock_corrupt');
125
+ const owner = readFileSync(lockPath, 'utf8');
126
+ const ownerMatch = owner.match(/^([1-9][0-9]*):([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\n$/i);
127
+ if (!ownerMatch || owner.length > 64)
128
+ throw new StateMigrationApplyError('state_migration_lock_corrupt');
129
+ let alive = true;
130
+ try {
131
+ process.kill(Number(ownerMatch[1]), 0);
132
+ }
133
+ catch (probe) {
134
+ alive = probe.code !== 'ESRCH';
135
+ }
136
+ if (alive)
137
+ throw new StateMigrationApplyError('state_migration_locked');
138
+ try {
139
+ unlinkSync(lockPath);
140
+ acquire();
141
+ }
142
+ catch {
143
+ throw new StateMigrationApplyError('state_migration_locked');
144
+ }
145
+ }
146
+ return () => {
147
+ try {
148
+ if (readFileSync(lockPath, 'utf8') !== ownerContents)
149
+ return;
150
+ unlinkSync(lockPath);
151
+ fsyncDirectoryBestEffort(dirname(lockPath));
152
+ }
153
+ catch { /* cleanup is best effort; never delete an unproven foreign lock */ }
154
+ };
155
+ }
156
+ function parseManifest(root) {
157
+ const path = join(root, MANIFEST_RELATIVE_PATH);
158
+ recoverAtomicReplaceUtf8(path);
159
+ if (!existsSync(path))
160
+ return null;
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(readFileSync(path, 'utf8'));
164
+ }
165
+ catch {
166
+ throw new StateMigrationApplyError('state_migration_manifest_corrupt');
167
+ }
168
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
169
+ throw new StateMigrationApplyError('state_migration_manifest_corrupt');
170
+ const value = parsed;
171
+ if (value.schemaVersion !== 1
172
+ || typeof value.operationId !== 'string' || !/^smig_[a-f0-9]{32}$/.test(value.operationId)
173
+ || !['prepared', 'applied', 'rolled-back'].includes(String(value.phase))
174
+ || typeof value.sourceCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.sourceCanonicalHash)
175
+ || typeof value.sourceByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(value.sourceByteDigest)
176
+ || typeof value.targetCanonicalHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.targetCanonicalHash)
177
+ || typeof value.targetByteDigest !== 'string' || !/^[a-f0-9]{64}$/.test(value.targetByteDigest)
178
+ || !Number.isSafeInteger(value.migratedEpicCount) || (value.migratedEpicCount ?? -1) < 0
179
+ || !Number.isSafeInteger(value.migratedStoryCount) || (value.migratedStoryCount ?? -1) < 0
180
+ || !Number.isSafeInteger(value.preservedUnknownFieldCount) || (value.preservedUnknownFieldCount ?? -1) < 0
181
+ || typeof value.backupPath !== 'string'
182
+ || value.backupPath !== join('.neocortex', `state.json.migration-backup-${value.operationId}`)) {
183
+ throw new StateMigrationApplyError('state_migration_manifest_corrupt');
184
+ }
185
+ return value;
186
+ }
187
+ function writeManifest(root, manifest) {
188
+ atomicReplaceUtf8(join(root, MANIFEST_RELATIVE_PATH), `${JSON.stringify(manifest, null, 2)}\n`);
189
+ }
190
+ function receipt(outcome, operationId, sourceBytesHash, targetBytesHash, sourceCanonicalHash, targetCanonicalHash, backupHash, rollbackStatus, migratedEpicCount, migratedStoryCount, preservedUnknownFieldCount, reasonCodes) {
191
+ const value = {
192
+ schemaVersion: STATE_MIGRATION_RECEIPT_SCHEMA,
193
+ operationId,
194
+ outcome,
195
+ sourceBytesHash,
196
+ targetBytesHash,
197
+ sourceCanonicalHash,
198
+ targetCanonicalHash,
199
+ backupHash,
200
+ rollbackStatus,
201
+ migratedEpicCount,
202
+ migratedStoryCount,
203
+ preservedUnknownFieldCount,
204
+ reasonCodes,
205
+ publicSafe: true,
206
+ };
207
+ assertStateMigrationReceiptV1(value);
208
+ return value;
209
+ }
210
+ export function previewStateMigration(projectRoot) {
211
+ const root = safeRoot(projectRoot);
212
+ let decision;
213
+ try {
214
+ decision = planStateMigration(readBoundedState(root).state);
215
+ }
216
+ catch (error) {
217
+ if (error instanceof StateMigrationHardStopError)
218
+ throw new StateMigrationApplyError(error.reasonCode, error.message);
219
+ throw error;
220
+ }
221
+ return decision.kind === 'migrate' ? decision.plan : null;
222
+ }
223
+ /** Apply one shared plan under a client-owned lock, byte CAS and durable backup. */
224
+ export function applyStateMigration(projectRoot, expectedPlan, hooks = {}) {
225
+ const root = safeRoot(projectRoot);
226
+ const release = claimLock(root);
227
+ try {
228
+ const statePath = join(root, STATE_RELATIVE_PATH);
229
+ try {
230
+ recoverAtomicReplaceUtf8(statePath);
231
+ }
232
+ catch {
233
+ throw new StateMigrationApplyError('state_migration_atomic_recovery_failed');
234
+ }
235
+ if (!existsSync(statePath))
236
+ throw new StateMigrationApplyError('state_migration_state_missing');
237
+ const initialRaw = readBoundedState(root).raw;
238
+ if (expectedPlan?.sourceByteDigest && sha256Bytes(initialRaw) !== expectedPlan.sourceByteDigest) {
239
+ throw new StateMigrationApplyError('state_migration_expected_bytes_conflict');
240
+ }
241
+ let decision;
242
+ try {
243
+ decision = planStateMigration(parseState(initialRaw));
244
+ }
245
+ catch (error) {
246
+ if (error instanceof StateMigrationHardStopError)
247
+ throw new StateMigrationApplyError(error.reasonCode, error.message);
248
+ throw error;
249
+ }
250
+ const existing = parseManifest(root);
251
+ const currentBytesHash = sha256Bytes(initialRaw);
252
+ if (decision.kind === 'unchanged') {
253
+ if (expectedPlan && decision.sourceCanonicalHash !== expectedPlan.targetCanonicalHash) {
254
+ throw new StateMigrationApplyError('state_migration_expected_plan_conflict');
255
+ }
256
+ if (existing && existing.targetCanonicalHash === decision.sourceCanonicalHash) {
257
+ if (existing.targetByteDigest !== currentBytesHash) {
258
+ throw new StateMigrationApplyError('state_migration_state_drift');
259
+ }
260
+ if (existing.phase === 'prepared')
261
+ writeManifest(root, { ...existing, phase: 'applied' });
262
+ if (existing.phase === 'rolled-back')
263
+ throw new StateMigrationApplyError('state_migration_state_drift');
264
+ return receipt('already-applied', existing.operationId, existing.sourceByteDigest, existing.targetByteDigest, existing.sourceCanonicalHash, existing.targetCanonicalHash, existing.sourceByteDigest, 'not-required', existing.migratedEpicCount, existing.migratedStoryCount, existing.preservedUnknownFieldCount, ['migration_replay_verified']);
265
+ }
266
+ if (existing)
267
+ throw new StateMigrationApplyError('state_migration_state_drift');
268
+ return receipt('already-applied', expectedPlan?.operationId ?? 'smig_00000000000000000000000000000000', currentBytesHash, currentBytesHash, decision.sourceCanonicalHash, decision.sourceCanonicalHash, null, 'not-required', 0, 0, 0, ['canonical_state_unchanged']);
269
+ }
270
+ const plan = decision.plan;
271
+ assertStateMigrationPlanV1(plan);
272
+ if (expectedPlan && (expectedPlan.operationId !== plan.operationId
273
+ || expectedPlan.sourceCanonicalHash !== plan.sourceCanonicalHash
274
+ || expectedPlan.targetCanonicalHash !== plan.targetCanonicalHash)) {
275
+ throw new StateMigrationApplyError('state_migration_expected_plan_conflict');
276
+ }
277
+ if (existing && existing.operationId !== plan.operationId) {
278
+ throw new StateMigrationApplyError('state_migration_operation_conflict');
279
+ }
280
+ const sourceByteDigest = currentBytesHash;
281
+ const targetRaw = stateRaw(plan.targetState);
282
+ const targetByteDigest = sha256Bytes(targetRaw);
283
+ const backupPath = join('.neocortex', `state.json.migration-backup-${plan.operationId}`);
284
+ const backupAbsolute = join(root, backupPath);
285
+ if (existsSync(backupAbsolute)) {
286
+ const backupStat = lstatSync(backupAbsolute);
287
+ if (backupStat.isSymbolicLink() || !backupStat.isFile() || sha256Bytes(readFileSync(backupAbsolute)) !== sourceByteDigest) {
288
+ throw new StateMigrationApplyError('state_migration_backup_conflict');
289
+ }
290
+ }
291
+ else {
292
+ durableCreateUtf8(backupAbsolute, initialRaw);
293
+ }
294
+ const manifest = {
295
+ schemaVersion: 1,
296
+ operationId: plan.operationId,
297
+ phase: 'prepared',
298
+ sourceCanonicalHash: plan.sourceCanonicalHash,
299
+ sourceByteDigest,
300
+ targetCanonicalHash: plan.targetCanonicalHash,
301
+ targetByteDigest,
302
+ migratedEpicCount: plan.migratedEpicIds.length,
303
+ migratedStoryCount: plan.migratedStoryIds.length,
304
+ preservedUnknownFieldCount: plan.preservedUnknownFieldCount,
305
+ backupPath,
306
+ };
307
+ writeManifest(root, manifest);
308
+ hooks.afterPrepared?.(statePath);
309
+ if (sha256Bytes(readFileSync(statePath)) !== sourceByteDigest) {
310
+ throw new StateMigrationApplyError('state_migration_source_cas_conflict');
311
+ }
312
+ try {
313
+ atomicReplaceUtf8(statePath, targetRaw);
314
+ hooks.afterReplace?.(statePath);
315
+ const installedRaw = readFileSync(statePath, 'utf8');
316
+ const installed = parseState(installedRaw);
317
+ if (sha256Bytes(installedRaw) !== targetByteDigest || stateMigrationDigest(installed) !== plan.targetCanonicalHash) {
318
+ throw new Error('readback-digest-mismatch');
319
+ }
320
+ writeManifest(root, { ...manifest, phase: 'applied' });
321
+ }
322
+ catch (error) {
323
+ try {
324
+ const backupRaw = readFileSync(backupAbsolute, 'utf8');
325
+ if (sha256Bytes(backupRaw) !== sourceByteDigest)
326
+ throw new Error('rollback-backup-digest-mismatch');
327
+ atomicReplaceUtf8(statePath, backupRaw);
328
+ if (sha256Bytes(readFileSync(statePath)) !== sourceByteDigest)
329
+ throw new Error('rollback-digest-mismatch');
330
+ writeManifest(root, { ...manifest, phase: 'rolled-back' });
331
+ }
332
+ catch {
333
+ const unverified = receipt('blocked', plan.operationId, sourceByteDigest, targetByteDigest, plan.sourceCanonicalHash, plan.targetCanonicalHash, sourceByteDigest, 'unverified', plan.migratedEpicIds.length, plan.migratedStoryIds.length, plan.preservedUnknownFieldCount, ['apply_failed', 'rollback_unverified']);
334
+ throw new StateMigrationApplyError('state_migration_rollback_failed', String(error), unverified);
335
+ }
336
+ const rolledBack = receipt('blocked', plan.operationId, sourceByteDigest, targetByteDigest, plan.sourceCanonicalHash, plan.targetCanonicalHash, sourceByteDigest, 'restored', plan.migratedEpicIds.length, plan.migratedStoryIds.length, plan.preservedUnknownFieldCount, ['apply_failed', 'rollback_verified']);
337
+ throw new StateMigrationApplyError('state_migration_apply_rolled_back', String(error), rolledBack);
338
+ }
339
+ return receipt('applied', plan.operationId, sourceByteDigest, targetByteDigest, plan.sourceCanonicalHash, plan.targetCanonicalHash, sourceByteDigest, 'not-required', plan.migratedEpicIds.length, plan.migratedStoryIds.length, plan.preservedUnknownFieldCount, ['lock_acquired', 'source_cas_verified', 'backup_verified', 'atomic_replace_verified']);
340
+ }
341
+ finally {
342
+ release();
343
+ }
344
+ }
@@ -1,2 +1,184 @@
1
- import{readFile as u}from"node:fs/promises";import{join as d}from"node:path";const p=".neocortex/architecture-policy.json",f=Object.freeze(["interactive","yoloop_friendly","fully_automated"]),y=Object.freeze(["aws","gcp","oci","azure","any"]),_=Object.freeze(["REST","GraphQL","tRPC"]),g=Object.freeze(["sync","async","hybrid"]),m=Object.freeze(["mobile-first","desktop-first","responsive"]),O=Object.freeze(["conservative","balanced","aggressive"]),b=Object.freeze(["TDD","test-after","BDD"]),h=new Set(["primary_persona","cloud_provider","api_style","integration_style","ui_priority","refactor_aggressiveness","test_workflow"]);function v(n){const r=[],o=[];if(typeof n!="object"||n===null||Array.isArray(n))return{valid:!1,errors:Object.freeze(["Policy must be a plain object"]),warnings:Object.freeze([])};const t=n;if(t.schema_version!==1&&r.push(`schema_version must be 1, got ${JSON.stringify(t.schema_version)}`),(typeof t.mode!="string"||!f.includes(t.mode))&&r.push(`mode must be one of [${f.join(", ")}], got ${JSON.stringify(t.mode)}`),t.defaults!==void 0&&t.defaults!==null)if(typeof t.defaults!="object"||Array.isArray(t.defaults))r.push("defaults must be an object");else{const e=t.defaults;for(const c of Object.keys(e))h.has(c)||o.push(`defaults.${c}: unknown field (ignored)`);e.primary_persona!==void 0&&e.primary_persona!==null&&typeof e.primary_persona!="string"&&r.push("defaults.primary_persona must be string or null"),i(e,"cloud_provider",y,r),i(e,"api_style",_,r),i(e,"integration_style",g,r),i(e,"ui_priority",m,r),i(e,"refactor_aggressiveness",O,r),i(e,"test_workflow",b,r)}return t.preserved_interactions!==void 0&&t.preserved_interactions!==null&&(!Array.isArray(t.preserved_interactions)||!t.preserved_interactions.every(e=>typeof e=="string"))&&r.push("preserved_interactions must be array of strings"),{valid:r.length===0,errors:Object.freeze(r),warnings:Object.freeze(o)}}async function A(n){const r=d(n,p);let o;try{o=await u(r,"utf8")}catch(s){if(s.code==="ENOENT")return;const l=s.message??String(s);console.warn(`[Neocortex] architecture-policy read failed (${r}): ${l}`);return}const t=o.replace(/^/,"").replace(/\r\n/g,`
2
- `);let e;try{e=JSON.parse(t)}catch(s){const a=s.message??String(s);console.warn(`[Neocortex] architecture-policy malformed JSON (${r}): ${a}. Proceeding without policy.`);return}const c=v(e);if(!c.valid){console.warn(`[Neocortex] architecture-policy schema invalid (${r}): ${c.errors.join("; ")}. Proceeding without policy.`);return}return e}function i(n,r,o,t){const e=n[r];e!=null&&(typeof e!="string"||!o.includes(e))&&t.push(`defaults.${r} must be one of [${o.join(", ")}] or null, got ${JSON.stringify(e)}`)}export{p as POLICY_FILE_PATH,A as readArchitecturePolicy,v as validatePolicy};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * This file is part of Neocortex CLI, licensed under the
6
+ * Functional Source License, Version 1.1 (FSL-1.1).
7
+ *
8
+ * Change Date: February 20, 2029
9
+ * Change License: MIT
10
+ *
11
+ * See the LICENSE file in the project root for full license text.
12
+ */
13
+ /**
14
+ * Epic P107.02: Client-side Policy Reader
15
+ *
16
+ * Reads `.neocortex/architecture-policy.json` from consumer project root,
17
+ * validates structure against P107.01 wire-format types, and exposes to
18
+ * `collectStateSnapshot` hook so the server receives it via request body.
19
+ *
20
+ * Fail-soft by design -- NEVER throws. File absent / malformed / invalid
21
+ * schema all return `undefined` (warning to stderr when non-trivial).
22
+ *
23
+ * Pattern reference:
24
+ * - P101.06/07 (client-side file reader + hook pattern)
25
+ * - P63.01 (UTF-8 BOM defense)
26
+ * - P103.06 (CRLF normalization)
27
+ */
28
+ import { readFile } from 'node:fs/promises';
29
+ import { join } from 'node:path';
30
+ /**
31
+ * Relative path from project root to consumer policy file.
32
+ * Consumer copies `architecture-policy.template.json` (from repo root) to
33
+ * this path and edits.
34
+ */
35
+ export const POLICY_FILE_PATH = '.neocortex/architecture-policy.json';
36
+ // Frozen canonical enum sets mirroring JSON Schema (core/data/architecture-policy-schema.json).
37
+ // Kept in sync with SSoT types in @neocortex/shared/types/architecture-policy.ts.
38
+ const VALID_MODES = Object.freeze([
39
+ 'interactive',
40
+ 'yoloop_friendly',
41
+ 'fully_automated',
42
+ ]);
43
+ const VALID_CLOUD_PROVIDERS = Object.freeze(['aws', 'gcp', 'oci', 'azure', 'any']);
44
+ const VALID_API_STYLES = Object.freeze(['REST', 'GraphQL', 'tRPC']);
45
+ const VALID_INTEGRATION_STYLES = Object.freeze(['sync', 'async', 'hybrid']);
46
+ const VALID_UI_PRIORITIES = Object.freeze(['mobile-first', 'desktop-first', 'responsive']);
47
+ const VALID_REFACTOR_AGGRESSIVENESS = Object.freeze(['conservative', 'balanced', 'aggressive']);
48
+ const VALID_TEST_WORKFLOWS = Object.freeze(['TDD', 'test-after', 'BDD']);
49
+ /** Known optional default field names per ArchitectureDefaults interface. */
50
+ const KNOWN_DEFAULT_FIELDS = new Set([
51
+ 'primary_persona',
52
+ 'cloud_provider',
53
+ 'api_style',
54
+ 'integration_style',
55
+ 'ui_priority',
56
+ 'refactor_aggressiveness',
57
+ 'test_workflow',
58
+ ]);
59
+ /**
60
+ * Pure function validator. Zero I/O. Deterministic.
61
+ *
62
+ * Returns `ArchitecturePolicyValidationResult` with:
63
+ * - `valid: true` iff all required fields correct and no hard errors
64
+ * - `errors`: hard failures (schema version mismatch, bad mode, type errors)
65
+ * - `warnings`: soft issues (unknown optional fields -- forward-compat)
66
+ */
67
+ export function validatePolicy(candidate) {
68
+ const errors = [];
69
+ const warnings = [];
70
+ if (typeof candidate !== 'object' || candidate === null || Array.isArray(candidate)) {
71
+ return {
72
+ valid: false,
73
+ errors: Object.freeze(['Policy must be a plain object']),
74
+ warnings: Object.freeze([]),
75
+ };
76
+ }
77
+ const c = candidate;
78
+ // schema_version: must be literal 1
79
+ if (c.schema_version !== 1) {
80
+ errors.push(`schema_version must be 1, got ${JSON.stringify(c.schema_version)}`);
81
+ }
82
+ // mode: must be one of 3 valid values
83
+ if (typeof c.mode !== 'string' || !VALID_MODES.includes(c.mode)) {
84
+ errors.push(`mode must be one of [${VALID_MODES.join(', ')}], got ${JSON.stringify(c.mode)}`);
85
+ }
86
+ // defaults: optional object, each field must match its enum (or null/undefined)
87
+ if (c.defaults !== undefined && c.defaults !== null) {
88
+ if (typeof c.defaults !== 'object' || Array.isArray(c.defaults)) {
89
+ errors.push('defaults must be an object');
90
+ }
91
+ else {
92
+ const defaults = c.defaults;
93
+ // Unknown-field warnings (forward-compat: future versions may add fields)
94
+ for (const key of Object.keys(defaults)) {
95
+ if (!KNOWN_DEFAULT_FIELDS.has(key)) {
96
+ warnings.push(`defaults.${key}: unknown field (ignored)`);
97
+ }
98
+ }
99
+ // Per-field value validation (null is allowed -- means "unset", asks human)
100
+ if (defaults.primary_persona !== undefined &&
101
+ defaults.primary_persona !== null &&
102
+ typeof defaults.primary_persona !== 'string') {
103
+ errors.push(`defaults.primary_persona must be string or null`);
104
+ }
105
+ validateEnumField(defaults, 'cloud_provider', VALID_CLOUD_PROVIDERS, errors);
106
+ validateEnumField(defaults, 'api_style', VALID_API_STYLES, errors);
107
+ validateEnumField(defaults, 'integration_style', VALID_INTEGRATION_STYLES, errors);
108
+ validateEnumField(defaults, 'ui_priority', VALID_UI_PRIORITIES, errors);
109
+ validateEnumField(defaults, 'refactor_aggressiveness', VALID_REFACTOR_AGGRESSIVENESS, errors);
110
+ validateEnumField(defaults, 'test_workflow', VALID_TEST_WORKFLOWS, errors);
111
+ }
112
+ }
113
+ // preserved_interactions: optional array of strings
114
+ if (c.preserved_interactions !== undefined && c.preserved_interactions !== null) {
115
+ if (!Array.isArray(c.preserved_interactions) ||
116
+ !c.preserved_interactions.every((s) => typeof s === 'string')) {
117
+ errors.push('preserved_interactions must be array of strings');
118
+ }
119
+ }
120
+ return {
121
+ valid: errors.length === 0,
122
+ errors: Object.freeze(errors),
123
+ warnings: Object.freeze(warnings),
124
+ };
125
+ }
126
+ /**
127
+ * Async reader. NEVER throws.
128
+ *
129
+ * Returns `undefined` when:
130
+ * - file does not exist (ENOENT; silent, expected default)
131
+ * - permission denied (EACCES; warns stderr)
132
+ * - malformed JSON (warns stderr with path)
133
+ * - schema invalid (warns stderr with error list)
134
+ *
135
+ * Returns typed `ArchitecturePolicy` on full success.
136
+ */
137
+ export async function readArchitecturePolicy(projectRoot) {
138
+ const absPath = join(projectRoot, POLICY_FILE_PATH);
139
+ let raw;
140
+ try {
141
+ raw = await readFile(absPath, 'utf8');
142
+ }
143
+ catch (err) {
144
+ const code = err.code;
145
+ if (code === 'ENOENT') {
146
+ // Silent: file absent is the expected default.
147
+ return undefined;
148
+ }
149
+ const msg = err.message ?? String(err);
150
+ // Defensive warn -- operational issue (permission, etc).
151
+ // eslint-disable-next-line no-console
152
+ console.warn(`[Neocortex] architecture-policy read failed (${absPath}): ${msg}`);
153
+ return undefined;
154
+ }
155
+ // Encoding normalization (P63 BOM + P103 CRLF patterns).
156
+ // eslint-disable-next-line no-misleading-character-class
157
+ const normalized = raw.replace(/^/, '').replace(/\r\n/g, '\n');
158
+ let parsed;
159
+ try {
160
+ parsed = JSON.parse(normalized);
161
+ }
162
+ catch (err) {
163
+ const msg = err.message ?? String(err);
164
+ // eslint-disable-next-line no-console
165
+ console.warn(`[Neocortex] architecture-policy malformed JSON (${absPath}): ${msg}. Proceeding without policy.`);
166
+ return undefined;
167
+ }
168
+ const result = validatePolicy(parsed);
169
+ if (!result.valid) {
170
+ // eslint-disable-next-line no-console
171
+ console.warn(`[Neocortex] architecture-policy schema invalid (${absPath}): ${result.errors.join('; ')}. Proceeding without policy.`);
172
+ return undefined;
173
+ }
174
+ return parsed;
175
+ }
176
+ // ── Internal helpers ──────────────────────────────────────────────────────
177
+ function validateEnumField(defaults, field, validValues, errors) {
178
+ const val = defaults[field];
179
+ if (val === undefined || val === null)
180
+ return; // unset is OK
181
+ if (typeof val !== 'string' || !validValues.includes(val)) {
182
+ errors.push(`defaults.${field} must be one of [${validValues.join(', ')}] or null, got ${JSON.stringify(val)}`);
183
+ }
184
+ }
@@ -1 +1,7 @@
1
- import{readArchitecturePolicy as c,validatePolicy as i,POLICY_FILE_PATH as o}from"./architecture-policy.js";export{o as POLICY_FILE_PATH,c as readArchitecturePolicy,i as validatePolicy};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * Barrel export for Epic P107.02 policy reader module.
6
+ */
7
+ export { readArchitecturePolicy, validatePolicy, POLICY_FILE_PATH, } from './architecture-policy.js';
@@ -0,0 +1,38 @@
1
+ /**
2
+ * P119.02: Inlined byte-identical types from
3
+ * `@neocortex/shared/types/architecture-policy`.
4
+ *
5
+ * SSoT-Shadow pattern (P92.01 server precedent extended by P117.01 to client
6
+ * checkpoint dist + P117.07 to client yoloop dist). Client tarball is published
7
+ * standalone via `@ornexus/neocortex` and does NOT include `@neocortex/shared`
8
+ * as a runtime dependency (workspace package, excluded from tarball per
9
+ * `.npmignore` + `tsconfig.build.json`). Any non-erased import of
10
+ * `@neocortex/shared` in `packages/client/dist/**` causes runtime
11
+ * `ERR_MODULE_NOT_FOUND` on globally installed `@ornexus/neocortex`.
12
+ *
13
+ * Pre-P119.02, three files leaked `import type` statements from
14
+ * `@neocortex/shared` in the published v4.19.1 tarball:
15
+ * - dist/policy/architecture-policy.d.ts
16
+ * - dist/policy/index.d.ts
17
+ * - dist/commands/invoke.d.ts (imported `YoloopPersistedState`)
18
+ *
19
+ * Type-only `import type` is erased at runtime (no module resolution attempt),
20
+ * but produces TS2307 in consumer projects that try to use the types via
21
+ * globally-installed CLI (`npm install -g @ornexus/neocortex`).
22
+ *
23
+ * Sync responsibility: `policy-shared-sync.test.ts` (client-side drift test,
24
+ * mirror of `checkpoint-shared-sync.test.ts` P117.01). Drift test fails CI
25
+ * if these diverge from SSoT canonical at
26
+ * `packages/shared/src/types/architecture-policy.ts`.
27
+ *
28
+ * Defense-in-depth: `validate-pre-publish.js` ships
29
+ * `validateClientNoSharedImport()` (P117.01) scanning client dist for
30
+ * `@neocortex/shared` runtime references. P119.02 expands its scope to also
31
+ * walk `dist/policy/` and `dist/commands/` (in addition to checkpoint + yoloop
32
+ * coverage from P117).
33
+ *
34
+ * DO NOT EDIT WITHOUT also editing
35
+ * `packages/shared/src/types/architecture-policy.ts`.
36
+ */
37
+ export {};
38
+ // === END P119.02 ===