@ornexus/neocortex 4.61.4 → 4.61.6

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 (254) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +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.js +1 -260
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -364
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +148 -7822
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -174
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  76. package/packages/client/dist/commands/story-worktree.js +5 -258
  77. package/packages/client/dist/config/host-auth-broker.js +1 -60
  78. package/packages/client/dist/config/host-auth-reference.js +1 -93
  79. package/packages/client/dist/config/profile-directory.js +1 -13
  80. package/packages/client/dist/config/resolver-selection.js +1 -278
  81. package/packages/client/dist/config/secure-config.js +12 -281
  82. package/packages/client/dist/config.js +2 -224
  83. package/packages/client/dist/constants.js +1 -25
  84. package/packages/client/dist/context/context-collector.js +2 -222
  85. package/packages/client/dist/context/context-sanitizer.js +1 -145
  86. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  87. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  88. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  89. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  90. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  91. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  92. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  93. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  94. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  95. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  96. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  97. package/packages/client/dist/continuity/outbox.js +1 -117
  98. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  99. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  100. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  101. package/packages/client/dist/errors/error-messages.js +2 -258
  102. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  103. package/packages/client/dist/evidence/collector.js +1 -347
  104. package/packages/client/dist/evidence/index.js +1 -1
  105. package/packages/client/dist/evidence/types.js +0 -2
  106. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  107. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  108. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  109. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  110. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
  111. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
  112. package/packages/client/dist/git/epic-operational-state.js +2 -672
  113. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  114. package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
  115. package/packages/client/dist/git/git-lifecycle-store.js +8 -2500
  116. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  117. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  118. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  119. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  120. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  121. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  122. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  123. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  124. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  125. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  126. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  127. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  128. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  129. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  130. package/packages/client/dist/i18n/first-run.js +2 -60
  131. package/packages/client/dist/index.js +1 -50
  132. package/packages/client/dist/invocation/invoke-input.js +1 -24
  133. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  134. package/packages/client/dist/license/index.js +1 -5
  135. package/packages/client/dist/license/license-client.js +1 -337
  136. package/packages/client/dist/machine/fingerprint.js +2 -163
  137. package/packages/client/dist/machine/index.js +1 -5
  138. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  139. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  140. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  141. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  142. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  143. package/packages/client/dist/migrations/project-identity.js +7 -493
  144. package/packages/client/dist/migrations/state-json.js +4 -393
  145. package/packages/client/dist/policy/architecture-policy.js +2 -184
  146. package/packages/client/dist/policy/index.js +1 -7
  147. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  148. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  149. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  150. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  151. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  152. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  153. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  154. package/packages/client/dist/private-execution/delivery.js +13 -410
  155. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  156. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  157. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  158. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  159. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  160. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  161. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  162. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  163. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  164. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  165. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  166. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  167. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  168. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  169. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  170. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  171. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  172. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  173. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  174. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  175. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  176. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  177. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  178. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  179. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  180. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  181. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  182. package/packages/client/dist/private-execution/session-lease.js +1 -63
  183. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  184. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  185. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  186. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  187. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  188. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  189. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  190. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  191. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  192. package/packages/client/dist/resilience/index.js +1 -8
  193. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  194. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  195. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  196. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  197. package/packages/client/dist/runner/binary.js +1 -404
  198. package/packages/client/dist/runner/cli.js +17 -1571
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.js +1 -85
  202. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  203. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  204. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  205. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  206. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  207. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  208. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  209. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  210. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  211. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  212. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  213. package/packages/client/dist/runner/headless/resolver.js +1 -231
  214. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  215. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  216. package/packages/client/dist/runner/headless/types.js +2 -575
  217. package/packages/client/dist/runner/host-capacity.js +1 -59
  218. package/packages/client/dist/runner/local-console.js +13 -396
  219. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  220. package/packages/client/dist/runner/project-identity.js +1 -106
  221. package/packages/client/dist/runner/scheduler.js +7 -995
  222. package/packages/client/dist/runner-cli.js +2 -18
  223. package/packages/client/dist/state/invocation-shape.js +1 -13
  224. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  225. package/packages/client/dist/state/state-json-repair.js +3 -785
  226. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  227. package/packages/client/dist/telemetry/index.js +1 -5
  228. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  229. package/packages/client/dist/tier/index.js +1 -5
  230. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  231. package/packages/client/dist/types/index.js +1 -38
  232. package/packages/client/dist/version.js +1 -27
  233. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  234. package/packages/client/dist/yolo/change-evidence-collector.js +1 -245
  235. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  236. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  237. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  238. package/packages/client/dist/yoloop/index.js +1 -8
  239. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  240. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  241. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  242. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  243. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  244. package/targets-stubs/antigravity/gemini.md +1 -1
  245. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  246. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  247. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  248. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  249. package/targets-stubs/claude-code/neocortex.md +2 -2
  250. package/targets-stubs/codex/AGENTS.md +1 -1
  251. package/targets-stubs/cursor/agent.md +2 -2
  252. package/targets-stubs/gemini-cli/agent.md +2 -2
  253. package/targets-stubs/opencode/neocortex-root.md +1 -1
  254. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,278 +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 - Resolver Selection Factory
15
- *
16
- * Factory function that selects the appropriate AssetResolver
17
- * based on CLI flags, environment variables, and auto-detection.
18
- *
19
- * Decision chain (priority order):
20
- * 1. forceLocal option (--local flag) -> LocalResolver
21
- * 2. NEOCORTEX_MODE=local env -> LocalResolver
22
- * 3. NEOCORTEX_MODE=remote env -> RemoteResolver
23
- * 4. core/ directory exists locally -> LocalResolver (dev mode)
24
- * 4.5. Feature flag cutover (hash(machine) % 100 < remotePercentage) -> RemoteResolver
25
- * 5. Valid license key present + no core/ -> RemoteResolver
26
- * 6. Default -> LocalResolver (safe fallback)
27
- */
28
- import { access, readFile, writeFile, mkdir } from 'node:fs/promises';
29
- import { join, resolve } from 'node:path';
30
- import { homedir } from 'node:os';
31
- import { createHash } from 'node:crypto';
32
- import { LocalResolver } from '../resolvers/local-resolver.js';
33
- import { RemoteResolver } from '../resolvers/remote-resolver.js';
34
- import { DEFAULT_SERVER_URL } from '../constants.js';
35
- // ── Feature Flag (Story 43.7) ───────────────────────────────────────────
36
- const CONFIG_CACHE_FILE = join(homedir(), '.neocortex', 'feature-flags.json');
37
- const CONFIG_CACHE_TTL_MS = 3600_000; // 1 hour
38
- /**
39
- * Check if this machine should use remote mode based on server feature flags.
40
- * Uses hash(machine_fingerprint) % 100 < remotePercentage to determine bucket.
41
- * Caches the server config for 1 hour.
42
- *
43
- * Returns 'remote' | 'local' | 'skip' (skip = no flag applies)
44
- */
45
- async function checkFeatureFlag(options) {
46
- try {
47
- // Check env override
48
- const envPercentage = process.env['NEOCORTEX_REMOTE_PERCENTAGE'];
49
- if (envPercentage !== undefined) {
50
- const pct = parseInt(envPercentage, 10);
51
- if (isNaN(pct) || pct <= 0)
52
- return 'skip';
53
- return isInRemoteBucket(pct) ? 'remote' : 'local';
54
- }
55
- // Try cached config
56
- const cached = await loadFeatureFlagCache();
57
- if (cached) {
58
- if (cached.forceLocal)
59
- return 'local';
60
- if (cached.forceRemote)
61
- return 'remote';
62
- if (cached.remotePercentage <= 0)
63
- return 'skip';
64
- return isInRemoteBucket(cached.remotePercentage) ? 'remote' : 'local';
65
- }
66
- // Fetch from server (non-blocking, fail gracefully)
67
- const serverUrl = getServerUrl(options);
68
- const config = await fetchFeatureFlags(serverUrl);
69
- if (config) {
70
- await saveFeatureFlagCache(config);
71
- if (config.forceLocal)
72
- return 'local';
73
- if (config.forceRemote)
74
- return 'remote';
75
- if (config.remotePercentage <= 0)
76
- return 'skip';
77
- return isInRemoteBucket(config.remotePercentage) ? 'remote' : 'local';
78
- }
79
- return 'skip'; // No flag info available
80
- }
81
- catch {
82
- return 'skip'; // Never block on feature flag errors
83
- }
84
- }
85
- /**
86
- * Deterministic bucket assignment using machine fingerprint hash.
87
- * hash(machine_id) % 100 < percentage = in remote bucket
88
- */
89
- function isInRemoteBucket(percentage) {
90
- const machineId = process.env['NEOCORTEX_MACHINE_ID'] ?? 'default';
91
- const hash = createHash('sha256').update(machineId).digest();
92
- const bucket = hash.readUInt16BE(0) % 100;
93
- return bucket < percentage;
94
- }
95
- async function loadFeatureFlagCache() {
96
- try {
97
- const raw = await readFile(CONFIG_CACHE_FILE, 'utf-8');
98
- const cached = JSON.parse(raw);
99
- if (Date.now() - cached.fetchedAt < CONFIG_CACHE_TTL_MS) {
100
- return cached;
101
- }
102
- return null; // Expired
103
- }
104
- catch {
105
- return null;
106
- }
107
- }
108
- async function saveFeatureFlagCache(config) {
109
- try {
110
- await mkdir(join(homedir(), '.neocortex'), { recursive: true });
111
- await writeFile(CONFIG_CACHE_FILE, JSON.stringify(config), 'utf-8');
112
- }
113
- catch {
114
- // Non-critical - ignore
115
- }
116
- }
117
- async function fetchFeatureFlags(serverUrl) {
118
- try {
119
- const controller = new AbortController();
120
- const timeout = setTimeout(() => controller.abort(), 5000);
121
- const response = await fetch(`${serverUrl}/api/v1/config`, {
122
- signal: controller.signal,
123
- });
124
- clearTimeout(timeout);
125
- if (!response.ok)
126
- return null;
127
- const data = (await response.json());
128
- return {
129
- remotePercentage: data.remotePercentage ?? 0,
130
- forceRemote: data.forceRemote ?? false,
131
- forceLocal: data.forceLocal ?? false,
132
- fetchedAt: Date.now(),
133
- };
134
- }
135
- catch {
136
- return null;
137
- }
138
- }
139
- // ── Detection Helpers ───────────────────────────────────────────────────
140
- /**
141
- * Check if the core/ directory exists at the given project root.
142
- * This indicates development mode.
143
- */
144
- async function detectLocalMode(projectRoot) {
145
- try {
146
- await access(join(projectRoot, 'core'));
147
- return true;
148
- }
149
- catch {
150
- return false;
151
- }
152
- }
153
- /**
154
- * Get license key from environment or options.
155
- */
156
- function getLicenseKey(options) {
157
- return options?.licenseKey || process.env['NEOCORTEX_LICENSE_KEY'] || undefined;
158
- }
159
- /**
160
- * Get server URL from environment or options.
161
- */
162
- function getServerUrl(options) {
163
- return (options?.serverUrl ||
164
- process.env['NEOCORTEX_SERVER_URL'] ||
165
- DEFAULT_SERVER_URL);
166
- }
167
- // ── Factory Function ────────────────────────────────────────────────────
168
- /**
169
- * Create the appropriate AssetResolver based on configuration.
170
- *
171
- * Selection follows a strict priority chain:
172
- * 1. forceLocal option -> LocalResolver
173
- * 2. NEOCORTEX_MODE=local -> LocalResolver
174
- * 3. NEOCORTEX_MODE=remote -> RemoteResolver
175
- * 4. core/ exists locally -> LocalResolver
176
- * 5. License key + no core/ -> RemoteResolver
177
- * 6. Default -> LocalResolver
178
- *
179
- * @param options - Optional configuration overrides
180
- * @returns Configured AssetResolver ready for use
181
- */
182
- export async function createResolver(options) {
183
- const result = await selectResolver(options);
184
- return result.resolver;
185
- }
186
- /**
187
- * Select resolver with full result including reason.
188
- * Useful for logging/debugging why a specific resolver was chosen.
189
- */
190
- export async function selectResolver(options) {
191
- const projectRoot = resolve(options?.projectRoot || process.cwd());
192
- const neocortexMode = process.env['NEOCORTEX_MODE']?.toLowerCase();
193
- // 1. forceLocal option (--local CLI flag)
194
- if (options?.forceLocal) {
195
- return {
196
- resolver: new LocalResolver({ projectRoot }),
197
- reason: 'Forced local mode via --local flag',
198
- mode: 'local',
199
- };
200
- }
201
- // 2. NEOCORTEX_MODE=local
202
- if (neocortexMode === 'local') {
203
- return {
204
- resolver: new LocalResolver({ projectRoot }),
205
- reason: 'NEOCORTEX_MODE=local environment variable',
206
- mode: 'local',
207
- };
208
- }
209
- // 3. NEOCORTEX_MODE=remote
210
- if (neocortexMode === 'remote') {
211
- const licenseKey = getLicenseKey(options);
212
- if (!licenseKey) {
213
- // Fall back to local if no license key for remote mode
214
- return {
215
- resolver: new LocalResolver({ projectRoot }),
216
- reason: 'NEOCORTEX_MODE=remote but no license key found, falling back to local',
217
- mode: 'local',
218
- };
219
- }
220
- return {
221
- resolver: new RemoteResolver({
222
- serverUrl: getServerUrl(options),
223
- licenseKey,
224
- cacheProvider: options?.cacheProvider,
225
- licenseClient: options?.licenseClient,
226
- }),
227
- reason: 'NEOCORTEX_MODE=remote environment variable',
228
- mode: 'remote',
229
- };
230
- }
231
- // 4. Auto-detect: core/ directory exists -> dev mode
232
- const hasLocalCore = await detectLocalMode(projectRoot);
233
- if (hasLocalCore) {
234
- return {
235
- resolver: new LocalResolver({ projectRoot }),
236
- reason: 'Auto-detected development mode (core/ directory exists)',
237
- mode: 'local',
238
- };
239
- }
240
- // 4.5. Feature flag cutover check (Story 43.7)
241
- // If server config says remotePercentage > 0, check if this machine is in the bucket
242
- const featureFlagResult = await checkFeatureFlag(options);
243
- if (featureFlagResult === 'remote') {
244
- const licenseKey = getLicenseKey(options);
245
- if (licenseKey) {
246
- return {
247
- resolver: new RemoteResolver({
248
- serverUrl: getServerUrl(options),
249
- licenseKey,
250
- cacheProvider: options?.cacheProvider,
251
- licenseClient: options?.licenseClient,
252
- }),
253
- reason: 'Feature flag cutover: machine in remote bucket',
254
- mode: 'remote',
255
- };
256
- }
257
- }
258
- // 5. License key present + no core/ -> production mode
259
- const licenseKey = getLicenseKey(options);
260
- if (licenseKey) {
261
- return {
262
- resolver: new RemoteResolver({
263
- serverUrl: getServerUrl(options),
264
- licenseKey,
265
- cacheProvider: options?.cacheProvider,
266
- licenseClient: options?.licenseClient,
267
- }),
268
- reason: 'Auto-detected production mode (license key present, no core/ directory)',
269
- mode: 'remote',
270
- };
271
- }
272
- // 6. Default -> LocalResolver (safe fallback)
273
- return {
274
- resolver: new LocalResolver({ projectRoot }),
275
- reason: 'Default fallback to local mode',
276
- mode: 'local',
277
- };
278
- }
1
+ import{access as E,readFile as h,writeFile as R,mkdir as C}from"node:fs/promises";import{join as i,resolve as w}from"node:path";import{homedir as d}from"node:os";import{createHash as g}from"node:crypto";import{LocalResolver as l}from"../resolvers/local-resolver.js";import{RemoteResolver as u}from"../resolvers/remote-resolver.js";import{DEFAULT_SERVER_URL as O}from"../constants.js";const v=i(d(),".neocortex","feature-flags.json"),y=36e5;async function _(e){try{const r=process.env.NEOCORTEX_REMOTE_PERCENTAGE;if(r!==void 0){const n=parseInt(r,10);return isNaN(n)||n<=0?"skip":f(n)?"remote":"local"}const t=await F();if(t)return t.forceLocal?"local":t.forceRemote?"remote":t.remotePercentage<=0?"skip":f(t.remotePercentage)?"remote":"local";const c=s(e),o=await L(c);return o?(await p(o),o.forceLocal?"local":o.forceRemote?"remote":o.remotePercentage<=0?"skip":f(o.remotePercentage)?"remote":"local"):"skip"}catch{return"skip"}}function f(e){const r=process.env.NEOCORTEX_MACHINE_ID??"default";return g("sha256").update(r).digest().readUInt16BE(0)%100<e}async function F(){try{const e=await h(v,"utf-8"),r=JSON.parse(e);return Date.now()-r.fetchedAt<y?r:null}catch{return null}}async function p(e){try{await C(i(d(),".neocortex"),{recursive:!0}),await R(v,JSON.stringify(e),"utf-8")}catch{}}async function L(e){try{const r=new AbortController,t=setTimeout(()=>r.abort(),5e3),c=await fetch(`${e}/api/v1/config`,{signal:r.signal});if(clearTimeout(t),!c.ok)return null;const o=await c.json();return{remotePercentage:o.remotePercentage??0,forceRemote:o.forceRemote??!1,forceLocal:o.forceLocal??!1,fetchedAt:Date.now()}}catch{return null}}async function N(e){try{return await E(i(e,"core")),!0}catch{return!1}}function m(e){return e?.licenseKey||process.env.NEOCORTEX_LICENSE_KEY||void 0}function s(e){return e?.serverUrl||process.env.NEOCORTEX_SERVER_URL||O}async function M(e){return(await k(e)).resolver}async function k(e){const r=w(e?.projectRoot||process.cwd()),t=process.env.NEOCORTEX_MODE?.toLowerCase();if(e?.forceLocal)return{resolver:new l({projectRoot:r}),reason:"Forced local mode via --local flag",mode:"local"};if(t==="local")return{resolver:new l({projectRoot:r}),reason:"NEOCORTEX_MODE=local environment variable",mode:"local"};if(t==="remote"){const a=m(e);return a?{resolver:new u({serverUrl:s(e),licenseKey:a,cacheProvider:e?.cacheProvider,licenseClient:e?.licenseClient}),reason:"NEOCORTEX_MODE=remote environment variable",mode:"remote"}:{resolver:new l({projectRoot:r}),reason:"NEOCORTEX_MODE=remote but no license key found, falling back to local",mode:"local"}}if(await N(r))return{resolver:new l({projectRoot:r}),reason:"Auto-detected development mode (core/ directory exists)",mode:"local"};if(await _(e)==="remote"){const a=m(e);if(a)return{resolver:new u({serverUrl:s(e),licenseKey:a,cacheProvider:e?.cacheProvider,licenseClient:e?.licenseClient}),reason:"Feature flag cutover: machine in remote bucket",mode:"remote"}}const n=m(e);return n?{resolver:new u({serverUrl:s(e),licenseKey:n,cacheProvider:e?.cacheProvider,licenseClient:e?.licenseClient}),reason:"Auto-detected production mode (license key present, no core/ directory)",mode:"remote"}:{resolver:new l({projectRoot:r}),reason:"Default fallback to local mode",mode:"local"}}export{M as createResolver,k as selectResolver};
@@ -1,281 +1,12 @@
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 - Secure Config
15
- *
16
- * Handles reading and writing config.json with encrypted license key.
17
- * Uses machine fingerprint as encryption seed so the key is bound
18
- * to the physical machine.
19
- *
20
- * Story 61.2 - F2 remediation: license key no longer stored in plaintext.
21
- *
22
- * Migration: if config has plaintext `licenseKey`, it is silently
23
- * migrated to `encryptedLicenseKey` on first read.
24
- *
25
- * If decryption fails (e.g. hardware change), returns null for
26
- * licenseKey, requiring re-activation.
27
- */
28
- import { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs';
29
- import { execSync } from 'node:child_process';
30
- import { join } from 'node:path';
31
- import { encrypt, decrypt } from '../cache/crypto-utils.js';
32
- import { getMachineFingerprint } from '../machine/fingerprint.js';
33
- import { DEFAULT_SERVER_URL } from '../constants.js';
34
- import { neocortexProfileDirectory } from './profile-directory.js';
35
- // ── Constants ────────────────────────────────────────────────────────────
36
- const CONFIG_DIR = neocortexProfileDirectory();
37
- const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
38
- const LEGACY_API_HOST = ['api', 'neocortex', 'ornexus', 'com'].join('.');
39
- // ── Types ────────────────────────────────────────────────────────────────
40
- /** Current config schema version (Epic 62 - FR8) */
41
- const CURRENT_CONFIG_VERSION = 1;
42
- // ── License Key Encryption ──────────────────────────────────────────────
43
- /**
44
- * Encrypt a license key using the machine fingerprint as passphrase.
45
- * Returns the encrypted envelope string.
46
- */
47
- export function encryptLicenseKey(licenseKey, options = {}) {
48
- const fingerprint = getMachineFingerprint(options);
49
- return encrypt(licenseKey, fingerprint);
50
- }
51
- /**
52
- * Decrypt a license key using the machine fingerprint as passphrase.
53
- * Returns the plaintext key or null if decryption fails (hardware changed).
54
- */
55
- export function decryptLicenseKey(encryptedKey, options = {}) {
56
- try {
57
- const fingerprint = getMachineFingerprint(options);
58
- const result = decrypt(encryptedKey, fingerprint);
59
- // expired flag is not relevant for license keys (no TTL)
60
- return result.plaintext;
61
- }
62
- catch {
63
- return null;
64
- }
65
- }
66
- // ── Secure File Permissions ─────────────────────────────────────────────
67
- /**
68
- * Set restrictive file permissions on config files.
69
- * Unix: chmod 600 (owner read/write only).
70
- * Windows: icacls to remove inheritance and grant Full Control only to current user.
71
- * Story 61.4 - F4 remediation.
72
- * Story 66.1 - Windows ACL via icacls.
73
- */
74
- export function setSecureFilePermissions(filePath) {
75
- try {
76
- if (process.platform === 'win32') {
77
- const username = process.env.USERNAME || process.env.USER || '';
78
- if (!username)
79
- return;
80
- execSync(`icacls "${filePath}" /inheritance:r /grant:r "${username}:(F)"`, { stdio: 'pipe', timeout: 5000 });
81
- }
82
- else {
83
- chmodSync(filePath, 0o600);
84
- }
85
- }
86
- catch {
87
- // Fail-open: ACL/chmod is hardening, not blocking
88
- }
89
- }
90
- /**
91
- * Set restrictive directory permissions on config directories.
92
- * Unix: chmod 700 (owner read/write/execute only).
93
- * Windows: icacls with (OI)(CI) for propagation to child objects.
94
- * Story 61.4 - F4 remediation.
95
- * Story 66.1 - Windows ACL via icacls.
96
- */
97
- export function setSecureDirPermissions(dirPath) {
98
- try {
99
- if (process.platform === 'win32') {
100
- const username = process.env.USERNAME || process.env.USER || '';
101
- if (!username)
102
- return;
103
- execSync(`icacls "${dirPath}" /inheritance:r /grant:r "${username}:(OI)(CI)(F)"`, { stdio: 'pipe', timeout: 5000 });
104
- }
105
- else {
106
- chmodSync(dirPath, 0o700);
107
- }
108
- }
109
- catch {
110
- // Fail-open: ACL/chmod is hardening, not blocking
111
- }
112
- }
113
- // ── Localhost Warning ────────────────────────────────────────────────────
114
- /**
115
- * Story 32.08: Warn if serverUrl points to localhost.
116
- * Informative only -- does NOT modify config.
117
- */
118
- let localhostWarningShown = false;
119
- function warnIfLocalhost(config) {
120
- if (localhostWarningShown)
121
- return;
122
- const url = config.serverUrl;
123
- if (!url)
124
- return;
125
- const isLocal = /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(url);
126
- if (isLocal) {
127
- localhostWarningShown = true;
128
- console.warn('\n[!] Warning: connected to local server (' + url + ').\n' +
129
- ' To use production, run: neocortex activate YOUR-LICENSE-KEY\n' +
130
- ' Get yours at https://neocortex.sh/portal/login\n');
131
- }
132
- }
133
- function repairLegacyApiHost(serverUrl) {
134
- const match = serverUrl.match(/^(https?:\/\/)([^/]+)(.*)$/i);
135
- if (!match)
136
- return null;
137
- const [, protocol, host, rest = ''] = match;
138
- if (host.toLowerCase() !== LEGACY_API_HOST)
139
- return null;
140
- return `${protocol}api.neocortex.sh${rest}`;
141
- }
142
- // ── Config Read/Write ───────────────────────────────────────────────────
143
- /**
144
- * Load config from ~/.neocortex/config.json with automatic migration.
145
- *
146
- * If the config contains a plaintext `licenseKey` (old format), it is:
147
- * 1. Encrypted using machine fingerprint
148
- * 2. Stored as `encryptedLicenseKey`
149
- * 3. Old `licenseKey` field removed
150
- * 4. Config rewritten to disk
151
- *
152
- * If decryption of `encryptedLicenseKey` fails (hardware change),
153
- * returns config with licenseKey = undefined.
154
- */
155
- export function loadSecureConfig(options = {}) {
156
- try {
157
- if (!existsSync(CONFIG_FILE))
158
- return null;
159
- const raw = readFileSync(CONFIG_FILE, 'utf-8');
160
- // Strip UTF-8 BOM if present (PowerShell 5.1 writes BOM via Out-File -Encoding utf8)
161
- // Defense in depth: handles configs written by old PS 5.1 installers (Epic 63 - Story 63.1)
162
- const config = JSON.parse(raw.replace(/^\uFEFF/, ''));
163
- // Migration path: plaintext licenseKey -> encrypted
164
- if (config.licenseKey && !config.encryptedLicenseKey) {
165
- const encrypted = encryptLicenseKey(config.licenseKey, options);
166
- const migratedConfig = { ...config };
167
- const plainKey = migratedConfig.licenseKey;
168
- delete migratedConfig.licenseKey;
169
- migratedConfig.encryptedLicenseKey = encrypted;
170
- // Ensure configVersion is preserved or added during migration
171
- if (!migratedConfig.configVersion) {
172
- migratedConfig.configVersion = CURRENT_CONFIG_VERSION;
173
- }
174
- // A strict inspection may consume legacy credentials, but it must never
175
- // turn that read into an implicit config migration. Ordinary invocations
176
- // retain the existing one-time migration behavior.
177
- if (!options.strictReadOnly)
178
- writeSecureConfig(migratedConfig);
179
- return {
180
- serverUrl: config.serverUrl,
181
- mode: config.mode,
182
- machineId: config.machineId,
183
- activatedAt: config.activatedAt,
184
- tier: config.tier,
185
- licenseKey: plainKey,
186
- keyType: config.keyType,
187
- };
188
- }
189
- // Decrypt encrypted license key
190
- let licenseKey;
191
- if (config.encryptedLicenseKey) {
192
- const decrypted = decryptLicenseKey(config.encryptedLicenseKey, options);
193
- if (decrypted) {
194
- licenseKey = decrypted;
195
- }
196
- // If decryption fails, licenseKey remains undefined -> requires re-activation
197
- // Story P26.06 below handles the fingerprint change warning
198
- }
199
- const result = {
200
- serverUrl: config.serverUrl,
201
- mode: config.mode,
202
- machineId: config.machineId,
203
- activatedAt: config.activatedAt,
204
- tier: config.tier,
205
- licenseKey,
206
- keyType: config.keyType,
207
- };
208
- // Story P26.04 + P26.06: Detect fingerprint change early and warn
209
- // This catches the issue BEFORE the user tries to invoke and gets a confusing error
210
- if (config.machineId && !licenseKey && config.encryptedLicenseKey) {
211
- const currentFp = getMachineFingerprint(options);
212
- if (config.machineId !== currentFp) {
213
- console.warn(`\n[!] Machine fingerprint changed (was: ${config.machineId.slice(0, 12)}..., now: ${currentFp.slice(0, 12)}...).` +
214
- '\n Your encrypted credentials are no longer valid.' +
215
- '\n Re-activate with: neocortex activate YOUR-LICENSE-KEY\n');
216
- }
217
- }
218
- // Story 32.08: Warn if serverUrl points to localhost
219
- warnIfLocalhost(result);
220
- // Story 70.05: Auto-repair localhost serverUrl if not intentional.
221
- // If serverUrl points to localhost and NEOCORTEX_SERVER_URL env is not set
222
- // to localhost (i.e., user didn't explicitly request local), repair to production.
223
- // This is an in-memory repair only -- does NOT rewrite the config file on disk.
224
- if (result.serverUrl && !process.env['NEOCORTEX_SERVER_URL']) {
225
- const isLocal = /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(result.serverUrl);
226
- if (isLocal) {
227
- const repairedUrl = DEFAULT_SERVER_URL;
228
- console.warn(`[neocortex] Auto-repairing serverUrl: ${result.serverUrl} -> ${repairedUrl}\n` +
229
- `[neocortex] To keep localhost, set NEOCORTEX_SERVER_URL=${result.serverUrl}\n`);
230
- return { ...result, serverUrl: repairedUrl };
231
- }
232
- }
233
- // Story P46.02: Auto-repair deprecated API host to neocortex.sh.
234
- // New installs should use the canonical api.neocortex.sh. In-memory only -- does NOT rewrite disk.
235
- // Suppressed by NEOCORTEX_SERVER_URL env var (developer override).
236
- if (result.serverUrl && !process.env['NEOCORTEX_SERVER_URL']) {
237
- const repairedUrl = repairLegacyApiHost(result.serverUrl);
238
- if (repairedUrl) {
239
- return { ...result, serverUrl: repairedUrl };
240
- }
241
- }
242
- return result;
243
- }
244
- catch {
245
- return null;
246
- }
247
- }
248
- /**
249
- * Write config to disk with encrypted license key and secure permissions.
250
- * The licenseKey field should already be encrypted as encryptedLicenseKey.
251
- */
252
- function writeSecureConfig(config) {
253
- mkdirSync(CONFIG_DIR, { recursive: true });
254
- setSecureDirPermissions(CONFIG_DIR);
255
- const cacheDir = join(CONFIG_DIR, 'cache');
256
- if (existsSync(cacheDir)) {
257
- setSecureDirPermissions(cacheDir);
258
- }
259
- writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + '\n', 'utf-8');
260
- setSecureFilePermissions(CONFIG_FILE);
261
- }
262
- /**
263
- * Save config after activation with encrypted license key.
264
- * This is the primary write path called from activate.ts.
265
- */
266
- export function saveSecureConfig(config) {
267
- const encrypted = encryptLicenseKey(config.licenseKey);
268
- // Auto-detect keyType from key prefix if not explicitly provided
269
- const keyType = config.keyType ?? (config.licenseKey.startsWith('nxk_') ? 'api_key' : 'license');
270
- const diskConfig = {
271
- configVersion: CURRENT_CONFIG_VERSION,
272
- serverUrl: config.serverUrl,
273
- mode: config.mode,
274
- machineId: config.machineId,
275
- activatedAt: config.activatedAt,
276
- tier: config.tier,
277
- encryptedLicenseKey: encrypted,
278
- keyType,
279
- };
280
- writeSecureConfig(diskConfig);
281
- }
1
+ import{existsSync as p,readFileSync as R,writeFileSync as S,mkdirSync as L,chmodSync as y}from"node:fs";import{execSync as u}from"node:child_process";import{join as d}from"node:path";import{encrypt as I,decrypt as g}from"../cache/crypto-utils.js";import{getMachineFingerprint as l}from"../machine/fingerprint.js";import{DEFAULT_SERVER_URL as x}from"../constants.js";import{neocortexProfileDirectory as K}from"./profile-directory.js";const s=K(),a=d(s,"config.json"),C=["api","neocortex","ornexus","com"].join("."),f=1;function m(r,t={}){const e=l(t);return I(r,e)}function O(r,t={}){try{const e=l(t);return g(r,e).plaintext}catch{return null}}function _(r){try{if(process.platform==="win32"){const t=process.env.USERNAME||process.env.USER||"";if(!t)return;u(`icacls "${r}" /inheritance:r /grant:r "${t}:(F)"`,{stdio:"pipe",timeout:5e3})}else y(r,384)}catch{}}function h(r){try{if(process.platform==="win32"){const t=process.env.USERNAME||process.env.USER||"";if(!t)return;u(`icacls "${r}" /inheritance:r /grant:r "${t}:(OI)(CI)(F)"`,{stdio:"pipe",timeout:5e3})}else y(r,448)}catch{}}let v=!1;function F(r){if(v)return;const t=r.serverUrl;if(!t)return;/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(t)&&(v=!0,console.warn(`
2
+ [!] Warning: connected to local server (`+t+`).
3
+ To use production, run: neocortex activate YOUR-LICENSE-KEY
4
+ Get yours at https://neocortex.sh/portal/login
5
+ `))}function w(r){const t=r.match(/^(https?:\/\/)([^/]+)(.*)$/i);if(!t)return null;const[,e,o,n=""]=t;return o.toLowerCase()!==C?null:`${e}api.neocortex.sh${n}`}function D(r={}){try{if(!p(a))return null;const t=R(a,"utf-8"),e=JSON.parse(t.replace(/^\uFEFF/,""));if(e.licenseKey&&!e.encryptedLicenseKey){const c=m(e.licenseKey,r),i={...e},U=i.licenseKey;return delete i.licenseKey,i.encryptedLicenseKey=c,i.configVersion||(i.configVersion=f),r.strictReadOnly||E(i),{serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:U,keyType:e.keyType}}let o;if(e.encryptedLicenseKey){const c=O(e.encryptedLicenseKey,r);c&&(o=c)}const n={serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:o,keyType:e.keyType};if(e.machineId&&!o&&e.encryptedLicenseKey){const c=l(r);e.machineId!==c&&console.warn(`
6
+ [!] Machine fingerprint changed (was: ${e.machineId.slice(0,12)}..., now: ${c.slice(0,12)}...).
7
+ Your encrypted credentials are no longer valid.
8
+ Re-activate with: neocortex activate YOUR-LICENSE-KEY
9
+ `)}if(F(n),n.serverUrl&&!process.env.NEOCORTEX_SERVER_URL&&/^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d+)?/i.test(n.serverUrl)){const i=x;return console.warn(`[neocortex] Auto-repairing serverUrl: ${n.serverUrl} -> ${i}
10
+ [neocortex] To keep localhost, set NEOCORTEX_SERVER_URL=${n.serverUrl}
11
+ `),{...n,serverUrl:i}}if(n.serverUrl&&!process.env.NEOCORTEX_SERVER_URL){const c=w(n.serverUrl);if(c)return{...n,serverUrl:c}}return n}catch{return null}}function E(r){L(s,{recursive:!0}),h(s);const t=d(s,"cache");p(t)&&h(t),S(a,JSON.stringify(r,null,2)+`
12
+ `,"utf-8"),_(a)}function G(r){const t=m(r.licenseKey),e=r.keyType??(r.licenseKey.startsWith("nxk_")?"api_key":"license"),o={configVersion:f,serverUrl:r.serverUrl,mode:r.mode,machineId:r.machineId,activatedAt:r.activatedAt,tier:r.tier,encryptedLicenseKey:t,keyType:e};E(o)}export{O as decryptLicenseKey,m as encryptLicenseKey,D as loadSecureConfig,G as saveSecureConfig,h as setSecureDirPermissions,_ as setSecureFilePermissions};