@ornexus/neocortex 4.60.67 → 4.60.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.sh +1 -1
  4. package/package.json +2 -2
  5. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  6. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  7. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  8. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  9. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  10. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  11. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  12. package/packages/client/dist/adapters/index.js +22 -1
  13. package/packages/client/dist/adapters/platform-detector.js +212 -1
  14. package/packages/client/dist/adapters/target-adapter.js +12 -0
  15. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  16. package/packages/client/dist/agent/refresh-stubs.js +417 -2
  17. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  18. package/packages/client/dist/agent/update-description.js +251 -1
  19. package/packages/client/dist/cache/crypto-utils.js +78 -1
  20. package/packages/client/dist/cache/encrypted-cache.js +108 -1
  21. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  22. package/packages/client/dist/cache/index.js +13 -1
  23. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  24. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  25. package/packages/client/dist/checkpoint/index.js +11 -1
  26. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  27. package/packages/client/dist/cli.js +290 -3
  28. package/packages/client/dist/commands/activate.js +394 -8
  29. package/packages/client/dist/commands/architecture-answers.js +274 -7
  30. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  31. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  32. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  33. package/packages/client/dist/commands/cache-status.js +112 -2
  34. package/packages/client/dist/commands/config.js +88 -1
  35. package/packages/client/dist/commands/doctor.js +635 -2
  36. package/packages/client/dist/commands/invoke.js +7140 -142
  37. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  38. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  39. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  40. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  41. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  42. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  43. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  44. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  45. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  46. package/packages/client/dist/commands/mutation-qa.js +220 -1
  47. package/packages/client/dist/commands/native-agent.js +136 -2
  48. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  49. package/packages/client/dist/commands/planning-generation.js +53 -1
  50. package/packages/client/dist/commands/planning-memory.js +40 -1
  51. package/packages/client/dist/commands/planning-research.js +42 -1
  52. package/packages/client/dist/commands/private-session.js +75 -1
  53. package/packages/client/dist/commands/property-qa.js +139 -1
  54. package/packages/client/dist/commands/qa-control.js +16 -1
  55. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  56. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  57. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  58. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  59. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  60. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  61. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  62. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  63. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  64. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  65. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  66. package/packages/client/dist/commands/refactor-commit.js +399 -13
  67. package/packages/client/dist/commands/refactor-control.js +142 -3
  68. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  69. package/packages/client/dist/commands/refactor-review.js +283 -5
  70. package/packages/client/dist/commands/refactor-root.js +588 -7
  71. package/packages/client/dist/commands/refresh-memory.js +156 -3
  72. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  73. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  74. package/packages/client/dist/config/profile-directory.js +13 -1
  75. package/packages/client/dist/config/resolver-selection.js +278 -1
  76. package/packages/client/dist/config/secure-config.js +281 -12
  77. package/packages/client/dist/config.js +223 -2
  78. package/packages/client/dist/constants.js +25 -1
  79. package/packages/client/dist/context/context-collector.js +222 -2
  80. package/packages/client/dist/context/context-sanitizer.js +145 -1
  81. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  82. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  83. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  84. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  85. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  86. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  87. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  88. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  89. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  90. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  91. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  92. package/packages/client/dist/continuity/outbox.js +117 -1
  93. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  94. package/packages/client/dist/continuity/sqlite-store.js +2536 -81
  95. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  96. package/packages/client/dist/errors/error-messages.js +228 -2
  97. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  98. package/packages/client/dist/evidence/collector.js +347 -1
  99. package/packages/client/dist/evidence/index.js +1 -1
  100. package/packages/client/dist/evidence/types.js +2 -0
  101. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  102. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  103. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  104. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  105. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  106. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  107. package/packages/client/dist/git/git-lifecycle-store.js +1938 -9
  108. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  109. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  110. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  111. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  112. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  113. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  114. package/packages/client/dist/i18n/first-run.js +60 -2
  115. package/packages/client/dist/index.js +47 -1
  116. package/packages/client/dist/invocation/invoke-input.js +24 -1
  117. package/packages/client/dist/license/index.js +5 -1
  118. package/packages/client/dist/license/license-client.js +304 -1
  119. package/packages/client/dist/machine/fingerprint.js +163 -2
  120. package/packages/client/dist/machine/index.js +5 -1
  121. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  122. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  123. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  124. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  125. package/packages/client/dist/migrations/project-identity.js +493 -7
  126. package/packages/client/dist/migrations/state-json.js +344 -4
  127. package/packages/client/dist/policy/architecture-policy.js +184 -2
  128. package/packages/client/dist/policy/index.js +7 -1
  129. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  130. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  131. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  132. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  133. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  134. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  135. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  136. package/packages/client/dist/private-execution/delivery.js +410 -13
  137. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  138. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  139. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  140. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  141. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  142. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  143. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  144. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  145. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  146. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  147. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  148. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  149. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  150. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  151. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  152. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  153. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  154. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  155. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  156. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  157. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  158. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  159. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  160. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  161. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  162. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  163. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  164. package/packages/client/dist/private-execution/session-lease.js +63 -1
  165. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  166. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  167. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  168. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  169. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  170. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  171. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  172. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  173. package/packages/client/dist/resilience/index.js +8 -1
  174. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  175. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  176. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  177. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  178. package/packages/client/dist/runner/binary.js +404 -1
  179. package/packages/client/dist/runner/cli.js +1571 -17
  180. package/packages/client/dist/runner/headless/adapters.js +49 -1
  181. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  182. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  183. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  184. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  185. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  186. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  187. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  188. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  189. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  190. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  191. package/packages/client/dist/runner/headless/resolver.js +231 -1
  192. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  193. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  194. package/packages/client/dist/runner/headless/types.js +574 -2
  195. package/packages/client/dist/runner/local-console.js +396 -13
  196. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  197. package/packages/client/dist/runner/project-identity.js +106 -1
  198. package/packages/client/dist/runner/scheduler.js +995 -7
  199. package/packages/client/dist/runner-cli.js +18 -2
  200. package/packages/client/dist/state/invocation-shape.js +13 -1
  201. package/packages/client/dist/state/project-state-snapshot.js +1677 -1
  202. package/packages/client/dist/state/state-json-repair.js +785 -3
  203. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  204. package/packages/client/dist/telemetry/index.js +5 -1
  205. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  206. package/packages/client/dist/tier/index.js +5 -1
  207. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  208. package/packages/client/dist/types/index.js +38 -1
  209. package/packages/client/dist/version.js +27 -1
  210. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  211. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  212. package/packages/client/dist/yolo/spec-envelope-collector.js +185 -5
  213. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  214. package/packages/client/dist/yoloop/index.js +8 -1
  215. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  216. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  217. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  218. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  219. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1723 -1
  220. package/targets-stubs/antigravity/gemini.md +1 -1
  221. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  222. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  223. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  224. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  225. package/targets-stubs/claude-code/neocortex.md +2 -2
  226. package/targets-stubs/codex/AGENTS.md +1 -1
  227. package/targets-stubs/cursor/agent.md +2 -2
  228. package/targets-stubs/gemini-cli/agent.md +2 -2
  229. package/targets-stubs/opencode/neocortex-root.md +1 -1
  230. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1 +1,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
+ /**
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 +1,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};
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 +1,100 @@
1
- import{DegradationLevel as e}from"./degradation-manager.js";const l={staleThresholdMs:864e5,warningThresholdMs:432e5};class h{config;constructor(t){this.config={...l,...t}}formatAge(t){if(t<0)return"just now";const r=Math.floor(t/1e3),n=Math.floor(t/6e4),s=Math.floor(t/36e5),o=Math.floor(t/864e5);return o>=1?`${o}d ago`:s>=1?`${s}h ago`:n>=1?`${n}m ago`:r>=1?`${r}s ago`:"just now"}evaluate(t,r){const n=t>this.config.staleThresholdMs,s=t>this.config.warningThresholdMs;let o=null,i="[CACHED]";if(n){const a=this.formatAge(t);i=`[STALE CACHE - ${a}]`,o=`WARNING: STALE - cached ${a}`}else if(s){const a=this.formatAge(t);i="[CACHED]",o=`WARNING - cached ${a}`}return{cached:!0,cacheAgeMs:t,stale:n,warning:o,prefix:i}}formatPrefix(t,r){switch(t){case e.ONLINE:return"";case e.HIGH_LATENCY:return r!=null?`[CACHED] cached ${this.formatAge(r)}`:"[CACHED]";case e.SERVER_DOWN:return r!=null?`[CACHED] cached ${this.formatAge(r)}`:"[CACHED]";case e.STALE_CACHE:return r!=null?`[STALE CACHE - ${this.formatAge(r)}]`:"[STALE CACHE]";case e.NO_CACHE:return"[ERROR]";default:return""}}}export{h as FreshnessIndicator};
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 - Freshness Indicator
15
+ *
16
+ * Enriches cache responses with freshness metadata for user-facing display.
17
+ * Formats cache age as human-readable strings and generates appropriate
18
+ * warning prefixes based on degradation level.
19
+ *
20
+ * Story 42.9
21
+ */
22
+ import { DegradationLevel } from './degradation-manager.js';
23
+ // ── Defaults ──────────────────────────────────────────────────────────────
24
+ const DEFAULT_CONFIG = {
25
+ staleThresholdMs: 86_400_000, // 24 hours
26
+ warningThresholdMs: 43_200_000, // 12 hours
27
+ };
28
+ // ── FreshnessIndicator ──────────────────────────────────────────────────
29
+ export class FreshnessIndicator {
30
+ config;
31
+ constructor(config) {
32
+ this.config = { ...DEFAULT_CONFIG, ...config };
33
+ }
34
+ /**
35
+ * Format a duration in ms as human-readable age string.
36
+ * Examples: "30m ago", "4h ago", "2d ago"
37
+ */
38
+ formatAge(ageMs) {
39
+ if (ageMs < 0)
40
+ return 'just now';
41
+ const seconds = Math.floor(ageMs / 1_000);
42
+ const minutes = Math.floor(ageMs / 60_000);
43
+ const hours = Math.floor(ageMs / 3_600_000);
44
+ const days = Math.floor(ageMs / 86_400_000);
45
+ if (days >= 1)
46
+ return `${days}d ago`;
47
+ if (hours >= 1)
48
+ return `${hours}h ago`;
49
+ if (minutes >= 1)
50
+ return `${minutes}m ago`;
51
+ if (seconds >= 1)
52
+ return `${seconds}s ago`;
53
+ return 'just now';
54
+ }
55
+ /**
56
+ * Evaluate freshness of a cache entry.
57
+ */
58
+ evaluate(cacheAgeMs, _ttlMs) {
59
+ const stale = cacheAgeMs > this.config.staleThresholdMs;
60
+ const aged = cacheAgeMs > this.config.warningThresholdMs;
61
+ let warning = null;
62
+ let prefix = '[CACHED]';
63
+ if (stale) {
64
+ const ageStr = this.formatAge(cacheAgeMs);
65
+ prefix = `[STALE CACHE - ${ageStr}]`;
66
+ warning = `WARNING: STALE - cached ${ageStr}`;
67
+ }
68
+ else if (aged) {
69
+ const ageStr = this.formatAge(cacheAgeMs);
70
+ prefix = `[CACHED]`;
71
+ warning = `WARNING - cached ${ageStr}`;
72
+ }
73
+ return {
74
+ cached: true,
75
+ cacheAgeMs,
76
+ stale,
77
+ warning,
78
+ prefix,
79
+ };
80
+ }
81
+ /**
82
+ * Format prefix string based on degradation level and optional age.
83
+ */
84
+ formatPrefix(level, ageMs) {
85
+ switch (level) {
86
+ case DegradationLevel.ONLINE:
87
+ return '';
88
+ case DegradationLevel.HIGH_LATENCY:
89
+ return ageMs != null ? `[CACHED] cached ${this.formatAge(ageMs)}` : '[CACHED]';
90
+ case DegradationLevel.SERVER_DOWN:
91
+ return ageMs != null ? `[CACHED] cached ${this.formatAge(ageMs)}` : '[CACHED]';
92
+ case DegradationLevel.STALE_CACHE:
93
+ return ageMs != null ? `[STALE CACHE - ${this.formatAge(ageMs)}]` : '[STALE CACHE]';
94
+ case DegradationLevel.NO_CACHE:
95
+ return '[ERROR]';
96
+ default:
97
+ return '';
98
+ }
99
+ }
100
+ }
@@ -1 +1,8 @@
1
- import{ClientCircuitBreaker as o}from"./circuit-breaker.js";import{DegradationManager as a,DegradationLevel as i}from"./degradation-manager.js";import{FreshnessIndicator as c}from"./freshness-indicator.js";import{RecoveryDetector as m}from"./recovery-detector.js";export{o as ClientCircuitBreaker,i as DegradationLevel,a as DegradationManager,c as FreshnessIndicator,m as RecoveryDetector};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ */
5
+ export { ClientCircuitBreaker } from './circuit-breaker.js';
6
+ export { DegradationManager, DegradationLevel } from './degradation-manager.js';
7
+ export { FreshnessIndicator } from './freshness-indicator.js';
8
+ export { RecoveryDetector } from './recovery-detector.js';
@@ -1 +1,74 @@
1
- class n{actions;constructor(e){this.actions=e}async onRecovery(){const e={circuitClosed:!1,jwtRefreshed:!1,cacheSynced:!1,telemetryFlushed:{sent:0,failed:0},notification:"[ONLINE] Server connection restored"};try{await this.actions.circuitBreaker.recordSuccess(),e.circuitClosed=!0}catch{}try{const t=await this.actions.licenseClient.getToken();e.jwtRefreshed=t!==null}catch{}try{e.cacheSynced=!0}catch{}try{const t=await this.actions.telemetryQueue.flush(async c=>(await fetch(`${this.actions.serverUrl}/api/v1/telemetry/batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:c})})).ok);e.telemetryFlushed=t}catch{}return e}}export{n as RecoveryDetector};
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
+ // ── RecoveryDetector ─────────────────────────────────────────────────────
14
+ export class RecoveryDetector {
15
+ actions;
16
+ constructor(actions) {
17
+ this.actions = actions;
18
+ }
19
+ /**
20
+ * Execute full recovery sequence.
21
+ * Each step is independent - failures are captured but don't block others.
22
+ */
23
+ async onRecovery() {
24
+ const result = {
25
+ circuitClosed: false,
26
+ jwtRefreshed: false,
27
+ cacheSynced: false,
28
+ telemetryFlushed: { sent: 0, failed: 0 },
29
+ notification: '[ONLINE] Server connection restored',
30
+ };
31
+ // Step 1: Close circuit breaker
32
+ try {
33
+ await this.actions.circuitBreaker.recordSuccess();
34
+ result.circuitClosed = true;
35
+ }
36
+ catch {
37
+ // Non-critical: breaker will close on next successful call
38
+ }
39
+ // Step 2: Re-validate JWT
40
+ try {
41
+ const token = await this.actions.licenseClient.getToken();
42
+ result.jwtRefreshed = token !== null;
43
+ }
44
+ catch {
45
+ // Non-critical: will be retried on next server call
46
+ }
47
+ // Step 3: Sync cache (background - just attempt, don't block)
48
+ try {
49
+ // We don't actually sync here - the next resolver call will
50
+ // update the cache automatically via fetchWithCacheFallback.
51
+ // We just mark as synced since the circuit is now closed.
52
+ result.cacheSynced = true;
53
+ }
54
+ catch {
55
+ // Non-critical
56
+ }
57
+ // Step 4: Flush telemetry queue
58
+ try {
59
+ const flushResult = await this.actions.telemetryQueue.flush(async (events) => {
60
+ const response = await fetch(`${this.actions.serverUrl}/api/v1/telemetry/batch`, {
61
+ method: 'POST',
62
+ headers: { 'Content-Type': 'application/json' },
63
+ body: JSON.stringify({ events }),
64
+ });
65
+ return response.ok;
66
+ });
67
+ result.telemetryFlushed = flushResult;
68
+ }
69
+ catch {
70
+ // Non-critical: queue will be flushed on next recovery
71
+ }
72
+ return result;
73
+ }
74
+ }
@@ -0,0 +1,13 @@
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 {};