@ornexus/neocortex 4.61.5 → 4.62.0

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 (279) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +1 -1
  5. package/package.json +5 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.d.ts +8 -1
  20. package/packages/client/dist/agent/update-description.js +2 -260
  21. package/packages/client/dist/cache/crypto-utils.js +1 -78
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  23. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  24. package/packages/client/dist/cache/index.js +1 -13
  25. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  26. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  27. package/packages/client/dist/checkpoint/index.js +1 -11
  28. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  29. package/packages/client/dist/cli.js +5 -364
  30. package/packages/client/dist/commands/activate.js +8 -394
  31. package/packages/client/dist/commands/architecture-answers.js +7 -274
  32. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  33. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  34. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  35. package/packages/client/dist/commands/cache-status.js +2 -112
  36. package/packages/client/dist/commands/config.js +1 -88
  37. package/packages/client/dist/commands/doctor.js +2 -635
  38. package/packages/client/dist/commands/invoke.d.ts +17 -0
  39. package/packages/client/dist/commands/invoke.js +148 -7822
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  41. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  42. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  44. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  45. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  46. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  47. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  49. package/packages/client/dist/commands/mutation-qa.js +1 -220
  50. package/packages/client/dist/commands/native-agent.js +2 -136
  51. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  52. package/packages/client/dist/commands/planning-generation.js +1 -53
  53. package/packages/client/dist/commands/planning-memory.js +1 -40
  54. package/packages/client/dist/commands/planning-research.js +1 -42
  55. package/packages/client/dist/commands/private-session.js +1 -75
  56. package/packages/client/dist/commands/property-qa.js +1 -139
  57. package/packages/client/dist/commands/qa-control.js +1 -16
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  60. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  61. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  62. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  68. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  69. package/packages/client/dist/commands/refactor-commit.js +13 -399
  70. package/packages/client/dist/commands/refactor-control.js +3 -142
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  72. package/packages/client/dist/commands/refactor-review.js +5 -283
  73. package/packages/client/dist/commands/refactor-root.js +7 -588
  74. package/packages/client/dist/commands/refresh-memory.js +3 -174
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  77. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  78. package/packages/client/dist/commands/story-worktree.js +5 -258
  79. package/packages/client/dist/config/host-auth-broker.js +1 -60
  80. package/packages/client/dist/config/host-auth-reference.js +1 -93
  81. package/packages/client/dist/config/profile-directory.js +1 -13
  82. package/packages/client/dist/config/resolver-selection.js +1 -278
  83. package/packages/client/dist/config/secure-config.js +12 -281
  84. package/packages/client/dist/config.js +2 -224
  85. package/packages/client/dist/constants.js +1 -25
  86. package/packages/client/dist/context/context-collector.js +2 -222
  87. package/packages/client/dist/context/context-sanitizer.js +1 -145
  88. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  89. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  90. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  91. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  92. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  93. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  94. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  95. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  96. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  97. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  98. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  99. package/packages/client/dist/continuity/outbox.js +1 -117
  100. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  101. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  102. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  103. package/packages/client/dist/errors/error-messages.js +2 -258
  104. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  105. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  106. package/packages/client/dist/evidence/collector.js +1 -347
  107. package/packages/client/dist/evidence/index.js +1 -1
  108. package/packages/client/dist/evidence/types.js +0 -2
  109. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  110. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  111. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  112. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  113. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +94 -9
  114. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -1592
  115. package/packages/client/dist/git/epic-operational-state.js +2 -672
  116. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  117. package/packages/client/dist/git/git-lifecycle-store.d.ts +88 -0
  118. package/packages/client/dist/git/git-lifecycle-store.js +9 -2529
  119. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  120. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  121. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  122. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  123. package/packages/client/dist/git/release-gate-env.d.ts +62 -0
  124. package/packages/client/dist/git/release-gate-env.js +1 -0
  125. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  126. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -186
  127. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  128. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  129. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  130. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  131. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  132. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  133. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  134. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  135. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  136. package/packages/client/dist/i18n/first-run.js +2 -60
  137. package/packages/client/dist/index.js +1 -50
  138. package/packages/client/dist/invocation/invoke-input.js +1 -24
  139. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  140. package/packages/client/dist/license/index.js +1 -5
  141. package/packages/client/dist/license/license-client.js +1 -337
  142. package/packages/client/dist/machine/fingerprint.js +2 -163
  143. package/packages/client/dist/machine/index.js +1 -5
  144. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  145. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  146. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  147. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  148. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  149. package/packages/client/dist/migrations/project-identity.js +7 -493
  150. package/packages/client/dist/migrations/state-json.js +4 -393
  151. package/packages/client/dist/policy/architecture-policy.js +2 -184
  152. package/packages/client/dist/policy/index.js +1 -7
  153. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  154. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  155. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  156. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  157. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  158. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  159. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  160. package/packages/client/dist/private-execution/delivery.js +13 -410
  161. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  162. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  163. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  164. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  165. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  166. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  167. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  168. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  169. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  170. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  171. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  172. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  173. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  174. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  175. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  176. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  177. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  178. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  179. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  180. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  181. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  182. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  183. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  184. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  185. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  186. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  187. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  188. package/packages/client/dist/private-execution/session-lease.js +1 -63
  189. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  190. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  191. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  192. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  193. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  194. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  195. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  196. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  197. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  198. package/packages/client/dist/resilience/index.js +1 -8
  199. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  200. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  201. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  202. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  203. package/packages/client/dist/runner/binary.js +1 -404
  204. package/packages/client/dist/runner/cli.js +17 -1571
  205. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  206. package/packages/client/dist/runner/headless/adapters.js +1 -49
  207. package/packages/client/dist/runner/headless/background-root.js +1 -85
  208. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  209. package/packages/client/dist/runner/headless/child-env.js +1 -0
  210. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  211. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  212. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  213. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  214. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
  215. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  216. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  217. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  218. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  219. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  220. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  221. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  222. package/packages/client/dist/runner/headless/resolver.js +1 -231
  223. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  224. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  225. package/packages/client/dist/runner/headless/types.js +2 -575
  226. package/packages/client/dist/runner/host-capacity.js +1 -59
  227. package/packages/client/dist/runner/local-console.js +13 -396
  228. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  229. package/packages/client/dist/runner/project-identity.js +1 -106
  230. package/packages/client/dist/runner/scheduler.js +7 -995
  231. package/packages/client/dist/runner-cli.js +2 -18
  232. package/packages/client/dist/state/invocation-shape.js +1 -13
  233. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  234. package/packages/client/dist/state/state-json-repair.js +3 -785
  235. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  236. package/packages/client/dist/telemetry/index.js +1 -5
  237. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  238. package/packages/client/dist/tier/index.js +1 -5
  239. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  240. package/packages/client/dist/types/index.js +1 -38
  241. package/packages/client/dist/version.js +1 -27
  242. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  243. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  244. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  245. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  246. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  247. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  248. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  249. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  250. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  251. package/packages/client/dist/yoloop/index.js +1 -8
  252. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  253. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
  254. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  255. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  256. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  257. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  258. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  259. package/packages/shared/dist/project-manifest-projection.js +199 -0
  260. package/packages/shared/dist/project-validation-commands.js +14 -6
  261. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  262. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  263. package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
  264. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  265. package/targets-stubs/antigravity/gemini.md +1 -1
  266. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  267. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  268. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  269. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  270. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  271. package/targets-stubs/claude-code/neocortex.md +5 -5
  272. package/targets-stubs/codex/AGENTS.md +1 -1
  273. package/targets-stubs/cursor/agent.md +2 -2
  274. package/targets-stubs/gemini-cli/agent.md +2 -2
  275. package/targets-stubs/lib/managed-config-merge.js +77 -1
  276. package/targets-stubs/lib/managed-profile.sh +7 -0
  277. package/targets-stubs/opencode/neocortex-root.md +1 -1
  278. package/targets-stubs/vscode/install-vscode.sh +21 -0
  279. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,338 +1 @@
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
+ 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,73 +1 @@
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
+ 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,13 +1 @@
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
+ import{EncryptedCache as c}from"./encrypted-cache.js";export{c as EncryptedCache};
@@ -1,44 +1 @@
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
+ 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,127 +1,2 @@
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
+ 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,11 +1 @@
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
+ export*from"./checkpoint-client-reader.js";import{MAX_SNAPSHOT_SIZE_BYTES as _}from"./shared-checkpoint-types.js";export{_ as MAX_SNAPSHOT_SIZE_BYTES};
@@ -1,32 +1 @@
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 ===
1
+ const S=5e4;export{S as MAX_SNAPSHOT_SIZE_BYTES};