@ornexus/neocortex 4.60.73 → 4.60.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  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 -212
  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 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  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 -358
  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 +143 -7200
  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 -156
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  75. package/packages/client/dist/config/profile-directory.js +1 -13
  76. package/packages/client/dist/config/resolver-selection.js +1 -278
  77. package/packages/client/dist/config/secure-config.js +12 -281
  78. package/packages/client/dist/config.js +2 -223
  79. package/packages/client/dist/constants.js +1 -25
  80. package/packages/client/dist/context/context-collector.js +2 -222
  81. package/packages/client/dist/context/context-sanitizer.js +1 -145
  82. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  83. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  84. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  85. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  86. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  87. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  88. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  90. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  91. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  92. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  93. package/packages/client/dist/continuity/outbox.js +1 -117
  94. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  95. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  96. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  97. package/packages/client/dist/errors/error-messages.js +2 -228
  98. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  99. package/packages/client/dist/evidence/collector.js +1 -347
  100. package/packages/client/dist/evidence/index.js +1 -1
  101. package/packages/client/dist/evidence/types.js +0 -2
  102. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  103. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  104. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  105. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  106. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  107. package/packages/client/dist/git/epic-operational-state.js +2 -672
  108. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  109. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  110. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  113. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  117. package/packages/client/dist/i18n/first-run.js +2 -60
  118. package/packages/client/dist/index.js +1 -47
  119. package/packages/client/dist/invocation/invoke-input.js +1 -24
  120. package/packages/client/dist/license/index.js +1 -5
  121. package/packages/client/dist/license/license-client.js +1 -304
  122. package/packages/client/dist/machine/fingerprint.js +2 -163
  123. package/packages/client/dist/machine/index.js +1 -5
  124. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  125. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  126. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  127. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  128. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  129. package/packages/client/dist/migrations/project-identity.js +7 -493
  130. package/packages/client/dist/migrations/state-json.js +4 -393
  131. package/packages/client/dist/policy/architecture-policy.js +2 -184
  132. package/packages/client/dist/policy/index.js +1 -7
  133. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  134. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  135. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  136. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  137. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  138. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  139. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  140. package/packages/client/dist/private-execution/delivery.js +13 -410
  141. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  142. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  143. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  144. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  145. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  146. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  147. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  148. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  149. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  150. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  151. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  152. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  153. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  154. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  155. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  156. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  157. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  158. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  159. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  160. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  161. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  162. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  163. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  164. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  165. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  166. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  167. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  168. package/packages/client/dist/private-execution/session-lease.js +1 -63
  169. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  170. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  171. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  172. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  173. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  174. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  175. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  176. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  177. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  178. package/packages/client/dist/resilience/index.js +1 -8
  179. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  180. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  181. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  182. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  183. package/packages/client/dist/runner/binary.js +1 -404
  184. package/packages/client/dist/runner/cli.js +17 -1571
  185. package/packages/client/dist/runner/headless/adapters.js +1 -49
  186. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  187. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  188. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  189. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  190. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  191. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  192. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  193. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +18 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  195. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  196. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  197. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  198. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  199. package/packages/client/dist/runner/headless/resolver.js +1 -231
  200. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  201. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  202. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  203. package/packages/client/dist/runner/headless/types.js +2 -574
  204. package/packages/client/dist/runner/local-console.js +13 -396
  205. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  206. package/packages/client/dist/runner/project-identity.js +1 -106
  207. package/packages/client/dist/runner/scheduler.js +7 -995
  208. package/packages/client/dist/runner-cli.js +2 -18
  209. package/packages/client/dist/state/invocation-shape.js +1 -13
  210. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  211. package/packages/client/dist/state/state-json-repair.js +3 -785
  212. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  213. package/packages/client/dist/telemetry/index.js +1 -5
  214. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  215. package/packages/client/dist/tier/index.js +1 -5
  216. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  217. package/packages/client/dist/types/index.js +1 -38
  218. package/packages/client/dist/version.js +1 -27
  219. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  220. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  221. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  222. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  223. package/packages/client/dist/yoloop/index.js +1 -8
  224. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  225. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  226. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  227. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  228. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  229. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  230. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  231. package/targets-stubs/antigravity/gemini.md +1 -1
  232. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  233. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  234. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  235. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex.md +2 -2
  237. package/targets-stubs/codex/AGENTS.md +1 -1
  238. package/targets-stubs/cursor/agent.md +2 -2
  239. package/targets-stubs/gemini-cli/agent.md +2 -2
  240. package/targets-stubs/opencode/neocortex-root.md +1 -1
  241. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,394 +1,8 @@
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 - Activate Command
15
- *
16
- * Manages license activation for the Neocortex CLI.
17
- * Validates license key with the IP Protection Server,
18
- * caches JWT token, and creates user config file.
19
- *
20
- * Story 43.3 - AC1, AC3, AC4, AC5
21
- */
22
- import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
23
- import { join, dirname } from 'node:path';
24
- import { homedir } from 'node:os';
25
- import { fileURLToPath } from 'node:url';
26
- import { LicenseClient } from '../license/license-client.js';
27
- import { EncryptedCache } from '../cache/encrypted-cache.js';
28
- import { getMachineFingerprint } from '../machine/fingerprint.js';
29
- import { updateAgentDescription } from '../agent/update-description.js';
30
- import { refreshStubs } from '../agent/refresh-stubs.js';
31
- import { updateAgentYaml } from '../agent/update-agent-yaml.js';
32
- import { saveSecureConfig, setSecureDirPermissions } from '../config/secure-config.js';
33
- import { DEFAULT_SERVER_URL } from '../constants.js';
34
- // ── Version Resolution ────────────────────────────────────────────────────
35
- function getInstalledVersion() {
36
- try {
37
- const thisFile = fileURLToPath(import.meta.url);
38
- let dir = dirname(thisFile);
39
- for (let i = 0; i < 5; i++) {
40
- try {
41
- const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8'));
42
- if (pkg.name === '@ornexus/neocortex' || pkg.name === '@neocortex/client') {
43
- return pkg.version ?? '0.0.0';
44
- }
45
- }
46
- catch { /* no package.json at this level */ }
47
- dir = dirname(dir);
48
- }
49
- }
50
- catch { /* fallback */ }
51
- return '0.0.0';
52
- }
53
- // ── Constants ─────────────────────────────────────────────────────────────
54
- const CONFIG_DIR = join(homedir(), '.neocortex');
55
- const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
56
- // License key format: NX-{F|P|E}-{24 hex}-{4 hex checksum}
57
- const LICENSE_KEY_PATTERN = /^NX-(F|P|E)-[a-f0-9]+-[a-f0-9]+$/i;
58
- // API key format: nxk_{24hex}_{4check} (new, P32) or nxk_{tier}_{24hex}_{4check} (legacy)
59
- const API_KEY_PATTERN = /^nxk_(?:[a-z]+_)?[a-f0-9]+_[a-f0-9]+$/;
60
- // ── Validation ────────────────────────────────────────────────────────────
61
- /**
62
- * Validate license key format.
63
- * Format: NX-{TIER}-{random}-{random}
64
- * Tiers: FREE, PRO, ENT
65
- */
66
- export function validateLicenseKeyFormat(key) {
67
- if (!key || key.trim().length === 0) {
68
- return { valid: false, error: 'License key cannot be empty' };
69
- }
70
- const trimmed = key.trim().toUpperCase();
71
- if (!trimmed.startsWith('NX-')) {
72
- return { valid: false, error: 'License key must start with "NX-"' };
73
- }
74
- if (!LICENSE_KEY_PATTERN.test(trimmed)) {
75
- return {
76
- valid: false,
77
- error: 'Invalid license key format. Expected: NX-{TIER}-{ID} (e.g., NX-PRO-ABC-123)',
78
- };
79
- }
80
- return { valid: true };
81
- }
82
- /**
83
- * Validate API key format.
84
- * Format: nxk_{tier}_{random}_{check}
85
- */
86
- export function validateApiKeyFormat(key) {
87
- if (!key || key.trim().length === 0) {
88
- return { valid: false, error: 'API key cannot be empty' };
89
- }
90
- const trimmed = key.trim();
91
- if (!trimmed.startsWith('nxk_')) {
92
- return { valid: false, error: 'API key must start with "nxk_"' };
93
- }
94
- if (trimmed.length < 20) {
95
- return { valid: false, error: 'API key is too short' };
96
- }
97
- if (!API_KEY_PATTERN.test(trimmed)) {
98
- return {
99
- valid: false,
100
- error: 'Invalid API key format. Expected: nxk_{id}_{check} (e.g., nxk_abc123def456...)',
101
- };
102
- }
103
- return { valid: true };
104
- }
105
- // ── Config Management ─────────────────────────────────────────────────────
106
- /**
107
- * Load existing user config, if any.
108
- */
109
- function loadExistingConfig() {
110
- try {
111
- if (existsSync(CONFIG_FILE)) {
112
- const raw = readFileSync(CONFIG_FILE, 'utf-8');
113
- return JSON.parse(raw);
114
- }
115
- }
116
- catch {
117
- // Corrupted config - will be overwritten
118
- }
119
- return null;
120
- }
121
- /**
122
- * Save user config after successful activation.
123
- * License key is encrypted using machine fingerprint (Story 61.2).
124
- * File permissions set to 600 (Story 61.4).
125
- */
126
- function saveConfig(config) {
127
- // Ensure directories exist with secure permissions
128
- mkdirSync(CONFIG_DIR, { recursive: true });
129
- setSecureDirPermissions(CONFIG_DIR);
130
- const cacheDir = join(CONFIG_DIR, 'cache');
131
- mkdirSync(cacheDir, { recursive: true });
132
- setSecureDirPermissions(cacheDir);
133
- if (config.licenseKey || config.apiKey) {
134
- // Use secure config writer which encrypts the key
135
- saveSecureConfig({
136
- serverUrl: config.serverUrl,
137
- mode: config.mode,
138
- machineId: config.machineId,
139
- activatedAt: config.activatedAt,
140
- tier: config.tier,
141
- licenseKey: (config.licenseKey ?? config.apiKey),
142
- });
143
- }
144
- else {
145
- // Fallback: write without key (should not happen in normal flow)
146
- const fallbackConfig = { configVersion: 1, ...config };
147
- writeFileSync(CONFIG_FILE, JSON.stringify(fallbackConfig, null, 2) + '\n', 'utf-8');
148
- }
149
- }
150
- // ── Activate Command ──────────────────────────────────────────────────────
151
- /**
152
- * Activate a Neocortex license.
153
- *
154
- * Flow:
155
- * 1. Validate license key format
156
- * 2. Call IP Protection Server to activate
157
- * 3. Cache JWT token via LicenseClient
158
- * 4. Create/update ~/.neocortex/config.json
159
- * 5. Return result with feedback
160
- */
161
- export async function activate(options) {
162
- const { licenseKey, serverUrl = DEFAULT_SERVER_URL } = options;
163
- // 1. Check if key is provided
164
- if (!licenseKey) {
165
- return {
166
- success: false,
167
- message: [
168
- 'No key provided.',
169
- '',
170
- 'Get your license key at https://neocortex.sh/portal/login',
171
- '',
172
- 'Usage:',
173
- ' neocortex activate YOUR-LICENSE-KEY',
174
- ' neocortex activate YOUR-API-KEY',
175
- ].join('\n'),
176
- };
177
- }
178
- const trimmedKey = licenseKey.trim();
179
- // 2. Detect key type: API key (nxk_) or license key (NX-)
180
- const isApiKey = trimmedKey.startsWith('nxk_');
181
- if (isApiKey) {
182
- // ── API Key Activation Flow (Story 22.04) ──────────────────────────
183
- const apiValidation = validateApiKeyFormat(trimmedKey);
184
- if (!apiValidation.valid) {
185
- return {
186
- success: false,
187
- message: `Invalid API key: ${apiValidation.error}`,
188
- };
189
- }
190
- // Extract tier from API key -- new format has no tier prefix, server returns tier in response
191
- const tierMatch = trimmedKey.match(/^nxk_(free|pro|ent)_/);
192
- const apiTierMap = { free: 'free', pro: 'pro', ent: 'enterprise' };
193
- const tier = tierMatch?.[1] ? (apiTierMap[tierMatch[1]] ?? 'unknown') : 'unknown'; // will be overridden by server response
194
- const machineId = getMachineFingerprint();
195
- const cliVersion = getInstalledVersion();
196
- // Call /api/v1/license/activate-key
197
- let response;
198
- try {
199
- const res = await fetch(`${serverUrl}/api/v1/license/activate-key`, {
200
- method: 'POST',
201
- headers: { 'Content-Type': 'application/json' },
202
- body: JSON.stringify({
203
- api_key: trimmedKey,
204
- machine_id: machineId,
205
- client_version: cliVersion,
206
- }),
207
- });
208
- if (!res.ok) {
209
- const body = await res.json().catch(() => ({}));
210
- const errorBody = body;
211
- return {
212
- success: false,
213
- message: `API key activation failed: ${errorBody.message ?? `HTTP ${res.status}`}`,
214
- };
215
- }
216
- response = await res.json();
217
- }
218
- catch {
219
- return {
220
- success: false,
221
- message: [
222
- 'Failed to connect to IP Protection Server.',
223
- '',
224
- 'Possible causes:',
225
- ` - Server at ${serverUrl} is unreachable`,
226
- ' - Network connectivity issue',
227
- '',
228
- 'Workaround: Use --local flag to run in local mode',
229
- ].join('\n'),
230
- };
231
- }
232
- const activatedTier = response.tier ?? tier;
233
- // Cache JWT token via EncryptedCache
234
- const cacheDir = join(CONFIG_DIR, 'cache');
235
- try {
236
- const encryptedCache = new EncryptedCache({
237
- cacheDir,
238
- passphrase: trimmedKey,
239
- });
240
- await encryptedCache.set('neocortex:jwt:token', response.token, response.expires_in * 1000);
241
- }
242
- catch {
243
- // Cache is non-critical (fail-open)
244
- }
245
- // Save config with API key
246
- const config = {
247
- serverUrl,
248
- mode: 'remote',
249
- machineId,
250
- activatedAt: new Date().toISOString(),
251
- tier: activatedTier,
252
- apiKey: trimmedKey,
253
- };
254
- try {
255
- saveConfig(config);
256
- }
257
- catch (err) {
258
- return {
259
- success: false,
260
- message: `Failed to save configuration: ${err instanceof Error ? err.message : 'unknown error'}`,
261
- };
262
- }
263
- // Refresh stubs and agent description
264
- const stubsRefreshed = refreshStubs(cliVersion, { forceCreate: true, targetFilter: 'claude-code' })
265
- + refreshStubs(cliVersion);
266
- updateAgentDescription(cliVersion, activatedTier);
267
- updateAgentYaml(cliVersion, activatedTier);
268
- return {
269
- success: true,
270
- message: [
271
- 'Neocortex activated successfully.',
272
- '',
273
- 'Open your preferred platform (Claude Code, Cursor, VS Code, etc.)',
274
- 'and reference the Neocortex agent.',
275
- ...(stubsRefreshed > 0
276
- ? ['', 'Managed agent wrappers were refreshed while preserving existing Markdown frontmatter and unrelated platform files.']
277
- : []),
278
- '',
279
- 'Use *menu to see available commands or check the Docs in your Dashboard.',
280
- ].join('\n'),
281
- tier: activatedTier,
282
- serverUrl,
283
- configPath: CONFIG_FILE,
284
- };
285
- }
286
- // ── License Key Activation Flow (existing) ──────────────────────────────
287
- const validation = validateLicenseKeyFormat(trimmedKey);
288
- if (!validation.valid) {
289
- return {
290
- success: false,
291
- message: `Invalid license key: ${validation.error}`,
292
- };
293
- }
294
- const normalizedKey = trimmedKey;
295
- // Extract tier from key
296
- const tierMatch = normalizedKey.match(/^NX-(F|P|E)-/i);
297
- const tierMap = { F: 'free', P: 'pro', E: 'enterprise' };
298
- const tier = tierMatch?.[1] ? (tierMap[tierMatch[1].toUpperCase()] ?? 'unknown') : 'unknown';
299
- // Attempt activation via LicenseClient with EncryptedCache
300
- const cacheDir = join(CONFIG_DIR, 'cache');
301
- const encryptedCache = new EncryptedCache({
302
- cacheDir,
303
- passphrase: normalizedKey,
304
- });
305
- const client = new LicenseClient({
306
- serverUrl,
307
- licenseKey: normalizedKey,
308
- cacheProvider: encryptedCache,
309
- });
310
- let activationResult;
311
- try {
312
- activationResult = await client.activate();
313
- }
314
- catch {
315
- return {
316
- success: false,
317
- message: [
318
- 'Failed to connect to IP Protection Server.',
319
- '',
320
- 'Possible causes:',
321
- ` - Server at ${serverUrl} is unreachable`,
322
- ' - Network connectivity issue',
323
- ' - Server is still being deployed',
324
- '',
325
- 'Workaround: Use --local flag to run in local mode',
326
- ].join('\n'),
327
- };
328
- }
329
- if (!activationResult) {
330
- return {
331
- success: false,
332
- message: [
333
- 'License activation failed.',
334
- '',
335
- 'Possible causes:',
336
- ' - Invalid or expired license key',
337
- ' - License already activated on another machine',
338
- ' - Server rejected the activation request',
339
- '',
340
- 'Check your license key and try again.',
341
- 'Contact support if the problem persists.',
342
- ].join('\n'),
343
- };
344
- }
345
- // An admin upgrade changes the server license tier without rotating the
346
- // original NX-F/NX-P key. The validated activation response is authoritative;
347
- // the prefix remains only a compatibility fallback for older servers.
348
- const activatedTier = activationResult.tier ?? tier;
349
- // Save config with license key for invoke re-authentication
350
- const config = {
351
- serverUrl,
352
- mode: 'remote',
353
- machineId: getMachineFingerprint(),
354
- activatedAt: new Date().toISOString(),
355
- tier: activatedTier,
356
- licenseKey: normalizedKey,
357
- };
358
- try {
359
- saveConfig(config);
360
- }
361
- catch (err) {
362
- return {
363
- success: false,
364
- message: `Failed to save config to ${CONFIG_FILE}: ${err instanceof Error ? err.message : String(err)}`,
365
- };
366
- }
367
- // Refresh Claude plus any other existing targets when versions differ.
368
- const cliVersion = getInstalledVersion();
369
- const stubsRefreshed = refreshStubs(cliVersion, {
370
- forceCreate: true,
371
- targetFilter: 'claude-code',
372
- }) + refreshStubs(cliVersion);
373
- // Update agent description with activated tier and version
374
- updateAgentDescription(cliVersion, activatedTier);
375
- // Update agent YAML with version and tier (Story 55.2)
376
- updateAgentYaml(cliVersion, activatedTier);
377
- return {
378
- success: true,
379
- message: [
380
- 'Neocortex activated successfully.',
381
- '',
382
- 'Open your preferred platform (Claude Code, Cursor, VS Code, etc.)',
383
- 'and reference the Neocortex agent.',
384
- ...(stubsRefreshed > 0
385
- ? ['', 'Managed agent wrappers were refreshed while preserving existing Markdown frontmatter and unrelated platform files.']
386
- : []),
387
- '',
388
- 'Use *menu to see available commands or check the Docs in your Dashboard.',
389
- ].join('\n'),
390
- tier: activatedTier,
391
- serverUrl,
392
- configPath: CONFIG_FILE,
393
- };
394
- }
1
+ import{existsSync as Y,mkdirSync as x,writeFileSync as X,readFileSync as I}from"node:fs";import{join as i,dirname as C}from"node:path";import{homedir as W}from"node:os";import{fileURLToPath as J}from"node:url";import{LicenseClient as B}from"../license/license-client.js";import{EncryptedCache as P}from"../cache/encrypted-cache.js";import{getMachineFingerprint as S}from"../machine/fingerprint.js";import{updateAgentDescription as E}from"../agent/update-description.js";import{refreshStubs as h}from"../agent/refresh-stubs.js";import{updateAgentYaml as N}from"../agent/update-agent-yaml.js";import{saveSecureConfig as G,setSecureDirPermissions as _}from"../config/secure-config.js";import{DEFAULT_SERVER_URL as z}from"../constants.js";function b(){try{const e=J(import.meta.url);let t=C(e);for(let r=0;r<5;r++){try{const n=JSON.parse(I(i(t,"package.json"),"utf-8"));if(n.name==="@ornexus/neocortex"||n.name==="@neocortex/client")return n.version??"0.0.0"}catch{}t=C(t)}}catch{}return"0.0.0"}const o=i(W(),".neocortex"),c=i(o,"config.json"),q=/^NX-(F|P|E)-[a-f0-9]+-[a-f0-9]+$/i,H=/^nxk_(?:[a-z]+_)?[a-f0-9]+_[a-f0-9]+$/;function Q(e){if(!e||e.trim().length===0)return{valid:!1,error:"License key cannot be empty"};const t=e.trim().toUpperCase();return t.startsWith("NX-")?q.test(t)?{valid:!0}:{valid:!1,error:"Invalid license key format. Expected: NX-{TIER}-{ID} (e.g., NX-PRO-ABC-123)"}:{valid:!1,error:'License key must start with "NX-"'}}function Z(e){if(!e||e.trim().length===0)return{valid:!1,error:"API key cannot be empty"};const t=e.trim();return t.startsWith("nxk_")?t.length<20?{valid:!1,error:"API key is too short"}:H.test(t)?{valid:!0}:{valid:!1,error:"Invalid API key format. Expected: nxk_{id}_{check} (e.g., nxk_abc123def456...)"}:{valid:!1,error:'API key must start with "nxk_"'}}function he(){try{if(Y(c)){const e=I(c,"utf-8");return JSON.parse(e)}}catch{}return null}function A(e){x(o,{recursive:!0}),_(o);const t=i(o,"cache");if(x(t,{recursive:!0}),_(t),e.licenseKey||e.apiKey)G({serverUrl:e.serverUrl,mode:e.mode,machineId:e.machineId,activatedAt:e.activatedAt,tier:e.tier,licenseKey:e.licenseKey??e.apiKey});else{const r={configVersion:1,...e};X(c,JSON.stringify(r,null,2)+`
2
+ `,"utf-8")}}async function ye(e){const{licenseKey:t,serverUrl:r=z}=e;if(!t)return{success:!1,message:["No key provided.","","Get your license key at https://neocortex.sh/portal/login","","Usage:"," neocortex activate YOUR-LICENSE-KEY"," neocortex activate YOUR-API-KEY"].join(`
3
+ `)};const n=t.trim();if(n.startsWith("nxk_")){const s=Z(n);if(!s.valid)return{success:!1,message:`Invalid API key: ${s.error}`};const k=n.match(/^nxk_(free|pro|ent)_/),T={free:"free",pro:"pro",ent:"enterprise"},L=k?.[1]?T[k[1]]??"unknown":"unknown",w=S(),l=b();let m;try{const a=await fetch(`${r}/api/v1/license/activate-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:n,machine_id:w,client_version:l})});if(!a.ok)return{success:!1,message:`API key activation failed: ${(await a.json().catch(()=>({}))).message??`HTTP ${a.status}`}`};m=await a.json()}catch{return{success:!1,message:["Failed to connect to IP Protection Server.","","Possible causes:",` - Server at ${r} is unreachable`," - Network connectivity issue","","Workaround: Use --local flag to run in local mode"].join(`
4
+ `)}}const p=m.tier??L,$=i(o,"cache");try{await new P({cacheDir:$,passphrase:n}).set("neocortex:jwt:token",m.token,m.expires_in*1e3)}catch{}const M={serverUrl:r,mode:"remote",machineId:w,activatedAt:new Date().toISOString(),tier:p,apiKey:n};try{A(M)}catch(a){return{success:!1,message:`Failed to save configuration: ${a instanceof Error?a.message:"unknown error"}`}}const V=h(l,{forceCreate:!0,targetFilter:"claude-code"})+h(l);return E(l,p),N(l,p),{success:!0,message:["Neocortex activated successfully.","","Open your preferred platform (Claude Code, Cursor, VS Code, etc.)","and reference the Neocortex agent.",...V>0?["","Managed agent wrappers were refreshed while preserving existing Markdown frontmatter and unrelated platform files."]:[],"","Use *menu to see available commands or check the Docs in your Dashboard."].join(`
5
+ `),tier:p,serverUrl:r,configPath:c}}const v=Q(n);if(!v.valid)return{success:!1,message:`Invalid license key: ${v.error}`};const d=n,g=d.match(/^NX-(F|P|E)-/i),F={F:"free",P:"pro",E:"enterprise"},K=g?.[1]?F[g[1].toUpperCase()]??"unknown":"unknown",U=i(o,"cache"),j=new P({cacheDir:U,passphrase:d}),D=new B({serverUrl:r,licenseKey:d,cacheProvider:j});let y;try{y=await D.activate()}catch{return{success:!1,message:["Failed to connect to IP Protection Server.","","Possible causes:",` - Server at ${r} is unreachable`," - Network connectivity issue"," - Server is still being deployed","","Workaround: Use --local flag to run in local mode"].join(`
6
+ `)}}if(!y)return{success:!1,message:["License activation failed.","","Possible causes:"," - Invalid or expired license key"," - License already activated on another machine"," - Server rejected the activation request","","Check your license key and try again.","Contact support if the problem persists."].join(`
7
+ `)};const u=y.tier??K,O={serverUrl:r,mode:"remote",machineId:S(),activatedAt:new Date().toISOString(),tier:u,licenseKey:d};try{A(O)}catch(s){return{success:!1,message:`Failed to save config to ${c}: ${s instanceof Error?s.message:String(s)}`}}const f=b(),R=h(f,{forceCreate:!0,targetFilter:"claude-code"})+h(f);return E(f,u),N(f,u),{success:!0,message:["Neocortex activated successfully.","","Open your preferred platform (Claude Code, Cursor, VS Code, etc.)","and reference the Neocortex agent.",...R>0?["","Managed agent wrappers were refreshed while preserving existing Markdown frontmatter and unrelated platform files."]:[],"","Use *menu to see available commands or check the Docs in your Dashboard."].join(`
8
+ `),tier:u,serverUrl:r,configPath:c}}export{ye as activate,Z as validateApiKeyFormat,Q as validateLicenseKeyFormat};