@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,234 +1 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { join, resolve } from 'node:path';
5
- export const REGISTRY_RECONCILIATION_REASON_CODES = Object.freeze({
6
- VERSION_INVALID: 'REGISTRY_RECONCILIATION_VERSION_INVALID',
7
- PROJECT_INVALID: 'REGISTRY_RECONCILIATION_PROJECT_INVALID',
8
- DOWNGRADE_BLOCKED: 'REGISTRY_RECONCILIATION_DOWNGRADE_BLOCKED',
9
- ARTIFACT_UNAVAILABLE: 'REGISTRY_RECONCILIATION_ARTIFACT_UNAVAILABLE',
10
- ARTIFACT_MISMATCH: 'REGISTRY_RECONCILIATION_ARTIFACT_MISMATCH',
11
- INSTALL_FAILED: 'REGISTRY_RECONCILIATION_INSTALL_FAILED',
12
- });
13
- export class RegistryReconciliationError extends Error {
14
- reasonCode;
15
- remediation;
16
- constructor(reasonCode, remediation) {
17
- super(`${reasonCode}: ${remediation}`);
18
- this.reasonCode = reasonCode;
19
- this.remediation = remediation;
20
- this.name = 'RegistryReconciliationError';
21
- }
22
- }
23
- const EXACT_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
24
- const REGISTRY_VERSION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u;
25
- const SHA256 = /^[a-f0-9]{64}$/u;
26
- export function parseExactSemver(value) {
27
- const match = EXACT_SEMVER.exec(value);
28
- if (!match)
29
- return undefined;
30
- const numeric = [match[1], match[2], match[3]].map(Number);
31
- if (numeric.some((part) => !Number.isSafeInteger(part)))
32
- return undefined;
33
- const prereleaseParts = match[4]?.split('.') ?? [];
34
- if (prereleaseParts.some((part) => /^\d+$/u.test(part) && !/^(0|[1-9]\d*)$/u.test(part)))
35
- return undefined;
36
- const prerelease = prereleaseParts.map((part) => /^(0|[1-9]\d*)$/u.test(part) ? Number(part) : part);
37
- return {
38
- major: numeric[0],
39
- minor: numeric[1],
40
- patch: numeric[2],
41
- prerelease,
42
- };
43
- }
44
- export function compareExactSemver(left, right) {
45
- const a = parseExactSemver(left);
46
- const b = parseExactSemver(right);
47
- if (!a || !b)
48
- return undefined;
49
- for (const key of ['major', 'minor', 'patch']) {
50
- if (a[key] !== b[key])
51
- return a[key] > b[key] ? 1 : -1;
52
- }
53
- if (a.prerelease.length === 0 || b.prerelease.length === 0) {
54
- return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
55
- }
56
- const length = Math.max(a.prerelease.length, b.prerelease.length);
57
- for (let index = 0; index < length; index += 1) {
58
- const av = a.prerelease[index];
59
- const bv = b.prerelease[index];
60
- if (av === undefined || bv === undefined)
61
- return av === bv ? 0 : av === undefined ? -1 : 1;
62
- if (av === bv)
63
- continue;
64
- if (typeof av === 'number' && typeof bv === 'string')
65
- return -1;
66
- if (typeof av === 'string' && typeof bv === 'number')
67
- return 1;
68
- return av > bv ? 1 : -1;
69
- }
70
- return 0;
71
- }
72
- function assertRegistryIdentity(value, reasonCode) {
73
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
74
- throw new RegistryReconciliationError(reasonCode, 'Regenerate the local command registry and retry.');
75
- }
76
- const candidate = value;
77
- if (typeof candidate.registryVersion !== 'string' || !REGISTRY_VERSION.test(candidate.registryVersion)
78
- || typeof candidate.registryChecksum !== 'string' || !SHA256.test(candidate.registryChecksum)) {
79
- throw new RegistryReconciliationError(reasonCode, 'Regenerate the local command registry and retry.');
80
- }
81
- return { version: candidate.registryVersion, checksum: candidate.registryChecksum };
82
- }
83
- /** Read only a Neocortex source checkout. Ordinary projects are not candidates. */
84
- export function readProjectRegistryIdentity(projectRoot) {
85
- const packagePath = join(resolve(projectRoot), 'package.json');
86
- if (!existsSync(packagePath))
87
- return undefined;
88
- let pkg;
89
- try {
90
- pkg = JSON.parse(readFileSync(packagePath, 'utf8'));
91
- }
92
- catch {
93
- // A non-Neocortex project owns its package.json. Invoke validation remains
94
- // responsible for it; registry reconciliation must not claim authority.
95
- return undefined;
96
- }
97
- if (pkg.name !== '@ornexus/neocortex')
98
- return undefined;
99
- if (typeof pkg.version !== 'string' || !parseExactSemver(pkg.version)) {
100
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.PROJECT_INVALID, 'Set the local @ornexus/neocortex package to an exact valid version and retry.');
101
- }
102
- const manifestPath = join(resolve(projectRoot), 'generated', 'command-registry', 'manifest.json');
103
- if (!existsSync(manifestPath)) {
104
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.PROJECT_INVALID, 'Run the repository command-registry generator, then retry.');
105
- }
106
- try {
107
- const identity = assertRegistryIdentity(JSON.parse(readFileSync(manifestPath, 'utf8')), REGISTRY_RECONCILIATION_REASON_CODES.PROJECT_INVALID);
108
- return { ...identity, packageVersion: pkg.version };
109
- }
110
- catch (error) {
111
- if (error instanceof RegistryReconciliationError)
112
- throw error;
113
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.PROJECT_INVALID, 'Regenerate the local command registry and retry.');
114
- }
115
- }
116
- function readGeneratedIdentity(source) {
117
- // Development builds retain exported identifiers. Published builds are
118
- // minified, so use the public projection-manifest keys as a deterministic
119
- // fallback rather than depending on private/minifier symbol names.
120
- const version = source.match(/COMMAND_REGISTRY_VERSION\s*=\s*["']([^"']+)["']/u)?.[1]
121
- ?? source.match(/registryVersion\s*:\s*["']([^"']+)["']/u)?.[1];
122
- const checksum = source.match(/COMMAND_REGISTRY_CHECKSUM\s*=\s*["']([a-f0-9]{64})["']/u)?.[1]
123
- ?? source.match(/registryChecksum\s*:\s*["']([a-f0-9]{64})["']/u)?.[1];
124
- return assertRegistryIdentity({ registryVersion: version, registryChecksum: checksum }, REGISTRY_RECONCILIATION_REASON_CODES.ARTIFACT_MISMATCH);
125
- }
126
- /** Validate an npm-installed fixture without trusting lifecycle output. */
127
- export function readPublishedPackageIdentityFromPrefix(prefix) {
128
- const root = join(prefix, 'node_modules', '@ornexus', 'neocortex');
129
- try {
130
- const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
131
- if (pkg.name !== '@ornexus/neocortex' || typeof pkg.version !== 'string' || !parseExactSemver(pkg.version)) {
132
- throw new Error('invalid package identity');
133
- }
134
- const generatedPath = join(root, 'packages', 'client', 'dist', 'generated', 'command-registry.generated.js');
135
- const identity = readGeneratedIdentity(readFileSync(generatedPath, 'utf8'));
136
- return { packageName: '@ornexus/neocortex', packageVersion: pkg.version, ...identity };
137
- }
138
- catch {
139
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.ARTIFACT_MISMATCH, 'The published package does not contain a valid client registry projection; do not invoke.');
140
- }
141
- }
142
- function defaultReadLatestVersion() {
143
- return execFileSync('npm', ['view', '@ornexus/neocortex', 'version'], {
144
- encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 30_000,
145
- }).trim();
146
- }
147
- function defaultInspectPublished(version) {
148
- const prefix = mkdtempSync(join(tmpdir(), 'neocortex-registry-reconcile-'));
149
- try {
150
- execFileSync('npm', [
151
- 'install', '--prefix', prefix, '--ignore-scripts', '--no-audit', '--no-fund', '--package-lock=false',
152
- `@ornexus/neocortex@${version}`,
153
- ], { stdio: 'ignore', timeout: 120_000 });
154
- const identity = readPublishedPackageIdentityFromPrefix(prefix);
155
- if (identity.packageVersion !== version)
156
- throw new Error('npm resolved a different version');
157
- return identity;
158
- }
159
- catch (error) {
160
- if (error instanceof RegistryReconciliationError)
161
- throw error;
162
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.ARTIFACT_UNAVAILABLE, `Verify public npm access, then install explicitly: npm install -g @ornexus/neocortex@${version}`);
163
- }
164
- finally {
165
- rmSync(prefix, { recursive: true, force: true });
166
- }
167
- }
168
- function defaultInstallGlobal(version) {
169
- try {
170
- execFileSync('npm', ['install', '-g', `@ornexus/neocortex@${version}`], {
171
- stdio: 'ignore', timeout: 120_000,
172
- });
173
- }
174
- catch {
175
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.INSTALL_FAILED, `Install the verified compatible client explicitly: npm install -g @ornexus/neocortex@${version}`);
176
- }
177
- }
178
- function sameIdentity(left, right) {
179
- return left.version === right.version && left.checksum === right.checksum;
180
- }
181
- export function reconcileRegistry(options) {
182
- const installed = parseExactSemver(options.installedVersion);
183
- if (!installed) {
184
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.VERSION_INVALID, 'Reinstall an exact published client version and retry.');
185
- }
186
- const dependencies = options.dependencies ?? {};
187
- const project = (dependencies.readProject ?? readProjectRegistryIdentity)(options.projectRoot);
188
- let selectedVersion;
189
- let expectedIdentity;
190
- let source = 'installed';
191
- if (project) {
192
- if (sameIdentity(project, options.installedIdentity)) {
193
- return { status: 'current', selectedVersion: options.installedVersion, source: 'project' };
194
- }
195
- const order = compareExactSemver(project.packageVersion, options.installedVersion);
196
- if (order === undefined) {
197
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.VERSION_INVALID, 'Use exact valid installed and project versions, then retry.');
198
- }
199
- if (order < 0) {
200
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.DOWNGRADE_BLOCKED, `The project requires ${project.packageVersion}, older than installed ${options.installedVersion}. Use a matching checkout or explicitly select a client version; automatic downgrade was refused.`);
201
- }
202
- selectedVersion = project.packageVersion;
203
- expectedIdentity = project;
204
- source = 'project';
205
- }
206
- else if (options.checkLatest) {
207
- let latest;
208
- try {
209
- latest = (dependencies.readLatestVersion ?? defaultReadLatestVersion)().trim();
210
- }
211
- catch {
212
- return { status: 'not-applicable', selectedVersion: options.installedVersion, source: 'installed' };
213
- }
214
- const order = compareExactSemver(latest, options.installedVersion);
215
- if (order === undefined) {
216
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.VERSION_INVALID, 'The public latest or installed version is invalid; no update was attempted.');
217
- }
218
- // Crucially, inequality is not enough: older stable tags never replace a
219
- // newer/beta installation.
220
- if (order <= 0)
221
- return { status: 'current', selectedVersion: options.installedVersion, source: 'installed' };
222
- selectedVersion = latest;
223
- source = 'latest';
224
- }
225
- else {
226
- return { status: 'not-applicable', selectedVersion: options.installedVersion, source: 'installed' };
227
- }
228
- const published = (dependencies.inspectPublished ?? defaultInspectPublished)(selectedVersion);
229
- if (published.packageVersion !== selectedVersion || (expectedIdentity && !sameIdentity(published, expectedIdentity))) {
230
- throw new RegistryReconciliationError(REGISTRY_RECONCILIATION_REASON_CODES.ARTIFACT_MISMATCH, `The public ${selectedVersion} artifact does not match the local registry projection. Regenerate/release a matching artifact; no global package was changed.`);
231
- }
232
- (dependencies.installGlobal ?? defaultInstallGlobal)(selectedVersion);
233
- return { status: 'updated', selectedVersion, source };
234
- }
1
+ import{execFileSync as p}from"node:child_process";import{existsSync as g,mkdtempSync as E,readFileSync as I,rmSync as T}from"node:fs";import{tmpdir as N}from"node:os";import{join as u,resolve as h}from"node:path";const a=Object.freeze({VERSION_INVALID:"REGISTRY_RECONCILIATION_VERSION_INVALID",PROJECT_INVALID:"REGISTRY_RECONCILIATION_PROJECT_INVALID",DOWNGRADE_BLOCKED:"REGISTRY_RECONCILIATION_DOWNGRADE_BLOCKED",ARTIFACT_UNAVAILABLE:"REGISTRY_RECONCILIATION_ARTIFACT_UNAVAILABLE",ARTIFACT_MISMATCH:"REGISTRY_RECONCILIATION_ARTIFACT_MISMATCH",INSTALL_FAILED:"REGISTRY_RECONCILIATION_INSTALL_FAILED"});class o extends Error{reasonCode;remediation;constructor(r,e){super(`${r}: ${e}`),this.reasonCode=r,this.remediation=e,this.name="RegistryReconciliationError"}}const _=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,V=/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/u,C=/^[a-f0-9]{64}$/u;function f(t){const r=_.exec(t);if(!r)return;const e=[r[1],r[2],r[3]].map(Number);if(e.some(i=>!Number.isSafeInteger(i)))return;const n=r[4]?.split(".")??[];if(n.some(i=>/^\d+$/u.test(i)&&!/^(0|[1-9]\d*)$/u.test(i)))return;const s=n.map(i=>/^(0|[1-9]\d*)$/u.test(i)?Number(i):i);return{major:e[0],minor:e[1],patch:e[2],prerelease:s}}function y(t,r){const e=f(t),n=f(r);if(!e||!n)return;for(const i of["major","minor","patch"])if(e[i]!==n[i])return e[i]>n[i]?1:-1;if(e.prerelease.length===0||n.prerelease.length===0)return e.prerelease.length===n.prerelease.length?0:e.prerelease.length===0?1:-1;const s=Math.max(e.prerelease.length,n.prerelease.length);for(let i=0;i<s;i+=1){const c=e.prerelease[i],l=n.prerelease[i];if(c===void 0||l===void 0)return c===l?0:c===void 0?-1:1;if(c!==l)return typeof c=="number"&&typeof l=="string"?-1:typeof c=="string"&&typeof l=="number"||c>l?1:-1}return 0}function A(t,r){if(!t||typeof t!="object"||Array.isArray(t))throw new o(r,"Regenerate the local command registry and retry.");const e=t;if(typeof e.registryVersion!="string"||!V.test(e.registryVersion)||typeof e.registryChecksum!="string"||!C.test(e.registryChecksum))throw new o(r,"Regenerate the local command registry and retry.");return{version:e.registryVersion,checksum:e.registryChecksum}}function x(t){const r=u(h(t),"package.json");if(!g(r))return;let e;try{e=JSON.parse(I(r,"utf8"))}catch{return}if(e.name!=="@ornexus/neocortex")return;if(typeof e.version!="string"||!f(e.version))throw new o(a.PROJECT_INVALID,"Set the local @ornexus/neocortex package to an exact valid version and retry.");const n=u(h(t),"generated","command-registry","manifest.json");if(!g(n))throw new o(a.PROJECT_INVALID,"Run the repository command-registry generator, then retry.");try{return{...A(JSON.parse(I(n,"utf8")),a.PROJECT_INVALID),packageVersion:e.version}}catch(s){throw s instanceof o?s:new o(a.PROJECT_INVALID,"Regenerate the local command registry and retry.")}}function S(t){const r=t.match(/COMMAND_REGISTRY_VERSION\s*=\s*["']([^"']+)["']/u)?.[1]??t.match(/registryVersion\s*:\s*["']([^"']+)["']/u)?.[1],e=t.match(/COMMAND_REGISTRY_CHECKSUM\s*=\s*["']([a-f0-9]{64})["']/u)?.[1]??t.match(/registryChecksum\s*:\s*["']([a-f0-9]{64})["']/u)?.[1];return A({registryVersion:r,registryChecksum:e},a.ARTIFACT_MISMATCH)}function O(t){const r=u(t,"node_modules","@ornexus","neocortex");try{const e=JSON.parse(I(u(r,"package.json"),"utf8"));if(e.name!=="@ornexus/neocortex"||typeof e.version!="string"||!f(e.version))throw new Error("invalid package identity");const n=u(r,"packages","client","dist","generated","command-registry.generated.js"),s=S(I(n,"utf8"));return{packageName:"@ornexus/neocortex",packageVersion:e.version,...s}}catch{throw new o(a.ARTIFACT_MISMATCH,"The published package does not contain a valid client registry projection; do not invoke.")}}function L(){return p("npm",["view","@ornexus/neocortex","version"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:3e4}).trim()}function w(t){const r=E(u(N(),"neocortex-registry-reconcile-"));try{p("npm",["install","--prefix",r,"--ignore-scripts","--no-audit","--no-fund","--package-lock=false",`@ornexus/neocortex@${t}`],{stdio:"ignore",timeout:12e4});const e=O(r);if(e.packageVersion!==t)throw new Error("npm resolved a different version");return e}catch(e){throw e instanceof o?e:new o(a.ARTIFACT_UNAVAILABLE,`Verify public npm access, then install explicitly: npm install -g @ornexus/neocortex@${t}`)}finally{T(r,{recursive:!0,force:!0})}}function k(t){try{p("npm",["install","-g",`@ornexus/neocortex@${t}`],{stdio:"ignore",timeout:12e4})}catch{throw new o(a.INSTALL_FAILED,`Install the verified compatible client explicitly: npm install -g @ornexus/neocortex@${t}`)}}function R(t,r){return t.version===r.version&&t.checksum===r.checksum}function M(t){if(!f(t.installedVersion))throw new o(a.VERSION_INVALID,"Reinstall an exact published client version and retry.");const e=t.dependencies??{},n=(e.readProject??x)(t.projectRoot);let s,i,c="installed";if(n){if(R(n,t.installedIdentity))return{status:"current",selectedVersion:t.installedVersion,source:"project"};const d=y(n.packageVersion,t.installedVersion);if(d===void 0)throw new o(a.VERSION_INVALID,"Use exact valid installed and project versions, then retry.");if(d<0)throw new o(a.DOWNGRADE_BLOCKED,`The project requires ${n.packageVersion}, older than installed ${t.installedVersion}. Use a matching checkout or explicitly select a client version; automatic downgrade was refused.`);s=n.packageVersion,i=n,c="project"}else if(t.checkLatest){let d;try{d=(e.readLatestVersion??L)().trim()}catch{return{status:"not-applicable",selectedVersion:t.installedVersion,source:"installed"}}const m=y(d,t.installedVersion);if(m===void 0)throw new o(a.VERSION_INVALID,"The public latest or installed version is invalid; no update was attempted.");if(m<=0)return{status:"current",selectedVersion:t.installedVersion,source:"installed"};s=d,c="latest"}else return{status:"not-applicable",selectedVersion:t.installedVersion,source:"installed"};const l=(e.inspectPublished??w)(s);if(l.packageVersion!==s||i&&!R(l,i))throw new o(a.ARTIFACT_MISMATCH,`The public ${s} artifact does not match the local registry projection. Regenerate/release a matching artifact; no global package was changed.`);return(e.installGlobal??k)(s),{status:"updated",selectedVersion:s,source:c}}export{a as REGISTRY_RECONCILIATION_REASON_CODES,o as RegistryReconciliationError,y as compareExactSemver,f as parseExactSemver,x as readProjectRegistryIdentity,O as readPublishedPackageIdentityFromPrefix,M as reconcileRegistry};
@@ -1,170 +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 - Persistent Circuit Breaker
15
- *
16
- * Circuit breaker with file-based state persistence for the CLI client.
17
- * Tracks server health using window-based failure counting and persists
18
- * state between CLI invocations at ~/.neocortex/.circuit-state.
19
- *
20
- * States:
21
- * CLOSED - Normal operation, requests pass through
22
- * OPEN - Circuit tripped, requests fail immediately (use cache)
23
- * HALF_OPEN - Testing if server recovered (one probe request allowed)
24
- *
25
- * Story 42.9
26
- */
27
- import { readFile, writeFile, mkdir } from 'node:fs/promises';
28
- import { dirname } from 'node:path';
29
- import { homedir } from 'node:os';
30
- import { join } from 'node:path';
31
- // ── Defaults ──────────────────────────────────────────────────────────────
32
- const DEFAULT_CONFIG = {
33
- failureThreshold: 3,
34
- failureWindowMs: 60_000,
35
- halfOpenAfterMs: 60_000,
36
- stateFilePath: join(homedir(), '.neocortex', '.circuit-state'),
37
- };
38
- const INITIAL_STATE = {
39
- state: 'CLOSED',
40
- failures: [],
41
- openedAt: null,
42
- lastProbeAt: null,
43
- };
44
- // ── ClientCircuitBreaker ──────────────────────────────────────────────────
45
- export class ClientCircuitBreaker {
46
- config;
47
- internalState;
48
- constructor(config, initialState) {
49
- this.config = { ...DEFAULT_CONFIG, ...config };
50
- this.internalState = initialState ? { ...initialState } : { ...INITIAL_STATE, failures: [] };
51
- }
52
- /**
53
- * Check if a request can be made to the server.
54
- * Returns false if circuit is OPEN (fail-fast to cache).
55
- */
56
- canCall() {
57
- this.pruneExpiredFailures();
58
- switch (this.internalState.state) {
59
- case 'CLOSED':
60
- return true;
61
- case 'OPEN': {
62
- const now = Date.now();
63
- const openedAt = this.internalState.openedAt ?? 0;
64
- if (now - openedAt >= this.config.halfOpenAfterMs) {
65
- this.internalState.state = 'HALF_OPEN';
66
- this.internalState.lastProbeAt = now;
67
- return true;
68
- }
69
- return false;
70
- }
71
- case 'HALF_OPEN':
72
- return true;
73
- default:
74
- return true;
75
- }
76
- }
77
- /**
78
- * Record a successful server response. Closes the circuit.
79
- */
80
- async recordSuccess() {
81
- this.internalState.state = 'CLOSED';
82
- this.internalState.failures = [];
83
- this.internalState.openedAt = null;
84
- this.internalState.lastProbeAt = null;
85
- await this.saveToDisk();
86
- }
87
- /**
88
- * Record a failed server response. Opens circuit after threshold failures in window.
89
- */
90
- async recordFailure() {
91
- const now = Date.now();
92
- this.internalState.failures.push({ timestamp: now });
93
- this.pruneExpiredFailures();
94
- if (this.internalState.failures.length >= this.config.failureThreshold) {
95
- this.internalState.state = 'OPEN';
96
- this.internalState.openedAt = now;
97
- }
98
- // If in HALF_OPEN and probe fails, go back to OPEN
99
- if (this.internalState.state === 'HALF_OPEN') {
100
- this.internalState.state = 'OPEN';
101
- this.internalState.openedAt = now;
102
- }
103
- await this.saveToDisk();
104
- }
105
- /**
106
- * Get current circuit breaker state (copy).
107
- */
108
- getState() {
109
- this.pruneExpiredFailures();
110
- return {
111
- state: this.internalState.state,
112
- failures: [...this.internalState.failures],
113
- openedAt: this.internalState.openedAt,
114
- lastProbeAt: this.internalState.lastProbeAt,
115
- };
116
- }
117
- /**
118
- * Reset circuit breaker to initial CLOSED state.
119
- */
120
- async reset() {
121
- this.internalState = { ...INITIAL_STATE, failures: [] };
122
- await this.saveToDisk();
123
- }
124
- /**
125
- * Load circuit breaker state from disk.
126
- */
127
- static async loadFromDisk(path) {
128
- const filePath = path ?? DEFAULT_CONFIG.stateFilePath;
129
- try {
130
- const raw = await readFile(filePath, 'utf8');
131
- const data = JSON.parse(raw);
132
- // Validate loaded state
133
- if (!data.state || !Array.isArray(data.failures)) {
134
- return new ClientCircuitBreaker({ stateFilePath: filePath });
135
- }
136
- return new ClientCircuitBreaker({ stateFilePath: filePath }, data);
137
- }
138
- catch {
139
- // File doesn't exist or is corrupted - start fresh
140
- return new ClientCircuitBreaker({ stateFilePath: filePath });
141
- }
142
- }
143
- // ── Private ─────────────────────────────────────────────────────────
144
- /**
145
- * Remove failures outside the counting window.
146
- */
147
- pruneExpiredFailures() {
148
- const cutoff = Date.now() - this.config.failureWindowMs;
149
- this.internalState.failures = this.internalState.failures.filter((f) => f.timestamp > cutoff);
150
- }
151
- /**
152
- * Persist state to disk with atomic write.
153
- */
154
- async saveToDisk() {
155
- try {
156
- const dir = dirname(this.config.stateFilePath);
157
- await mkdir(dir, { recursive: true });
158
- const tmpPath = `${this.config.stateFilePath}.tmp`;
159
- const data = JSON.stringify(this.internalState, null, 2);
160
- await writeFile(tmpPath, data, 'utf8');
161
- // Atomic rename
162
- const { rename } = await import('node:fs/promises');
163
- await rename(tmpPath, this.config.stateFilePath);
164
- }
165
- catch {
166
- // Persistence failures are non-critical - circuit breaker
167
- // still works in-memory for current session
168
- }
169
- }
170
- }
1
+ import{readFile as l,writeFile as o,mkdir as h}from"node:fs/promises";import{dirname as u}from"node:path";import{homedir as c}from"node:os";import{join as f}from"node:path";const n={failureThreshold:3,failureWindowMs:6e4,halfOpenAfterMs:6e4,stateFilePath:f(c(),".neocortex",".circuit-state")},r={state:"CLOSED",failures:[],openedAt:null,lastProbeAt:null};class i{config;internalState;constructor(t,e){this.config={...n,...t},this.internalState=e?{...e}:{...r,failures:[]}}canCall(){switch(this.pruneExpiredFailures(),this.internalState.state){case"CLOSED":return!0;case"OPEN":{const t=Date.now(),e=this.internalState.openedAt??0;return t-e>=this.config.halfOpenAfterMs?(this.internalState.state="HALF_OPEN",this.internalState.lastProbeAt=t,!0):!1}case"HALF_OPEN":return!0;default:return!0}}async recordSuccess(){this.internalState.state="CLOSED",this.internalState.failures=[],this.internalState.openedAt=null,this.internalState.lastProbeAt=null,await this.saveToDisk()}async recordFailure(){const t=Date.now();this.internalState.failures.push({timestamp:t}),this.pruneExpiredFailures(),this.internalState.failures.length>=this.config.failureThreshold&&(this.internalState.state="OPEN",this.internalState.openedAt=t),this.internalState.state==="HALF_OPEN"&&(this.internalState.state="OPEN",this.internalState.openedAt=t),await this.saveToDisk()}getState(){return this.pruneExpiredFailures(),{state:this.internalState.state,failures:[...this.internalState.failures],openedAt:this.internalState.openedAt,lastProbeAt:this.internalState.lastProbeAt}}async reset(){this.internalState={...r,failures:[]},await this.saveToDisk()}static async loadFromDisk(t){const e=t??n.stateFilePath;try{const s=await l(e,"utf8"),a=JSON.parse(s);return!a.state||!Array.isArray(a.failures)?new i({stateFilePath:e}):new i({stateFilePath:e},a)}catch{return new i({stateFilePath:e})}}pruneExpiredFailures(){const t=Date.now()-this.config.failureWindowMs;this.internalState.failures=this.internalState.failures.filter(e=>e.timestamp>t)}async saveToDisk(){try{const t=u(this.config.stateFilePath);await h(t,{recursive:!0});const e=`${this.config.stateFilePath}.tmp`,s=JSON.stringify(this.internalState,null,2);await o(e,s,"utf8");const{rename:a}=await import("node:fs/promises");await a(e,this.config.stateFilePath)}catch{}}}export{i as ClientCircuitBreaker};
@@ -1,164 +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
- // ── Types ─────────────────────────────────────────────────────────────────
14
- export var DegradationLevel;
15
- (function (DegradationLevel) {
16
- /** Server available, fresh data, optimal performance */
17
- DegradationLevel[DegradationLevel["ONLINE"] = 0] = "ONLINE";
18
- /** Server slow (>2s), use cache when available */
19
- DegradationLevel[DegradationLevel["HIGH_LATENCY"] = 1] = "HIGH_LATENCY";
20
- /** Server down, use cache exclusively */
21
- DegradationLevel[DegradationLevel["SERVER_DOWN"] = 2] = "SERVER_DOWN";
22
- /** Cache expired (>24h), use with warning */
23
- DegradationLevel[DegradationLevel["STALE_CACHE"] = 3] = "STALE_CACHE";
24
- /** No cache and no server - error state */
25
- DegradationLevel[DegradationLevel["NO_CACHE"] = 4] = "NO_CACHE";
26
- })(DegradationLevel || (DegradationLevel = {}));
27
- // ── Defaults ──────────────────────────────────────────────────────────────
28
- const DEFAULT_CONFIG = {
29
- staleThresholdMs: 86_400_000, // 24 hours
30
- warningThresholdMs: 43_200_000, // 12 hours
31
- latencyThresholdMs: 2_000, // 2 seconds
32
- };
33
- // ── DegradationManager ───────────────────────────────────────────────────
34
- export class DegradationManager {
35
- config;
36
- constructor(config) {
37
- this.config = { ...DEFAULT_CONFIG, ...config };
38
- }
39
- /**
40
- * Evaluate the current degradation level based on context.
41
- */
42
- evaluate(context) {
43
- // Force-offline mode: always use cache
44
- if (context.forceOffline) {
45
- return this.buildCacheOnlyDecision(context, '[OFFLINE]');
46
- }
47
- // Circuit is OPEN: server known to be down
48
- if (context.circuitState === 'OPEN') {
49
- return this.buildServerDownDecision(context);
50
- }
51
- // Circuit is HALF_OPEN: probing server
52
- if (context.circuitState === 'HALF_OPEN') {
53
- // Allow server request (probe), but prepare cache fallback
54
- return {
55
- level: DegradationLevel.SERVER_DOWN,
56
- useCache: true,
57
- useServer: true,
58
- prefix: '[PROBING]',
59
- warning: null,
60
- };
61
- }
62
- // Circuit is CLOSED: server available
63
- if (context.latencyMs != null && context.latencyMs > this.config.latencyThresholdMs) {
64
- // High latency: prefer cache if available
65
- if (context.cacheAvailable) {
66
- return {
67
- level: DegradationLevel.HIGH_LATENCY,
68
- useCache: true,
69
- useServer: false,
70
- prefix: '[CACHED]',
71
- warning: null,
72
- };
73
- }
74
- // No cache available: still use server (slow is better than nothing)
75
- return {
76
- level: DegradationLevel.HIGH_LATENCY,
77
- useCache: false,
78
- useServer: true,
79
- prefix: '',
80
- warning: 'Server response is slow. Consider running `neocortex cache warmup`.',
81
- };
82
- }
83
- // Normal operation
84
- return {
85
- level: DegradationLevel.ONLINE,
86
- useCache: false,
87
- useServer: true,
88
- prefix: '',
89
- warning: null,
90
- };
91
- }
92
- // ── Private ─────────────────────────────────────────────────────────
93
- buildServerDownDecision(context) {
94
- if (!context.cacheAvailable) {
95
- return {
96
- level: DegradationLevel.NO_CACHE,
97
- useCache: false,
98
- useServer: false,
99
- prefix: '[ERROR]',
100
- warning: 'Server unavailable and no cached data. Run `neocortex cache warmup` when online.',
101
- };
102
- }
103
- const cacheAgeMs = context.cacheAgeMs ?? 0;
104
- if (cacheAgeMs > this.config.staleThresholdMs) {
105
- const ageStr = this.formatAge(cacheAgeMs);
106
- return {
107
- level: DegradationLevel.STALE_CACHE,
108
- useCache: true,
109
- useServer: false,
110
- prefix: `[STALE CACHE - ${ageStr}]`,
111
- warning: `Cache is stale (${ageStr} old). Data may be outdated.`,
112
- };
113
- }
114
- return {
115
- level: DegradationLevel.SERVER_DOWN,
116
- useCache: true,
117
- useServer: false,
118
- prefix: '[CACHED]',
119
- warning: cacheAgeMs > this.config.warningThresholdMs
120
- ? `Cache is ${this.formatAge(cacheAgeMs)} old.`
121
- : null,
122
- };
123
- }
124
- buildCacheOnlyDecision(context, prefix) {
125
- if (!context.cacheAvailable) {
126
- return {
127
- level: DegradationLevel.NO_CACHE,
128
- useCache: false,
129
- useServer: false,
130
- prefix: '[ERROR]',
131
- warning: 'Offline mode active but no cached data available. Run `neocortex cache warmup` when online.',
132
- };
133
- }
134
- const cacheAgeMs = context.cacheAgeMs ?? 0;
135
- if (cacheAgeMs > this.config.staleThresholdMs) {
136
- const ageStr = this.formatAge(cacheAgeMs);
137
- return {
138
- level: DegradationLevel.STALE_CACHE,
139
- useCache: true,
140
- useServer: false,
141
- prefix: `[STALE CACHE - ${ageStr}]`,
142
- warning: `Using stale cache (${ageStr} old) in offline mode.`,
143
- };
144
- }
145
- return {
146
- level: DegradationLevel.SERVER_DOWN,
147
- useCache: true,
148
- useServer: false,
149
- prefix,
150
- warning: null,
151
- };
152
- }
153
- formatAge(ms) {
154
- const hours = Math.floor(ms / 3_600_000);
155
- if (hours >= 48)
156
- return `${Math.floor(hours / 24)}d`;
157
- if (hours >= 1)
158
- return `${hours}h`;
159
- const minutes = Math.floor(ms / 60_000);
160
- if (minutes >= 1)
161
- return `${minutes}m`;
162
- return '<1m';
163
- }
164
- }
1
+ var r;(function(s){s[s.ONLINE=0]="ONLINE",s[s.HIGH_LATENCY=1]="HIGH_LATENCY",s[s.SERVER_DOWN=2]="SERVER_DOWN",s[s.STALE_CACHE=3]="STALE_CACHE",s[s.NO_CACHE=4]="NO_CACHE"})(r||(r={}));const i={staleThresholdMs:864e5,warningThresholdMs:432e5,latencyThresholdMs:2e3};class u{config;constructor(e){this.config={...i,...e}}evaluate(e){return e.forceOffline?this.buildCacheOnlyDecision(e,"[OFFLINE]"):e.circuitState==="OPEN"?this.buildServerDownDecision(e):e.circuitState==="HALF_OPEN"?{level:r.SERVER_DOWN,useCache:!0,useServer:!0,prefix:"[PROBING]",warning:null}:e.latencyMs!=null&&e.latencyMs>this.config.latencyThresholdMs?e.cacheAvailable?{level:r.HIGH_LATENCY,useCache:!0,useServer:!1,prefix:"[CACHED]",warning:null}:{level:r.HIGH_LATENCY,useCache:!1,useServer:!0,prefix:"",warning:"Server response is slow. Consider running `neocortex cache warmup`."}:{level:r.ONLINE,useCache:!1,useServer:!0,prefix:"",warning:null}}buildServerDownDecision(e){if(!e.cacheAvailable)return{level:r.NO_CACHE,useCache:!1,useServer:!1,prefix:"[ERROR]",warning:"Server unavailable and no cached data. Run `neocortex cache warmup` when online."};const a=e.cacheAgeMs??0;if(a>this.config.staleThresholdMs){const n=this.formatAge(a);return{level:r.STALE_CACHE,useCache:!0,useServer:!1,prefix:`[STALE CACHE - ${n}]`,warning:`Cache is stale (${n} old). Data may be outdated.`}}return{level:r.SERVER_DOWN,useCache:!0,useServer:!1,prefix:"[CACHED]",warning:a>this.config.warningThresholdMs?`Cache is ${this.formatAge(a)} old.`:null}}buildCacheOnlyDecision(e,a){if(!e.cacheAvailable)return{level:r.NO_CACHE,useCache:!1,useServer:!1,prefix:"[ERROR]",warning:"Offline mode active but no cached data available. Run `neocortex cache warmup` when online."};const n=e.cacheAgeMs??0;if(n>this.config.staleThresholdMs){const l=this.formatAge(n);return{level:r.STALE_CACHE,useCache:!0,useServer:!1,prefix:`[STALE CACHE - ${l}]`,warning:`Using stale cache (${l} old) in offline mode.`}}return{level:r.SERVER_DOWN,useCache:!0,useServer:!1,prefix:a,warning:null}}formatAge(e){const a=Math.floor(e/36e5);if(a>=48)return`${Math.floor(a/24)}d`;if(a>=1)return`${a}h`;const n=Math.floor(e/6e4);return n>=1?`${n}m`:"<1m"}}export{r as DegradationLevel,u as DegradationManager};