@ornexus/neocortex 4.60.78 → 4.60.79

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 (241) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1206
  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 +214 -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 +443 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +260 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +338 -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 +7712 -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 +159 -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/host-auth-broker.js +60 -1
  76. package/packages/client/dist/config/host-auth-reference.js +93 -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 +105 -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 +2612 -81
  98. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  99. package/packages/client/dist/errors/error-messages.js +258 -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 +1341 -4
  109. package/packages/client/dist/git/epic-operational-state.js +672 -2
  110. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  111. package/packages/client/dist/git/git-lifecycle-store.js +2185 -10
  112. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  113. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  114. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  115. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  116. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  117. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  118. package/packages/client/dist/i18n/first-run.js +60 -2
  119. package/packages/client/dist/index.js +50 -1
  120. package/packages/client/dist/invocation/invoke-input.js +24 -1
  121. package/packages/client/dist/license/host-auth-recovery.js +401 -1
  122. package/packages/client/dist/license/index.js +5 -1
  123. package/packages/client/dist/license/license-client.js +337 -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 +1067 -41
  128. package/packages/client/dist/memory/shared-project-memory-types.js +259 -2
  129. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -3
  130. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  131. package/packages/client/dist/migrations/project-identity.js +493 -7
  132. package/packages/client/dist/migrations/state-json.js +393 -4
  133. package/packages/client/dist/policy/architecture-policy.js +184 -2
  134. package/packages/client/dist/policy/index.js +7 -1
  135. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  136. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  137. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  138. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  139. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  140. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  141. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  142. package/packages/client/dist/private-execution/delivery.js +410 -13
  143. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  144. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  145. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  146. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  147. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  148. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  149. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  150. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  151. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  152. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  153. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  154. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  155. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  156. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  157. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  158. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  159. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  160. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  161. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  162. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  163. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  164. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  165. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  166. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  167. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  168. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  169. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  170. package/packages/client/dist/private-execution/session-lease.js +63 -1
  171. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  172. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  173. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  174. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  175. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  176. package/packages/client/dist/registry/registry-reconciliation.js +234 -1
  177. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  178. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  179. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  180. package/packages/client/dist/resilience/index.js +8 -1
  181. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  182. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  183. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  184. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  185. package/packages/client/dist/runner/binary.js +404 -1
  186. package/packages/client/dist/runner/cli.js +1571 -17
  187. package/packages/client/dist/runner/epic-background-dispatcher.js +124 -1
  188. package/packages/client/dist/runner/headless/adapters.js +49 -1
  189. package/packages/client/dist/runner/headless/background-root.js +85 -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 +111 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1464 -10
  195. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +357 -2
  196. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  197. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +274 -1
  198. package/packages/client/dist/runner/headless/managed-profile.js +149 -1
  199. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  200. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  201. package/packages/client/dist/runner/headless/resolver.js +231 -1
  202. package/packages/client/dist/runner/headless/run-yolo.js +886 -1
  203. package/packages/client/dist/runner/headless/run-yoloop.js +2582 -2
  204. package/packages/client/dist/runner/headless/types.js +575 -2
  205. package/packages/client/dist/runner/host-capacity.js +59 -1
  206. package/packages/client/dist/runner/local-console.js +396 -13
  207. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  208. package/packages/client/dist/runner/project-identity.js +106 -1
  209. package/packages/client/dist/runner/scheduler.js +995 -7
  210. package/packages/client/dist/runner-cli.js +18 -2
  211. package/packages/client/dist/state/invocation-shape.js +13 -1
  212. package/packages/client/dist/state/project-state-snapshot.js +1751 -1
  213. package/packages/client/dist/state/state-json-repair.js +785 -3
  214. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  215. package/packages/client/dist/telemetry/index.js +5 -1
  216. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  217. package/packages/client/dist/tier/index.js +5 -1
  218. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  219. package/packages/client/dist/types/index.js +38 -1
  220. package/packages/client/dist/version.js +27 -1
  221. package/packages/client/dist/yolo/change-evidence-collector.js +222 -1
  222. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  223. package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
  224. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  225. package/packages/client/dist/yoloop/index.js +8 -1
  226. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  227. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -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.js +1920 -1
  231. package/targets-stubs/antigravity/gemini.md +1 -1
  232. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  233. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  234. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  235. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex.md +2 -2
  237. package/targets-stubs/codex/AGENTS.md +1 -1
  238. package/targets-stubs/cursor/agent.md +2 -2
  239. package/targets-stubs/gemini-cli/agent.md +2 -2
  240. package/targets-stubs/opencode/neocortex-root.md +1 -1
  241. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1 +1,338 @@
1
- import{mkdir as I,writeFile as L,readFile as c,rm as m,readdir as N,open as v,rename as b,lstat as E}from"node:fs/promises";import{basename as R,join as D}from"node:path";import{createHash as l,randomUUID as F}from"node:crypto";import{hostname as O}from"node:os";import{encrypt as S,decrypt as g}from"./crypto-utils.js";import{setSecureFilePermissions as T}from"../config/secure-config.js";import{hasProtectedCachePayloadMarker as H}from"./protected-pi-boundary.js";const $=".enc";class z{cacheDir;passphrase;strictReadOnly;authoritativeFaultInjector;authoritativeNow;authoritativeOwnerAlive;initPromise=null;constructor(t){this.cacheDir=t.cacheDir,this.passphrase=t.passphrase,this.strictReadOnly=t.strictReadOnly??!1,this.authoritativeFaultInjector=t.authoritativeFaultInjector,this.authoritativeNow=t.authoritativeNow??Date.now,this.authoritativeOwnerAlive=t.authoritativeOwnerAlive??q}async get(t){try{const r=this.keyToPath(t),a=await c(r,"utf8"),i=g(a,this.passphrase);return i.expired?(this.strictReadOnly||await m(r,{force:!0}).catch(()=>{}),null):i.plaintext}catch{return null}}async set(t,r,a){if(!this.strictReadOnly)try{if(H(r))return;await this.ensureDir();const i=this.keyToPath(t),e=S(r,this.passphrase,a);await L(i,e,"utf8"),T(i)}catch{}}async getAuthoritative(t){const r=this.keyToPath(t);try{const a=await E(r);if(!a.isFile()||a.isSymbolicLink())throw new Error("auth-generation-path-unsafe");const i=await c(r,"utf8"),e=g(i,this.passphrase);if(e.expired)throw new Error("auth-generation-corrupt");return e.plaintext}catch(a){if(a?.code==="ENOENT")return null;throw C(a)?a:new Error("auth-generation-unavailable",{cause:a})}}async setAuthoritative(t,r,a={}){if(this.strictReadOnly)throw new Error("auth-generation-unavailable");if(Buffer.byteLength(r,"utf8")>256*1024)throw new Error("auth-generation-capacity");await this.ensureDir();const i=await E(this.cacheDir);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("auth-generation-path-unsafe");const e=this.keyToPath(t),h=`${e}.lock`,u=`${e}.${process.pid}.${F()}.tmp`,f=F();let n,s;try{n=await this.acquireAuthoritativeLock(h,f,l("sha256").update(t).digest("hex"));const x=this.authoritativeNow();if(await n.writeFile(JSON.stringify({schemaVersion:1,ownerPid:process.pid,ownerHost:O(),nonce:f,keyDigest:l("sha256").update(t).digest("hex"),createdAt:new Date(x).toISOString(),expiresAt:new Date(x+6e4).toISOString()})),await n.sync(),await this.injectAuthoritativeFault("lock-synced"),(await N(this.cacheDir)).filter(o=>o.startsWith(`${R(e)}.`)&&o.endsWith(".tmp")).length>0)throw new Error("auth-generation-path-unsafe");try{const o=await E(e);if(!o.isFile()||o.isSymbolicLink())throw new Error("auth-generation-path-unsafe")}catch(o){if(o?.code!=="ENOENT")throw o}const d=await this.readAuthoritativePreimage(e),y=d===null?null:l("sha256").update(d.plaintext).digest("hex");if(a.expectedPlaintextSha256!==void 0&&y!==a.expectedPlaintextSha256)throw new Error("auth-generation-revision-conflict");const j=S(r,this.passphrase);if(s=await v(u,"wx",384),await s.writeFile(j,"utf8"),await s.sync(),await this.injectAuthoritativeFault("temp-synced"),await s.close(),s=void 0,d!==null&&y!==null){const o=`${e}.${y}.bak`;try{const w=await v(o,"wx",384);try{await w.writeFile(d.raw,"utf8"),await w.sync()}finally{await w.close()}}catch(w){if(w?.code!=="EEXIST")throw w;if(await c(o,"utf8")!==d.raw)throw new Error("auth-generation-path-unsafe")}await this.injectAuthoritativeFault("backup-synced")}const k=await this.readAuthoritativePreimage(e);if((k===null?null:l("sha256").update(k.plaintext).digest("hex"))!==y)throw new Error("auth-generation-revision-conflict");await b(u,e),await this.injectAuthoritativeFault("renamed"),T(e);const A=await v(this.cacheDir,"r");try{await A.sync()}finally{await A.close()}await this.injectAuthoritativeFault("directory-synced");const P=g(await c(e,"utf8"),this.passphrase);if(P.expired||P.plaintext!==r)throw new Error("auth-generation-corrupt");await this.injectAuthoritativeFault("readback-verified")}finally{if(s&&await s.close().catch(()=>{}),await m(u,{force:!0}).catch(()=>{}),n){await n.close().catch(()=>{});try{JSON.parse(await c(h,"utf8")).nonce===f&&await m(h,{force:!0})}catch{}}}}async clear(){if(!this.strictReadOnly)try{const r=(await N(this.cacheDir).catch(()=>[])).filter(a=>a.endsWith($)).map(a=>m(D(this.cacheDir,a),{force:!0}).catch(()=>{}));await Promise.all(r)}catch{}}keyToPath(t){const r=l("sha256").update(t).digest("hex");return D(this.cacheDir,`${r}${$}`)}ensureDir(){return this.initPromise||(this.initPromise=I(this.cacheDir,{recursive:!0}).then(()=>{}).catch(t=>{throw this.initPromise=null,t})),this.initPromise}async acquireAuthoritativeLock(t,r,a){for(let i=0;i<2;i+=1)try{return await v(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;if(i>0)throw new Error("auth-recovery-backpressure");await this.quarantineExpiredAuthoritativeLock(t,r,a)}throw new Error("auth-recovery-backpressure")}async quarantineExpiredAuthoritativeLock(t,r,a){let i;try{i=await c(t,"utf8")}catch(n){if(n?.code==="ENOENT")return;throw new Error("auth-recovery-backpressure",{cause:n})}let e;try{e=JSON.parse(i)}catch(n){throw new Error("auth-generation-path-unsafe",{cause:n})}const h=typeof e.expiresAt=="string"?Date.parse(e.expiresAt):Number.NaN,u=e.ownerPid;if(e.schemaVersion!==1||e.keyDigest!==a||!Number.isSafeInteger(u)||typeof e.ownerHost!="string"||typeof e.nonce!="string"||!Number.isFinite(h))throw new Error("auth-generation-path-unsafe");if(h>this.authoritativeNow()||e.ownerHost!==O()||this.authoritativeOwnerAlive(u))throw new Error("auth-recovery-backpressure");const f=`${t}.stale-${l("sha256").update(i).digest("hex").slice(0,16)}-${r}.bak`;try{await b(t,f)}catch(n){if(n?.code==="ENOENT")return;throw new Error("auth-recovery-backpressure",{cause:n})}}async readAuthoritativePreimage(t){try{const r=await E(t);if(!r.isFile()||r.isSymbolicLink())throw new Error("auth-generation-path-unsafe");const a=await c(t,"utf8"),i=g(a,this.passphrase);if(i.expired)throw new Error("auth-generation-corrupt");return{raw:a,plaintext:i.plaintext}}catch(r){if(r?.code==="ENOENT")return null;throw r}}async injectAuthoritativeFault(t){await this.authoritativeFaultInjector?.(t)}}function q(p){try{return process.kill(p,0),!0}catch(t){return t?.code==="EPERM"}}function C(p){return p instanceof Error&&/^auth-generation-(?:corrupt|path-unsafe|capacity|revision-conflict|unavailable)$/.test(p.message)}export{z as EncryptedCache};
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
+ * @neocortex/client - EncryptedCache
15
+ *
16
+ * Filesystem-backed encrypted cache implementing the CacheProvider interface.
17
+ * Stores assets as AES-256-GCM encrypted files with PBKDF2 key derivation.
18
+ * Cache keys are hashed with SHA-256 to produce safe filenames.
19
+ *
20
+ * PI boundary (P176.05): values may contain public metadata, hashes, counts,
21
+ * sizes, or bounded encrypted data only. Synthetic protected prompt/workflow/
22
+ * step-body markers and explicit protected JSON field names are rejected before
23
+ * disk write. Default TTL is caller-owned and remains [TBD].
24
+ *
25
+ * All public methods are designed to never throw - cache failures are
26
+ * silently handled since caching is a non-critical optimization.
27
+ */
28
+ import { mkdir, writeFile, readFile, rm, readdir, open, rename, lstat } from 'node:fs/promises';
29
+ import { basename, join } from 'node:path';
30
+ import { createHash, randomUUID } from 'node:crypto';
31
+ import { hostname } from 'node:os';
32
+ import { encrypt, decrypt } from './crypto-utils.js';
33
+ import { setSecureFilePermissions } from '../config/secure-config.js';
34
+ import { hasProtectedCachePayloadMarker } from './protected-pi-boundary.js';
35
+ // ── Constants ────────────────────────────────────────────────────────────
36
+ const CACHE_FILE_EXTENSION = '.enc';
37
+ // ── EncryptedCache Implementation ────────────────────────────────────────
38
+ export class EncryptedCache {
39
+ cacheDir;
40
+ passphrase;
41
+ strictReadOnly;
42
+ authoritativeFaultInjector;
43
+ authoritativeNow;
44
+ authoritativeOwnerAlive;
45
+ initPromise = null;
46
+ constructor(options) {
47
+ this.cacheDir = options.cacheDir;
48
+ this.passphrase = options.passphrase;
49
+ this.strictReadOnly = options.strictReadOnly ?? false;
50
+ this.authoritativeFaultInjector = options.authoritativeFaultInjector;
51
+ this.authoritativeNow = options.authoritativeNow ?? Date.now;
52
+ this.authoritativeOwnerAlive = options.authoritativeOwnerAlive ?? isProcessAlive;
53
+ }
54
+ async get(key) {
55
+ try {
56
+ const filePath = this.keyToPath(key);
57
+ const raw = await readFile(filePath, 'utf8');
58
+ const result = decrypt(raw, this.passphrase);
59
+ if (result.expired) {
60
+ if (!this.strictReadOnly)
61
+ await rm(filePath, { force: true }).catch(() => { });
62
+ return null;
63
+ }
64
+ return result.plaintext;
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ async set(key, value, ttlMs) {
71
+ if (this.strictReadOnly)
72
+ return;
73
+ try {
74
+ if (hasProtectedCachePayloadMarker(value))
75
+ return;
76
+ await this.ensureDir();
77
+ const filePath = this.keyToPath(key);
78
+ const encrypted = encrypt(value, this.passphrase, ttlMs);
79
+ await writeFile(filePath, encrypted, 'utf8');
80
+ // Story 66.1 AC6: Apply restrictive permissions on .enc files
81
+ setSecureFilePermissions(filePath);
82
+ }
83
+ catch {
84
+ // Cache write failures are non-critical
85
+ }
86
+ }
87
+ /**
88
+ * Required private-state read. Unlike ordinary cache reads, corruption and
89
+ * access failures are explicit and expired content is never cleaned up.
90
+ */
91
+ async getAuthoritative(key) {
92
+ const filePath = this.keyToPath(key);
93
+ try {
94
+ const file = await lstat(filePath);
95
+ if (!file.isFile() || file.isSymbolicLink())
96
+ throw new Error('auth-generation-path-unsafe');
97
+ const raw = await readFile(filePath, 'utf8');
98
+ const result = decrypt(raw, this.passphrase);
99
+ if (result.expired)
100
+ throw new Error('auth-generation-corrupt');
101
+ return result.plaintext;
102
+ }
103
+ catch (error) {
104
+ if (error?.code === 'ENOENT')
105
+ return null;
106
+ if (isAuthGenerationError(error))
107
+ throw error;
108
+ throw new Error('auth-generation-unavailable', { cause: error });
109
+ }
110
+ }
111
+ /**
112
+ * Durable compare-bound replace for private auth generations. This method is
113
+ * intentionally separate from best-effort cache set(): callers must observe
114
+ * every lock, persistence, readback and preimage failure.
115
+ */
116
+ async setAuthoritative(key, value, options = {}) {
117
+ if (this.strictReadOnly)
118
+ throw new Error('auth-generation-unavailable');
119
+ if (Buffer.byteLength(value, 'utf8') > 256 * 1024)
120
+ throw new Error('auth-generation-capacity');
121
+ await this.ensureDir();
122
+ const directory = await lstat(this.cacheDir);
123
+ if (!directory.isDirectory() || directory.isSymbolicLink())
124
+ throw new Error('auth-generation-path-unsafe');
125
+ const filePath = this.keyToPath(key);
126
+ const lockPath = `${filePath}.lock`;
127
+ const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
128
+ const lockNonce = randomUUID();
129
+ let lock;
130
+ let temp;
131
+ try {
132
+ lock = await this.acquireAuthoritativeLock(lockPath, lockNonce, createHash('sha256').update(key).digest('hex'));
133
+ const now = this.authoritativeNow();
134
+ await lock.writeFile(JSON.stringify({
135
+ schemaVersion: 1,
136
+ ownerPid: process.pid,
137
+ ownerHost: hostname(),
138
+ nonce: lockNonce,
139
+ keyDigest: createHash('sha256').update(key).digest('hex'),
140
+ createdAt: new Date(now).toISOString(),
141
+ expiresAt: new Date(now + 60_000).toISOString(),
142
+ }));
143
+ await lock.sync();
144
+ await this.injectAuthoritativeFault('lock-synced');
145
+ const orphanTemps = (await readdir(this.cacheDir))
146
+ .filter((entry) => entry.startsWith(`${basename(filePath)}.`) && entry.endsWith('.tmp'));
147
+ if (orphanTemps.length > 0)
148
+ throw new Error('auth-generation-path-unsafe');
149
+ try {
150
+ const currentType = await lstat(filePath);
151
+ if (!currentType.isFile() || currentType.isSymbolicLink())
152
+ throw new Error('auth-generation-path-unsafe');
153
+ }
154
+ catch (error) {
155
+ if (error?.code !== 'ENOENT')
156
+ throw error;
157
+ }
158
+ const preimage = await this.readAuthoritativePreimage(filePath);
159
+ const actual = preimage === null ? null : createHash('sha256').update(preimage.plaintext).digest('hex');
160
+ if (options.expectedPlaintextSha256 !== undefined && actual !== options.expectedPlaintextSha256) {
161
+ throw new Error('auth-generation-revision-conflict');
162
+ }
163
+ const encrypted = encrypt(value, this.passphrase);
164
+ temp = await open(tempPath, 'wx', 0o600);
165
+ await temp.writeFile(encrypted, 'utf8');
166
+ await temp.sync();
167
+ await this.injectAuthoritativeFault('temp-synced');
168
+ await temp.close();
169
+ temp = undefined;
170
+ if (preimage !== null && actual !== null) {
171
+ const backupPath = `${filePath}.${actual}.bak`;
172
+ try {
173
+ const backup = await open(backupPath, 'wx', 0o600);
174
+ try {
175
+ await backup.writeFile(preimage.raw, 'utf8');
176
+ await backup.sync();
177
+ }
178
+ finally {
179
+ await backup.close();
180
+ }
181
+ }
182
+ catch (error) {
183
+ if (error?.code !== 'EEXIST')
184
+ throw error;
185
+ if (await readFile(backupPath, 'utf8') !== preimage.raw)
186
+ throw new Error('auth-generation-path-unsafe');
187
+ }
188
+ await this.injectAuthoritativeFault('backup-synced');
189
+ }
190
+ const revalidated = await this.readAuthoritativePreimage(filePath);
191
+ const revalidatedDigest = revalidated === null ? null : createHash('sha256').update(revalidated.plaintext).digest('hex');
192
+ if (revalidatedDigest !== actual) {
193
+ throw new Error('auth-generation-revision-conflict');
194
+ }
195
+ await rename(tempPath, filePath);
196
+ await this.injectAuthoritativeFault('renamed');
197
+ setSecureFilePermissions(filePath);
198
+ const dirHandle = await open(this.cacheDir, 'r');
199
+ try {
200
+ await dirHandle.sync();
201
+ }
202
+ finally {
203
+ await dirHandle.close();
204
+ }
205
+ await this.injectAuthoritativeFault('directory-synced');
206
+ const readback = decrypt(await readFile(filePath, 'utf8'), this.passphrase);
207
+ if (readback.expired || readback.plaintext !== value)
208
+ throw new Error('auth-generation-corrupt');
209
+ await this.injectAuthoritativeFault('readback-verified');
210
+ }
211
+ finally {
212
+ if (temp)
213
+ await temp.close().catch(() => undefined);
214
+ await rm(tempPath, { force: true }).catch(() => undefined);
215
+ if (lock) {
216
+ await lock.close().catch(() => undefined);
217
+ try {
218
+ const owner = JSON.parse(await readFile(lockPath, 'utf8'));
219
+ if (owner.nonce === lockNonce)
220
+ await rm(lockPath, { force: true });
221
+ }
222
+ catch { /* never remove a lock whose ownership cannot be proved */ }
223
+ }
224
+ }
225
+ }
226
+ async clear() {
227
+ if (this.strictReadOnly)
228
+ return;
229
+ try {
230
+ const entries = await readdir(this.cacheDir).catch(() => []);
231
+ const removals = entries
232
+ .filter((entry) => entry.endsWith(CACHE_FILE_EXTENSION))
233
+ .map((entry) => rm(join(this.cacheDir, entry), { force: true }).catch(() => { }));
234
+ await Promise.all(removals);
235
+ }
236
+ catch {
237
+ // Clear failures are non-critical
238
+ }
239
+ }
240
+ // ── Private Methods ─────────────────────────────────────────────────
241
+ keyToPath(key) {
242
+ const hash = createHash('sha256').update(key).digest('hex');
243
+ return join(this.cacheDir, `${hash}${CACHE_FILE_EXTENSION}`);
244
+ }
245
+ ensureDir() {
246
+ if (!this.initPromise) {
247
+ this.initPromise = mkdir(this.cacheDir, { recursive: true }).then(() => undefined).catch((err) => {
248
+ this.initPromise = null; // allow retry on next call
249
+ throw err;
250
+ });
251
+ }
252
+ return this.initPromise;
253
+ }
254
+ async acquireAuthoritativeLock(lockPath, nonce, keyDigest) {
255
+ for (let attempt = 0; attempt < 2; attempt += 1) {
256
+ try {
257
+ return await open(lockPath, 'wx', 0o600);
258
+ }
259
+ catch (error) {
260
+ if (error?.code !== 'EEXIST')
261
+ throw error;
262
+ if (attempt > 0)
263
+ throw new Error('auth-recovery-backpressure');
264
+ await this.quarantineExpiredAuthoritativeLock(lockPath, nonce, keyDigest);
265
+ }
266
+ }
267
+ throw new Error('auth-recovery-backpressure');
268
+ }
269
+ async quarantineExpiredAuthoritativeLock(lockPath, nonce, keyDigest) {
270
+ let raw;
271
+ try {
272
+ raw = await readFile(lockPath, 'utf8');
273
+ }
274
+ catch (error) {
275
+ if (error?.code === 'ENOENT')
276
+ return;
277
+ throw new Error('auth-recovery-backpressure', { cause: error });
278
+ }
279
+ let owner;
280
+ try {
281
+ owner = JSON.parse(raw);
282
+ }
283
+ catch (error) {
284
+ throw new Error('auth-generation-path-unsafe', { cause: error });
285
+ }
286
+ const expiresAt = typeof owner.expiresAt === 'string' ? Date.parse(owner.expiresAt) : Number.NaN;
287
+ const ownerPid = owner.ownerPid;
288
+ if (owner.schemaVersion !== 1 || owner.keyDigest !== keyDigest || !Number.isSafeInteger(ownerPid)
289
+ || typeof owner.ownerHost !== 'string' || typeof owner.nonce !== 'string' || !Number.isFinite(expiresAt)) {
290
+ throw new Error('auth-generation-path-unsafe');
291
+ }
292
+ if (expiresAt > this.authoritativeNow() || owner.ownerHost !== hostname()
293
+ || this.authoritativeOwnerAlive(ownerPid)) {
294
+ throw new Error('auth-recovery-backpressure');
295
+ }
296
+ const quarantine = `${lockPath}.stale-${createHash('sha256').update(raw).digest('hex').slice(0, 16)}-${nonce}.bak`;
297
+ try {
298
+ await rename(lockPath, quarantine);
299
+ }
300
+ catch (error) {
301
+ if (error?.code === 'ENOENT')
302
+ return;
303
+ throw new Error('auth-recovery-backpressure', { cause: error });
304
+ }
305
+ }
306
+ async readAuthoritativePreimage(filePath) {
307
+ try {
308
+ const file = await lstat(filePath);
309
+ if (!file.isFile() || file.isSymbolicLink())
310
+ throw new Error('auth-generation-path-unsafe');
311
+ const raw = await readFile(filePath, 'utf8');
312
+ const decrypted = decrypt(raw, this.passphrase);
313
+ if (decrypted.expired)
314
+ throw new Error('auth-generation-corrupt');
315
+ return { raw, plaintext: decrypted.plaintext };
316
+ }
317
+ catch (error) {
318
+ if (error?.code === 'ENOENT')
319
+ return null;
320
+ throw error;
321
+ }
322
+ }
323
+ async injectAuthoritativeFault(phase) {
324
+ await this.authoritativeFaultInjector?.(phase);
325
+ }
326
+ }
327
+ function isProcessAlive(pid) {
328
+ try {
329
+ process.kill(pid, 0);
330
+ return true;
331
+ }
332
+ catch (error) {
333
+ return error?.code === 'EPERM';
334
+ }
335
+ }
336
+ function isAuthGenerationError(error) {
337
+ return error instanceof Error && /^auth-generation-(?:corrupt|path-unsafe|capacity|revision-conflict|unavailable)$/.test(error.message);
338
+ }
@@ -1 +1,73 @@
1
- import{hasProtectedCachePayloadMarker as n}from"./protected-pi-boundary.js";const a=50,h=300*1e3;class u{store=new Map;maxSize;ttlMs;constructor(t={}){this.maxSize=t.maxSize??a,this.ttlMs=t.ttlMs??h}async get(t){const e=this.store.get(t);return e?Date.now()>=e.expiresAt?(this.store.delete(t),null):(this.store.delete(t),this.store.set(t,e),e.value):null}async set(t,e,r){if(n(e))return;const i=r??this.ttlMs,o=Date.now()+i;if(this.store.has(t))this.store.delete(t);else if(this.store.size>=this.maxSize){const s=this.store.keys().next().value;s!==void 0&&this.store.delete(s)}this.store.set(t,{value:e,expiresAt:o})}async clear(){this.store.clear()}size(){return this.store.size}}export{u as InMemoryAssetCache};
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
+ import { hasProtectedCachePayloadMarker } from './protected-pi-boundary.js';
14
+ const DEFAULT_MAX_SIZE = 50;
15
+ const DEFAULT_TTL_MS = 5 * 60 * 1000;
16
+ export class InMemoryAssetCache {
17
+ store = new Map();
18
+ maxSize;
19
+ ttlMs;
20
+ constructor(options = {}) {
21
+ this.maxSize = options.maxSize ?? DEFAULT_MAX_SIZE;
22
+ this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
23
+ }
24
+ /**
25
+ * Retrieve a value by key. Returns null if missing or expired.
26
+ * Accessing a key moves it to the end of the LRU ordering.
27
+ */
28
+ async get(key) {
29
+ const entry = this.store.get(key);
30
+ if (!entry)
31
+ return null;
32
+ if (Date.now() >= entry.expiresAt) {
33
+ this.store.delete(key);
34
+ return null;
35
+ }
36
+ // LRU: move to end (most recently used)
37
+ this.store.delete(key);
38
+ this.store.set(key, entry);
39
+ return entry.value;
40
+ }
41
+ /**
42
+ * Store a value by key. Evicts the least-recently-used entry if the
43
+ * cache is at capacity.
44
+ *
45
+ * @param ttlMs - optional override of the default TTL
46
+ */
47
+ async set(key, value, ttlMs) {
48
+ if (hasProtectedCachePayloadMarker(value))
49
+ return;
50
+ const ttl = ttlMs ?? this.ttlMs;
51
+ const expiresAt = Date.now() + ttl;
52
+ if (this.store.has(key)) {
53
+ // Overwrite keeps insertion order fresh -- delete then set.
54
+ this.store.delete(key);
55
+ }
56
+ else if (this.store.size >= this.maxSize) {
57
+ // LRU eviction: delete oldest entry (first in insertion order).
58
+ const oldestKey = this.store.keys().next().value;
59
+ if (oldestKey !== undefined) {
60
+ this.store.delete(oldestKey);
61
+ }
62
+ }
63
+ this.store.set(key, { value, expiresAt });
64
+ }
65
+ /** Drop all entries. Safe to call at any time. */
66
+ async clear() {
67
+ this.store.clear();
68
+ }
69
+ /** Internal: number of live entries (for diagnostics / tests). */
70
+ size() {
71
+ return this.store.size;
72
+ }
73
+ }
@@ -1 +1,13 @@
1
- import{EncryptedCache as c}from"./encrypted-cache.js";export{c as EncryptedCache};
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
+ export { EncryptedCache } from './encrypted-cache.js';
@@ -1 +1,44 @@
1
- const t="protected-cache-payload-rejected",a=/P176_SYNTHETIC_PROTECTED_(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|RAW_LOG|PRIVATE_URL|SECRET|PROPRIETARY_ASSET)/i,n=/^(?:promptBody|workflowBody|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)$/i;function r(e){return!e||typeof e!="object"?!1:Array.isArray(e)?e.some(r):Object.entries(e).some(([o,c])=>n.test(o)||r(c))}function s(e){if(a.test(e))return!0;try{return r(JSON.parse(e))}catch{return!1}}class E extends Error{code=t;constructor(){super(t),this.name="ProtectedCachePayloadError"}}function P(e){if(s(e))throw new E}export{t as PROTECTED_CACHE_PAYLOAD_REASON,E as ProtectedCachePayloadError,P as assertPublicSafeCachePayload,s as hasProtectedCachePayloadMarker};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * Public-safe client cache PI boundary checks.
6
+ */
7
+ /** Public reason code used when a synthetic protected PI marker is detected. */
8
+ export const PROTECTED_CACHE_PAYLOAD_REASON = 'protected-cache-payload-rejected';
9
+ const SYNTHETIC_PROTECTED_MARKER = /P176_SYNTHETIC_PROTECTED_(?:PROMPT|PROMPT_BODY|WORKFLOW|WORKFLOW_GRAPH|STEP_BODY|RAW_LOG|PRIVATE_URL|SECRET|PROPRIETARY_ASSET)/i;
10
+ const PROTECTED_FIELD_NAME = /^(?:promptBody|workflowBody|workflowGraph|stepBody|privateUrl|rawLog|secret|credential|licenseKey|apiKey|internalRouting|serverOnly|proprietary|protected)$/i;
11
+ function hasProtectedField(value) {
12
+ if (!value || typeof value !== 'object')
13
+ return false;
14
+ if (Array.isArray(value))
15
+ return value.some(hasProtectedField);
16
+ return Object.entries(value).some(([key, child]) => (PROTECTED_FIELD_NAME.test(key) || hasProtectedField(child)));
17
+ }
18
+ /**
19
+ * Returns true only for synthetic protected markers or explicit protected field
20
+ * names. Generic words like "prompt" or "workflow" are intentionally not
21
+ * rejected because cache keys and README-grade metadata may use them safely.
22
+ */
23
+ export function hasProtectedCachePayloadMarker(value) {
24
+ if (SYNTHETIC_PROTECTED_MARKER.test(value))
25
+ return true;
26
+ try {
27
+ return hasProtectedField(JSON.parse(value));
28
+ }
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ export class ProtectedCachePayloadError extends Error {
34
+ code = PROTECTED_CACHE_PAYLOAD_REASON;
35
+ constructor() {
36
+ super(PROTECTED_CACHE_PAYLOAD_REASON);
37
+ this.name = 'ProtectedCachePayloadError';
38
+ }
39
+ }
40
+ export function assertPublicSafeCachePayload(value) {
41
+ if (hasProtectedCachePayloadMarker(value)) {
42
+ throw new ProtectedCachePayloadError();
43
+ }
44
+ }
@@ -1,2 +1,127 @@
1
- import{promises as a}from"node:fs";import f from"node:path";import{MAX_SNAPSHOT_SIZE_BYTES as u}from"./shared-checkpoint-types.js";const d=".neocortex/checkpoint-pending.json",p=1e4,c=["FASE_1","FASE_2","FASE_3","FASE_4"];function l(o){if(o===null||typeof o!="object")return{valid:!1,errors:["payload must be object"]};const e=o,n=[];return(typeof e.storyId!="string"||e.storyId.length===0)&&n.push("storyId must be non-empty string"),(typeof e.turn!="number"||!Number.isFinite(e.turn)||e.turn<0)&&n.push("turn must be non-negative finite number"),(!Array.isArray(e.filesModified)||!e.filesModified.every(t=>typeof t=="string"))&&n.push("filesModified must be string[]"),(!Array.isArray(e.testsModified)||!e.testsModified.every(t=>typeof t=="string"))&&n.push("testsModified must be string[]"),(typeof e.currentPhase!="string"||!c.includes(e.currentPhase))&&n.push(`currentPhase must be one of ${c.join("|")}`),typeof e.snapshotMd!="string"&&n.push("snapshotMd must be string"),{valid:n.length===0,errors:Object.freeze(n)}}async function y(o){const e=f.join(o,d);let n;try{n=await a.readFile(e,"utf-8")}catch(r){if(r.code==="ENOENT")return;console.warn(`[Neocortex] checkpoint read failed: ${r instanceof Error?r.message:String(r)}`);return}try{await a.unlink(e)}catch(r){console.warn(`[Neocortex] checkpoint unlink failed: ${r instanceof Error?r.message:String(r)}`)}const t=n.replace(/^/,"").replace(/\r\n/g,`
2
- `);if(t.length>u+p){console.warn(`[Neocortex] checkpoint oversized (${t.length} bytes), skipping`);return}let i;try{i=JSON.parse(t)}catch(r){console.warn(`[Neocortex] checkpoint malformed JSON: ${r instanceof Error?r.message:String(r)}`);return}const s=l(i);if(!s.valid){console.warn(`[Neocortex] checkpoint schema invalid: ${s.errors.join("; ")}`);return}return i}export{d as CHECKPOINT_PENDING_PATH,y as readAndConsumeCheckpoint,l as validateSnapshot};
1
+ /**
2
+ * Epic P109.05: Checkpoint client-side reader (fail-soft).
3
+ *
4
+ * Reads `.neocortex/checkpoint-pending.json` (written by agent per P109.04
5
+ * step prompt instructions), validates shape against ImplementCheckpointSnapshot
6
+ * (P109.02), and consumes (deletes) the file to prevent re-send.
7
+ *
8
+ * Cross-refs: P107.02 (architecture-policy reader pattern), P101.06 (atomic
9
+ * file ops), P63.01 (UTF-8 BOM strip), P103.06 (CRLF normalize).
10
+ */
11
+ import { promises as fs } from 'node:fs';
12
+ import path from 'node:path';
13
+ import { MAX_SNAPSHOT_SIZE_BYTES } from './shared-checkpoint-types.js';
14
+ /**
15
+ * Canonical pending-checkpoint path (relative to projectRoot).
16
+ * Matches P109.04 step prompt instruction literal.
17
+ */
18
+ export const CHECKPOINT_PENDING_PATH = '.neocortex/checkpoint-pending.json';
19
+ /**
20
+ * Size buffer over the server-enforced MAX_SNAPSHOT_SIZE_BYTES to account for
21
+ * JSON structural overhead (field names, quotes, commas). Guards against
22
+ * pathological huge files before parse attempts.
23
+ */
24
+ const SIZE_BUFFER_BYTES = 10000;
25
+ const VALID_PHASES = ['FASE_1', 'FASE_2', 'FASE_3', 'FASE_4'];
26
+ /**
27
+ * Pure validation (zero I/O). Deterministic.
28
+ *
29
+ * Checks all required fields of ImplementCheckpointSnapshot shape. Extra fields
30
+ * are ignored (forward-compat). Does NOT enforce MAX_SNAPSHOT_SIZE_BYTES on
31
+ * snapshotMd length -- that is the reader's responsibility and server's
32
+ * final truncation (P109.06).
33
+ */
34
+ export function validateSnapshot(candidate) {
35
+ if (candidate === null || typeof candidate !== 'object') {
36
+ return { valid: false, errors: ['payload must be object'] };
37
+ }
38
+ const obj = candidate;
39
+ const errors = [];
40
+ if (typeof obj.storyId !== 'string' || obj.storyId.length === 0) {
41
+ errors.push('storyId must be non-empty string');
42
+ }
43
+ if (typeof obj.turn !== 'number' || !Number.isFinite(obj.turn) || obj.turn < 0) {
44
+ errors.push('turn must be non-negative finite number');
45
+ }
46
+ if (!Array.isArray(obj.filesModified) ||
47
+ !obj.filesModified.every((x) => typeof x === 'string')) {
48
+ errors.push('filesModified must be string[]');
49
+ }
50
+ if (!Array.isArray(obj.testsModified) ||
51
+ !obj.testsModified.every((x) => typeof x === 'string')) {
52
+ errors.push('testsModified must be string[]');
53
+ }
54
+ if (typeof obj.currentPhase !== 'string' ||
55
+ !VALID_PHASES.includes(obj.currentPhase)) {
56
+ errors.push(`currentPhase must be one of ${VALID_PHASES.join('|')}`);
57
+ }
58
+ if (typeof obj.snapshotMd !== 'string') {
59
+ errors.push('snapshotMd must be string');
60
+ }
61
+ return { valid: errors.length === 0, errors: Object.freeze(errors) };
62
+ }
63
+ /**
64
+ * Read + validate + consume (delete) the pending checkpoint file.
65
+ *
66
+ * Fail-soft contract:
67
+ * - ENOENT (common case -- no checkpoint pending) -> undefined, silent.
68
+ * - Any other read error -> undefined + console.warn.
69
+ * - Malformed JSON or schema invalid -> undefined + console.warn.
70
+ * - Oversized file -> undefined + console.warn.
71
+ * - Unlink failure -> caller still receives snapshot; warn logged.
72
+ *
73
+ * **File consume is critical (AC4)**: after first successful read (regardless
74
+ * of validation outcome), the file is deleted to prevent re-send on next
75
+ * invoke. This avoids infinite checkpoint-loop scenarios from malformed
76
+ * agent-produced content.
77
+ */
78
+ export async function readAndConsumeCheckpoint(projectRoot) {
79
+ const fullPath = path.join(projectRoot, CHECKPOINT_PENDING_PATH);
80
+ let raw;
81
+ try {
82
+ raw = await fs.readFile(fullPath, 'utf-8');
83
+ }
84
+ catch (err) {
85
+ if (err.code === 'ENOENT') {
86
+ // Common case: no checkpoint pending. Silent (zero warn).
87
+ return undefined;
88
+ }
89
+ // eslint-disable-next-line no-console
90
+ console.warn(`[Neocortex] checkpoint read failed: ${err instanceof Error ? err.message : String(err)}`);
91
+ return undefined;
92
+ }
93
+ // Consume before returning so the enclosing capability drains the physical
94
+ // unlink before an invocation receipt can complete.
95
+ try {
96
+ await fs.unlink(fullPath);
97
+ }
98
+ catch (unlinkErr) {
99
+ // eslint-disable-next-line no-console
100
+ console.warn(`[Neocortex] checkpoint unlink failed: ${unlinkErr instanceof Error ? unlinkErr.message : String(unlinkErr)}`);
101
+ }
102
+ // Encoding defense: BOM strip (P63.01) + CRLF normalize (P103.06).
103
+ const normalized = raw.replace(/^/, '').replace(/\r\n/g, '\n');
104
+ // Size guard (AC5): reject pathologically large files before parse.
105
+ if (normalized.length > MAX_SNAPSHOT_SIZE_BYTES + SIZE_BUFFER_BYTES) {
106
+ // eslint-disable-next-line no-console
107
+ console.warn(`[Neocortex] checkpoint oversized (${normalized.length} bytes), skipping`);
108
+ return undefined;
109
+ }
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(normalized);
113
+ }
114
+ catch (err) {
115
+ // eslint-disable-next-line no-console
116
+ console.warn(`[Neocortex] checkpoint malformed JSON: ${err instanceof Error ? err.message : String(err)}`);
117
+ return undefined;
118
+ }
119
+ const validation = validateSnapshot(parsed);
120
+ if (!validation.valid) {
121
+ // eslint-disable-next-line no-console
122
+ console.warn(`[Neocortex] checkpoint schema invalid: ${validation.errors.join('; ')}`);
123
+ return undefined;
124
+ }
125
+ // Safe to cast after validation.
126
+ return parsed;
127
+ }
@@ -1 +1,11 @@
1
- export*from"./checkpoint-client-reader.js";import{MAX_SNAPSHOT_SIZE_BYTES as _}from"./shared-checkpoint-types.js";export{_ as MAX_SNAPSHOT_SIZE_BYTES};
1
+ /**
2
+ * Epic P109.05: Checkpoint client-side module barrel.
3
+ *
4
+ * Exports the fail-soft reader + validator + canonical path const.
5
+ * Re-exports wire-format types from local SSoT-Shadow inline (P117.01) so
6
+ * the published client tarball never references `@neocortex/shared` at
7
+ * runtime. Type identity stays in sync with `@neocortex/shared` via
8
+ * `checkpoint-shared-sync.test.ts` drift test.
9
+ */
10
+ export * from './checkpoint-client-reader.js';
11
+ export { MAX_SNAPSHOT_SIZE_BYTES } from './shared-checkpoint-types.js';
@@ -1 +1,32 @@
1
- const S=5e4;export{S as MAX_SNAPSHOT_SIZE_BYTES};
1
+ /**
2
+ * P117.01: Inlined byte-identical types from `@neocortex/shared/checkpoints`.
3
+ *
4
+ * SSoT-Shadow pattern (P92.01 server precedent — server `shared-types.ts` does
5
+ * the same for tier-config). Client tarball is published standalone via
6
+ * `@ornexus/neocortex` and does NOT include `@neocortex/shared` as a runtime
7
+ * dependency (workspace package, excluded from tarball per `.npmignore` +
8
+ * `tsconfig.build.json`). Any non-erased import of `@neocortex/shared` in
9
+ * `packages/client/dist/**` causes runtime `ERR_MODULE_NOT_FOUND` on globally
10
+ * installed `@ornexus/neocortex`.
11
+ *
12
+ * Live regression reproduced 2026-04-25 (Epic P117 origin):
13
+ * `[Neocortex] checkpoint hook failed: Cannot find package '@neocortex/shared'
14
+ * imported from .../checkpoint/checkpoint-client-reader.js. Proceeding without
15
+ * checkpoint.`
16
+ *
17
+ * Sync responsibility: `shared-types-sync.test.ts` (P117.01 describe block) +
18
+ * `checkpoint-shared-sync.test.ts` (client-side drift test). Drift test fails
19
+ * CI if these diverge from SSoT.
20
+ *
21
+ * Defense-in-depth: `validate-pre-publish.js` ships
22
+ * `validateClientNoSharedImport()` (P117.01) scanning client dist for
23
+ * `@neocortex/shared` runtime references — match = exit 1 (publish blocked).
24
+ *
25
+ * DO NOT EDIT WITHOUT also editing `packages/shared/src/checkpoints/types.ts`.
26
+ */
27
+ /**
28
+ * Snapshot size guard: prevents PG bloat from pathological code-paste scenarios.
29
+ * Truncate snapshot_md at this byte count (P109.06 enforces).
30
+ */
31
+ export const MAX_SNAPSHOT_SIZE_BYTES = 50000;
32
+ // === END P117.01 ===