@ornexus/neocortex 4.60.16

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 (235) hide show
  1. package/LICENSE +56 -0
  2. package/LICENSE-COMMERCIAL.md +70 -0
  3. package/README.md +58 -0
  4. package/dist/sbom.cdx.json +11159 -0
  5. package/docs/install/coderabbit-manual-setup.md +86 -0
  6. package/docs/install/installer-diagnostics.md +107 -0
  7. package/docs/install/linux-global-install.md +97 -0
  8. package/install.js +572 -0
  9. package/install.ps1 +2214 -0
  10. package/install.sh +2013 -0
  11. package/package.json +132 -0
  12. package/packages/client/dist/adapters/adapter-registry.d.ts +61 -0
  13. package/packages/client/dist/adapters/adapter-registry.js +1 -0
  14. package/packages/client/dist/adapters/antigravity-adapter.d.ts +18 -0
  15. package/packages/client/dist/adapters/antigravity-adapter.js +2 -0
  16. package/packages/client/dist/adapters/claude-code-adapter.d.ts +19 -0
  17. package/packages/client/dist/adapters/claude-code-adapter.js +3 -0
  18. package/packages/client/dist/adapters/codex-adapter.d.ts +19 -0
  19. package/packages/client/dist/adapters/codex-adapter.js +2 -0
  20. package/packages/client/dist/adapters/cursor-adapter.d.ts +19 -0
  21. package/packages/client/dist/adapters/cursor-adapter.js +4 -0
  22. package/packages/client/dist/adapters/gemini-adapter.d.ts +18 -0
  23. package/packages/client/dist/adapters/gemini-adapter.js +2 -0
  24. package/packages/client/dist/adapters/index.d.ts +19 -0
  25. package/packages/client/dist/adapters/index.js +1 -0
  26. package/packages/client/dist/adapters/platform-detector.d.ts +48 -0
  27. package/packages/client/dist/adapters/platform-detector.js +1 -0
  28. package/packages/client/dist/adapters/target-adapter.d.ts +70 -0
  29. package/packages/client/dist/adapters/target-adapter.js +0 -0
  30. package/packages/client/dist/adapters/vscode-adapter.d.ts +19 -0
  31. package/packages/client/dist/adapters/vscode-adapter.js +2 -0
  32. package/packages/client/dist/agent/refresh-stubs.d.ts +90 -0
  33. package/packages/client/dist/agent/refresh-stubs.js +2 -0
  34. package/packages/client/dist/agent/update-agent-yaml.d.ts +26 -0
  35. package/packages/client/dist/agent/update-agent-yaml.js +1 -0
  36. package/packages/client/dist/agent/update-description.d.ts +45 -0
  37. package/packages/client/dist/agent/update-description.js +1 -0
  38. package/packages/client/dist/cache/crypto-utils.d.ts +30 -0
  39. package/packages/client/dist/cache/crypto-utils.js +1 -0
  40. package/packages/client/dist/cache/encrypted-cache.d.ts +30 -0
  41. package/packages/client/dist/cache/encrypted-cache.js +1 -0
  42. package/packages/client/dist/cache/in-memory-asset-cache.d.ts +62 -0
  43. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -0
  44. package/packages/client/dist/cache/index.d.ts +13 -0
  45. package/packages/client/dist/cache/index.js +1 -0
  46. package/packages/client/dist/cache/protected-pi-boundary.d.ts +19 -0
  47. package/packages/client/dist/cache/protected-pi-boundary.js +1 -0
  48. package/packages/client/dist/checkpoint/checkpoint-client-reader.d.ts +45 -0
  49. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -0
  50. package/packages/client/dist/checkpoint/index.d.ts +12 -0
  51. package/packages/client/dist/checkpoint/index.js +1 -0
  52. package/packages/client/dist/checkpoint/shared-checkpoint-types.d.ts +85 -0
  53. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -0
  54. package/packages/client/dist/cli.d.ts +14 -0
  55. package/packages/client/dist/cli.js +81 -0
  56. package/packages/client/dist/commands/activate.d.ts +55 -0
  57. package/packages/client/dist/commands/activate.js +8 -0
  58. package/packages/client/dist/commands/cache-status.d.ts +39 -0
  59. package/packages/client/dist/commands/cache-status.js +2 -0
  60. package/packages/client/dist/commands/invoke.d.ts +546 -0
  61. package/packages/client/dist/commands/invoke.js +140 -0
  62. package/packages/client/dist/commands/refresh-memory.d.ts +11 -0
  63. package/packages/client/dist/commands/refresh-memory.js +1 -0
  64. package/packages/client/dist/config/resolver-selection.d.ts +40 -0
  65. package/packages/client/dist/config/resolver-selection.js +1 -0
  66. package/packages/client/dist/config/secure-config.d.ts +78 -0
  67. package/packages/client/dist/config/secure-config.js +12 -0
  68. package/packages/client/dist/constants.d.ts +25 -0
  69. package/packages/client/dist/constants.js +1 -0
  70. package/packages/client/dist/context/context-collector.d.ts +28 -0
  71. package/packages/client/dist/context/context-collector.js +2 -0
  72. package/packages/client/dist/context/context-sanitizer.d.ts +28 -0
  73. package/packages/client/dist/context/context-sanitizer.js +1 -0
  74. package/packages/client/dist/continuity/autonomous-governance.d.ts +84 -0
  75. package/packages/client/dist/continuity/autonomous-governance.js +1 -0
  76. package/packages/client/dist/continuity/continuity-client-state-store.d.ts +302 -0
  77. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -0
  78. package/packages/client/dist/continuity/invoke-hooks.d.ts +19 -0
  79. package/packages/client/dist/continuity/invoke-hooks.js +1 -0
  80. package/packages/client/dist/continuity/migrations/001-initial-schema.d.ts +11 -0
  81. package/packages/client/dist/continuity/migrations/001-initial-schema.js +263 -0
  82. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.d.ts +11 -0
  83. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +7 -0
  84. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.d.ts +11 -0
  85. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +62 -0
  86. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.d.ts +11 -0
  87. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +19 -0
  88. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.d.ts +11 -0
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +35 -0
  90. package/packages/client/dist/continuity/outbox.d.ts +83 -0
  91. package/packages/client/dist/continuity/outbox.js +1 -0
  92. package/packages/client/dist/continuity/runner-bootstrap-policy.d.ts +50 -0
  93. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -0
  94. package/packages/client/dist/continuity/sqlite-store.d.ts +926 -0
  95. package/packages/client/dist/continuity/sqlite-store.js +619 -0
  96. package/packages/client/dist/errors/error-messages.d.ts +40 -0
  97. package/packages/client/dist/errors/error-messages.js +2 -0
  98. package/packages/client/dist/graph-retrieval/pre-command-hook.d.ts +34 -0
  99. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -0
  100. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.d.ts +99 -0
  101. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -0
  102. package/packages/client/dist/i18n/first-run.d.ts +23 -0
  103. package/packages/client/dist/i18n/first-run.js +2 -0
  104. package/packages/client/dist/index.d.ts +56 -0
  105. package/packages/client/dist/index.js +1 -0
  106. package/packages/client/dist/license/index.d.ts +5 -0
  107. package/packages/client/dist/license/index.js +1 -0
  108. package/packages/client/dist/license/license-client.d.ts +79 -0
  109. package/packages/client/dist/license/license-client.js +1 -0
  110. package/packages/client/dist/machine/fingerprint.d.ts +34 -0
  111. package/packages/client/dist/machine/fingerprint.js +2 -0
  112. package/packages/client/dist/machine/index.d.ts +5 -0
  113. package/packages/client/dist/machine/index.js +1 -0
  114. package/packages/client/dist/memory/project-memory-writer.d.ts +74 -0
  115. package/packages/client/dist/memory/project-memory-writer.js +36 -0
  116. package/packages/client/dist/memory/shared-project-memory-types.d.ts +370 -0
  117. package/packages/client/dist/memory/shared-project-memory-types.js +2 -0
  118. package/packages/client/dist/policy/architecture-policy.d.ts +40 -0
  119. package/packages/client/dist/policy/architecture-policy.js +2 -0
  120. package/packages/client/dist/policy/index.d.ts +8 -0
  121. package/packages/client/dist/policy/index.js +1 -0
  122. package/packages/client/dist/policy/shared-policy-types.d.ts +89 -0
  123. package/packages/client/dist/policy/shared-policy-types.js +0 -0
  124. package/packages/client/dist/resilience/circuit-breaker.d.ts +70 -0
  125. package/packages/client/dist/resilience/circuit-breaker.js +1 -0
  126. package/packages/client/dist/resilience/degradation-manager.d.ts +67 -0
  127. package/packages/client/dist/resilience/degradation-manager.js +1 -0
  128. package/packages/client/dist/resilience/freshness-indicator.d.ts +59 -0
  129. package/packages/client/dist/resilience/freshness-indicator.js +1 -0
  130. package/packages/client/dist/resilience/index.d.ts +8 -0
  131. package/packages/client/dist/resilience/index.js +1 -0
  132. package/packages/client/dist/resilience/recovery-detector.d.ts +59 -0
  133. package/packages/client/dist/resilience/recovery-detector.js +1 -0
  134. package/packages/client/dist/resolvers/asset-resolver.d.ts +79 -0
  135. package/packages/client/dist/resolvers/asset-resolver.js +0 -0
  136. package/packages/client/dist/resolvers/local-resolver.d.ts +26 -0
  137. package/packages/client/dist/resolvers/local-resolver.js +8 -0
  138. package/packages/client/dist/resolvers/remote-resolver.d.ts +91 -0
  139. package/packages/client/dist/resolvers/remote-resolver.js +1 -0
  140. package/packages/client/dist/runner/binary.d.ts +115 -0
  141. package/packages/client/dist/runner/binary.js +1 -0
  142. package/packages/client/dist/runner/cli.d.ts +168 -0
  143. package/packages/client/dist/runner/cli.js +70 -0
  144. package/packages/client/dist/runner/headless/adapters.d.ts +20 -0
  145. package/packages/client/dist/runner/headless/adapters.js +1 -0
  146. package/packages/client/dist/runner/headless/claude-code-adapter.d.ts +8 -0
  147. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -0
  148. package/packages/client/dist/runner/headless/fake-adapter.d.ts +8 -0
  149. package/packages/client/dist/runner/headless/fake-adapter.js +1 -0
  150. package/packages/client/dist/runner/headless/opencode-adapter.d.ts +15 -0
  151. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -0
  152. package/packages/client/dist/runner/headless/resolver.d.ts +68 -0
  153. package/packages/client/dist/runner/headless/resolver.js +1 -0
  154. package/packages/client/dist/runner/headless/run-yolo.d.ts +59 -0
  155. package/packages/client/dist/runner/headless/run-yolo.js +1 -0
  156. package/packages/client/dist/runner/headless/run-yoloop.d.ts +113 -0
  157. package/packages/client/dist/runner/headless/run-yoloop.js +1 -0
  158. package/packages/client/dist/runner/headless/types.d.ts +194 -0
  159. package/packages/client/dist/runner/headless/types.js +2 -0
  160. package/packages/client/dist/runner/local-console.d.ts +83 -0
  161. package/packages/client/dist/runner/local-console.js +13 -0
  162. package/packages/client/dist/runner/portal-sync-worker.d.ts +184 -0
  163. package/packages/client/dist/runner/portal-sync-worker.js +1 -0
  164. package/packages/client/dist/runner/project-identity.d.ts +19 -0
  165. package/packages/client/dist/runner/project-identity.js +1 -0
  166. package/packages/client/dist/runner/scheduler.d.ts +186 -0
  167. package/packages/client/dist/runner/scheduler.js +7 -0
  168. package/packages/client/dist/runner-cli.d.ts +9 -0
  169. package/packages/client/dist/runner-cli.js +3 -0
  170. package/packages/client/dist/state/project-state-snapshot.d.ts +24 -0
  171. package/packages/client/dist/state/project-state-snapshot.js +1 -0
  172. package/packages/client/dist/state/state-json-repair.d.ts +74 -0
  173. package/packages/client/dist/state/state-json-repair.js +3 -0
  174. package/packages/client/dist/telemetry/index.d.ts +5 -0
  175. package/packages/client/dist/telemetry/index.js +1 -0
  176. package/packages/client/dist/telemetry/offline-queue.d.ts +57 -0
  177. package/packages/client/dist/telemetry/offline-queue.js +1 -0
  178. package/packages/client/dist/tier/index.d.ts +5 -0
  179. package/packages/client/dist/tier/index.js +1 -0
  180. package/packages/client/dist/tier/tier-aware-client.d.ts +105 -0
  181. package/packages/client/dist/tier/tier-aware-client.js +1 -0
  182. package/packages/client/dist/types/index.d.ts +140 -0
  183. package/packages/client/dist/types/index.js +1 -0
  184. package/packages/client/dist/yoloop/discovery-hook.d.ts +85 -0
  185. package/packages/client/dist/yoloop/discovery-hook.js +2 -0
  186. package/packages/client/dist/yoloop/index.d.ts +10 -0
  187. package/packages/client/dist/yoloop/index.js +1 -0
  188. package/packages/client/dist/yoloop/invoke-hooks.d.ts +127 -0
  189. package/packages/client/dist/yoloop/invoke-hooks.js +5 -0
  190. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +289 -0
  191. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -0
  192. package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +172 -0
  193. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -0
  194. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +124 -0
  195. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -0
  196. package/postinstall.js +754 -0
  197. package/targets-stubs/antigravity/README.md +36 -0
  198. package/targets-stubs/antigravity/gemini.md +29 -0
  199. package/targets-stubs/antigravity/install-antigravity.sh +153 -0
  200. package/targets-stubs/antigravity/mcp-config.json +30 -0
  201. package/targets-stubs/antigravity/skill/SKILL.md +166 -0
  202. package/targets-stubs/claude-code/.mcp.json +32 -0
  203. package/targets-stubs/claude-code/README.md +20 -0
  204. package/targets-stubs/claude-code/neocortex-root.agent.yaml +42 -0
  205. package/targets-stubs/claude-code/neocortex-root.md +317 -0
  206. package/targets-stubs/claude-code/neocortex.agent.yaml +42 -0
  207. package/targets-stubs/claude-code/neocortex.md +385 -0
  208. package/targets-stubs/codex/AGENTS.md +250 -0
  209. package/targets-stubs/codex/README.md +47 -0
  210. package/targets-stubs/codex/config-mcp.toml +22 -0
  211. package/targets-stubs/codex/install-codex.sh +63 -0
  212. package/targets-stubs/codex/neocortex.toml +33 -0
  213. package/targets-stubs/cursor/README.md +33 -0
  214. package/targets-stubs/cursor/agent.md +211 -0
  215. package/targets-stubs/cursor/install-cursor.sh +50 -0
  216. package/targets-stubs/cursor/mcp.json +30 -0
  217. package/targets-stubs/gemini-cli/README.md +34 -0
  218. package/targets-stubs/gemini-cli/agent.md +241 -0
  219. package/targets-stubs/gemini-cli/agents/neocortex.md +60 -0
  220. package/targets-stubs/gemini-cli/gemini.md +46 -0
  221. package/targets-stubs/gemini-cli/install-gemini.sh +70 -0
  222. package/targets-stubs/gemini-cli/settings-mcp.json +30 -0
  223. package/targets-stubs/kimi/mcp.json +33 -0
  224. package/targets-stubs/kimi/neocortex.md +60 -0
  225. package/targets-stubs/lib/mcp-merge.js +189 -0
  226. package/targets-stubs/openclaw/README.md +12 -0
  227. package/targets-stubs/openclaw/SKILL.md +92 -0
  228. package/targets-stubs/opencode/neocortex-root.md +267 -0
  229. package/targets-stubs/opencode/neocortex.md +65 -0
  230. package/targets-stubs/opencode/opencode-mcp.json +35 -0
  231. package/targets-stubs/vscode/README.md +34 -0
  232. package/targets-stubs/vscode/copilot-instructions.md +47 -0
  233. package/targets-stubs/vscode/install-vscode.sh +72 -0
  234. package/targets-stubs/vscode/mcp.json +36 -0
  235. package/targets-stubs/vscode/neocortex.agent.md +252 -0
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * Central, localized error message helpers for CLI output. Turns
6
+ * server error codes and low-level exceptions into friendly, actionable
7
+ * messages with "What happened" + "What to do" + support email.
8
+ *
9
+ * Story P76.06.
10
+ */
11
+ export type ErrorMessageLocale = 'pt-BR' | 'en';
12
+ export interface HumanizedError {
13
+ /** Short one-line summary. */
14
+ readonly summary: string;
15
+ /** What happened (friendly explanation). */
16
+ readonly whatHappened: string;
17
+ /** Actionable next step(s). */
18
+ readonly whatToDo: string;
19
+ /** Optional CLI command snippet the user should run. */
20
+ readonly command?: string;
21
+ /** URL the user can visit for more context. */
22
+ readonly url?: string;
23
+ }
24
+ /** Detect the best locale from LC_ALL / LANG. Falls back to 'en'. */
25
+ export declare function detectErrorLocale(env?: NodeJS.ProcessEnv): ErrorMessageLocale;
26
+ /**
27
+ * Look up a humanized message for an error code.
28
+ * Returns null if the code is unknown -- caller should fall back to the
29
+ * raw server message.
30
+ */
31
+ export declare function humanizeError(code: string, locale?: ErrorMessageLocale): HumanizedError | null;
32
+ /**
33
+ * Format a humanized error for stderr. Always ends with the support email.
34
+ */
35
+ export declare function formatHumanizedError(humanized: HumanizedError, locale?: ErrorMessageLocale): string;
36
+ /**
37
+ * Infer an error code from a low-level error object (e.g., Node.js error
38
+ * thrown by fetch / dns / pg). Returns null if we cannot classify it.
39
+ */
40
+ export declare function inferErrorCodeFromException(err: unknown): string | null;
@@ -0,0 +1,2 @@
1
+ const t="support@neocortex.sh",u={AUTH_EXPIRED:{en:{summary:"Your session has expired.",whatHappened:"The token we use to authenticate your CLI has expired. This is normal and happens every few hours.",whatToDo:"Re-activate with the license key that was emailed to you.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Sua sess\xE3o expirou.",whatHappened:"O token de autentica\xE7\xE3o do CLI expirou. Isso \xE9 normal e acontece a cada poucas horas.",whatToDo:"Reative o CLI com a license key que voc\xEA recebeu por email.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}},UPGRADE_REQUIRED:{en:{summary:"Your CLI version is outdated.",whatHappened:"The server requires a newer CLI version. Older versions are not allowed for security and compatibility reasons.",whatToDo:"Install the latest CLI globally with npm.",command:"npm install -g @ornexus/neocortex@latest"},"pt-BR":{summary:"Sua vers\xE3o do CLI est\xE1 desatualizada.",whatHappened:"O servidor exige uma vers\xE3o mais recente do CLI. Vers\xF5es antigas n\xE3o s\xE3o permitidas por motivos de seguran\xE7a e compatibilidade.",whatToDo:"Instale a vers\xE3o mais recente globalmente via npm.",command:"npm install -g @ornexus/neocortex@latest"}},RATE_LIMITED:{en:{summary:"You sent too many requests in a short window.",whatHappened:"You hit the rate limit for your plan. This protects the service from abuse and keeps it fast for everyone.",whatToDo:"Wait a few seconds and try again. If you hit this often, upgrading your plan raises the limit.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Voc\xEA fez muitas requisi\xE7\xF5es em pouco tempo.",whatHappened:"O limite de taxa do seu plano foi atingido. Isso protege o servi\xE7o contra abuso e mant\xE9m a velocidade para todos.",whatToDo:"Espere alguns segundos e tente novamente. Se isso acontece com frequ\xEAncia, fazer upgrade do seu plano aumenta o limite.",url:"https://neocortex.sh/portal/plans"}},TRIGGER_NOT_ALLOWED:{en:{summary:"This command is not available on your current plan.",whatHappened:"You tried to use a trigger that requires a paid plan (Pro or Enterprise).",whatToDo:"See the full comparison and upgrade in the portal.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Este comando n\xE3o est\xE1 dispon\xEDvel no seu plano atual.",whatHappened:"Voc\xEA tentou usar um trigger que requer um plano pago (Pro ou Enterprise).",whatToDo:"Veja a compara\xE7\xE3o completa e fa\xE7a upgrade no portal.",url:"https://neocortex.sh/portal/plans"}},QUOTA_EXCEEDED:{en:{summary:"Daily quota reached.",whatHappened:"You have used all invocations allowed by your plan today. Quotas reset at midnight UTC.",whatToDo:"Wait for the daily reset, or upgrade your plan for a higher quota.",url:"https://neocortex.sh/portal/plans"},"pt-BR":{summary:"Quota di\xE1ria atingida.",whatHappened:"Voc\xEA usou todas as invoca\xE7\xF5es permitidas pelo seu plano hoje. As quotas s\xE3o resetadas \xE0 meia-noite UTC.",whatToDo:"Aguarde o reset di\xE1rio ou fa\xE7a upgrade do plano para uma quota maior.",url:"https://neocortex.sh/portal/plans"}},SERVER_ERROR:{en:{summary:"Server error.",whatHappened:"Something went wrong on our side. We have logged the error and will investigate.",whatToDo:`Try again in a minute. If the problem persists, please contact ${t} with the details.`},"pt-BR":{summary:"Erro do servidor.",whatHappened:"Algo deu errado no nosso lado. O erro foi registrado e vamos investigar.",whatToDo:`Tente novamente em um minuto. Se o problema persistir, entre em contato: ${t}.`}},ECONNREFUSED:{en:{summary:"Cannot reach the Neocortex server.",whatHappened:"We could not open a connection to the server. This is usually a network problem on your side.",whatToDo:"Check your internet connection, any VPN or corporate proxy, and try again."},"pt-BR":{summary:"N\xE3o foi poss\xEDvel alcan\xE7ar o servidor Neocortex.",whatHappened:"N\xE3o conseguimos abrir uma conex\xE3o com o servidor. Isso geralmente \xE9 um problema de rede do seu lado.",whatToDo:"Verifique sua conex\xE3o, qualquer VPN ou proxy corporativo, e tente novamente."}},MACHINE_LIMIT_EXCEEDED:{en:{summary:"Machine limit reached.",whatHappened:"Your plan allows a limited number of active machines, and this one would exceed it.",whatToDo:"Deactivate a machine you no longer use from the portal, then re-run activate here.",url:"https://neocortex.sh/portal/machines"},"pt-BR":{summary:"Limite de m\xE1quinas atingido.",whatHappened:"Seu plano permite um n\xFAmero limitado de m\xE1quinas ativas, e esta ultrapassaria o limite.",whatToDo:"Desative uma m\xE1quina que voc\xEA n\xE3o usa mais no portal e rode activate aqui de novo.",url:"https://neocortex.sh/portal/machines"}},NOT_CONFIGURED:{en:{summary:"Neocortex is not configured on this machine.",whatHappened:"No license key was found. You need to run `neocortex activate` once before using the CLI.",whatToDo:"Get a license key from the portal and activate.",command:"neocortex activate YOUR-LICENSE-KEY",url:"https://neocortex.sh/portal"},"pt-BR":{summary:"Neocortex n\xE3o est\xE1 configurado nesta m\xE1quina.",whatHappened:"Nenhuma license key encontrada. Voc\xEA precisa rodar `neocortex activate` uma vez antes de usar o CLI.",whatToDo:"Pegue uma license key no portal e ative.",command:"neocortex activate SUA-LICENSE-KEY",url:"https://neocortex.sh/portal"}}};function r(o=process.env){return(o.LC_ALL??o.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function p(o,a=r()){const e=u[o];return e?e[a]??e.en??null:null}function c(o,a=r()){const e=[];e.push(""),e.push(`[Neocortex] ${o.summary}`),e.push("");const n=a==="pt-BR"?"O que aconteceu":"What happened",s=a==="pt-BR"?"O que fazer":"What to do",i=a==="pt-BR"?`Precisa de ajuda? ${t}`:`Need help? ${t}`;return e.push(`${n}: ${o.whatHappened}`),e.push(`${s}: ${o.whatToDo}`),o.command&&(e.push(""),e.push(` ${o.command}`)),o.url&&(e.push(""),e.push(` ${o.url}`)),e.push(""),e.push(i),e.push(""),e.join(`
2
+ `)}function l(o){if(!o||typeof o!="object")return null;const a=o;return typeof a.code=="string"&&(a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"||a.code==="ETIMEDOUT"||a.code==="ECONNRESET")||typeof a.message=="string"&&(/connect/i.test(a.message)&&/refus/i.test(a.message)||/fetch failed/i.test(a.message))?"ECONNREFUSED":null}export{r as detectErrorLocale,c as formatHumanizedError,p as humanizeError,l as inferErrorCodeFromException};
@@ -0,0 +1,34 @@
1
+ /**
2
+ * P158.06 -- optional pre-command deterministic graph retrieval enrichment.
3
+ *
4
+ * The client collects a tiny, public, redacted context envelope for commands
5
+ * resolved by the shared command context policy shadow. It never constructs
6
+ * workflow prompts or decides orchestration; the server validates and decides
7
+ * whether to consume this auxiliary metadata.
8
+ */
9
+ import { type CommandContextRetrievalProfile, type GraphRetrievalMetadata } from './shared-graph-retrieval-contract.js';
10
+ declare const CONTRACT_VERSION = "client-pre-command-v1";
11
+ export interface GraphRetrievalHookContext {
12
+ readonly args: string;
13
+ readonly projectRoot: string;
14
+ readonly featureFlag: boolean;
15
+ readonly nowIso?: string;
16
+ readonly logger?: {
17
+ readonly warn?: (msg: string) => void;
18
+ };
19
+ }
20
+ export type GraphRetrievalCommand = string;
21
+ export type GraphRetrievalEnrichmentMetadata = GraphRetrievalMetadata & {
22
+ readonly contractVersion: typeof CONTRACT_VERSION;
23
+ readonly command: GraphRetrievalCommand;
24
+ };
25
+ export interface GraphRetrievalHookResult {
26
+ readonly applied: boolean;
27
+ readonly reason: 'flag_off' | 'command_not_allowlisted' | 'no_items' | 'applied' | 'hook_error';
28
+ readonly command?: GraphRetrievalCommand;
29
+ readonly profile?: CommandContextRetrievalProfile;
30
+ readonly metadata?: GraphRetrievalEnrichmentMetadata;
31
+ readonly warning?: string;
32
+ }
33
+ export declare function runGraphRetrievalHook(ctx: GraphRetrievalHookContext): Promise<GraphRetrievalHookResult>;
34
+ export {};
@@ -0,0 +1 @@
1
+ import{createHash as _}from"node:crypto";import{existsSync as T,readFileSync as f,statSync as v}from"node:fs";import{join as h}from"node:path";import{DEFAULT_GRAPH_RETRIEVAL_BUDGETS as y,createGraphRetrievalMetadata as g,normalizeGraphRetrievalPath as i,resolveClientCommandContextPolicy as I}from"./shared-graph-retrieval-contract.js";const u="client-pre-command-v1",P="1970-01-01T00:00:00.000Z";function E(e){return I(e)}function p(e){return _("sha256").update(e).digest("hex")}function m(e){const t=i(e);return t.length===0||t.startsWith("/")||t.startsWith("..")||t.includes("/../")||/(^|\/)\.env(?:$|[./-])/i.test(t)||/(^|\/)(?:credentials?|secrets?|tokens?|private-prompts?|raw-logs?)(?:\.|\/|$)/i.test(t)||/\.(?:sqlite|db|pem|key|p12|pfx|crt|cer|der|bin)$/i.test(t)}function A(e,t){const n=i(t);if(m(n))return null;const o=h(e,n);if(!T(o))return null;const r=v(o);if(!r.isFile()||r.size>96*1024)return null;const a=f(o,"utf8");return{kind:"repo-path",path:n,contentHash:p(a).slice(0,16),mtimeMs:Math.floor(r.mtimeMs)}}function b(e){let t=e;const n=t;return t=t.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[REDACTED_EMAIL]"),t=t.replace(/\b(api[-_ ]?key|license[-_ ]?key|token|password|secret)\b\s*[:=]\s*[^\s`'"\])}]+/gi,"$1=[REDACTED_SECRET]"),t=t.replace(/\b(?:sk|pk|ghp|github_pat|pat)_[A-Za-z0-9_\-]{16,}\b/g,"[REDACTED_TOKEN]"),t=t.replace(/\b[A-Za-z0-9+/]{32,}={0,2}\b/g,"[REDACTED_TOKEN]"),t=t.replace(/<!--\s*(?:server|private|proprietary)[\s\S]*?-->/gi,"[REDACTED_PRIVATE_PROMPT]"),t=t.replace(/\b(?:private|proprietary|protected)\s+(?:prompt|workflow|step\s*body|orchestration)\b[^.!?\n]*/gi,"[REDACTED_PRIVATE_PROMPT]"),{text:t,redacted:t!==n}}function k(e,t=y.maxSnippetChars){const n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("---")&&!r.startsWith("<!--")).slice(0,8).join(" "),o=b(n);return{summary:o.text.slice(0,t),redacted:o.redacted}}function R(e,t){const n=A(e,t.path);if(!n)return null;const o=f(h(e,n.path),"utf8"),r=k(o,t.maxSnippetChars);return{nodeType:t.nodeType,stableId:t.stableId,source:n,confidence:r.redacted?Math.min(t.confidence,.72):t.confidence,reasonCode:t.reasonCode,budgetCost:t.budgetCost,summary:r.summary,warnings:r.redacted?["redacted_sensitive_content"]:void 0,score:t.score}}function x(e){const t=`Public command ${e.commandId}; graphRetrieval profile ${e.retrievalProfile}; context is auxiliary, redacted, budgeted and non-authoritative.`;return{nodeType:"Command",stableId:`command:${e.commandId}`,source:{kind:"command",path:e.commandId,contentHash:p(t).slice(0,16)},confidence:.88,reasonCode:"command_surface_match",budgetCost:1,summary:t.slice(0,e.retrievalBudget.maxSnippetChars),score:90}}function C(e){return e.match(/@?(docs\/stories\/[A-Za-z0-9._-]+\.story\.md)\b/)?.[1]??null}function S(e){return e.match(/@?(docs\/epics\/[A-Za-z0-9._-]+\.md)\b/)?.[1]??null}function D(e){const o=C(e)?.split("/").pop()?.replace(/\.story\.md$/,"")?.match(/^(P\d+)\./i)?.[1];if(o)return o.toUpperCase();const r=e.match(/\b(P\d+)(?:\.\d+)?\b/i)?.[1];return r?r.toUpperCase():null}function $(e){return[...e.matchAll(/@?((?:docs|core)\/[A-Za-z0-9_./-]+\.md)\b/g)].map(t=>i(t[1])).filter(t=>!m(t))}function w(e){return e.startsWith("docs/stories/")?{nodeType:"Story",reasonCode:"story_scope_match"}:e.startsWith("docs/epics/")?{nodeType:"Epic",reasonCode:"epic_scope_match"}:e.includes("security")||e.includes("policy")||e.includes("standard")?{nodeType:"Guardrail",reasonCode:"guardrail_match"}:{nodeType:"Doc",reasonCode:"architecture_reference"}}function s(e,t){const n=i(t.path);if(m(n))return;e.some(r=>r.nodeType===t.nodeType&&i(r.path)===n)||e.push({...t,path:n})}function G(e,t,n){const o=C(t);if(o){const c=o.split("/").pop()?.replace(/\.story\.md$/,"")??o;s(e,{path:o,nodeType:"Story",stableId:c,reasonCode:"story_scope_match",confidence:.96,budgetCost:3,score:96,maxSnippetChars:n})}const r=S(t),a=D(t);if(r){const c=r.split("/").pop()?.replace(/\.md$/,"")??r;s(e,{path:r,nodeType:"Epic",stableId:c,reasonCode:"epic_scope_match",confidence:.92,budgetCost:3,score:92,maxSnippetChars:n})}else a&&s(e,{path:`docs/epics/epic-${a}.md`,nodeType:"Epic",stableId:a,reasonCode:"epic_scope_match",confidence:.9,budgetCost:3,score:90,maxSnippetChars:n});for(const c of $(t)){const l=c.split("/").pop()?.replace(/\.md$/,"").replace(/\.story$/,"")??c,d=w(c);s(e,{path:c,stableId:l,...d,confidence:.84,budgetCost:3,score:82,maxSnippetChars:n})}}function M(e,t,n){const o=e.retrievalBudget.maxSnippetChars,r=[];return s(r,{path:"NEOCORTEX.md",nodeType:"CanonicalMemory",stableId:"canonical-memory",reasonCode:"canonical_memory_seed",confidence:.92,budgetCost:4,score:100,maxSnippetChars:o}),s(r,{path:"AGENTS.md",nodeType:"PlatformMemory",stableId:"platform-memory:agents",reasonCode:"platform_memory_reference",confidence:.7,budgetCost:2,score:66,maxSnippetChars:o}),s(r,{path:"package.json",nodeType:"Package",stableId:"root-package",reasonCode:"package_surface_match",confidence:.78,budgetCost:2,score:72,maxSnippetChars:o}),(e.retrievalProfile!=="utility"||e.commandId==="ui-ux-review")&&s(r,{path:"docs/arquitetura-software/deterministic-graph-retrieval.md",nodeType:"Doc",stableId:"deterministic-graph-retrieval",reasonCode:"architecture_reference",confidence:.9,budgetCost:4,score:84,maxSnippetChars:o}),G(r,t,o),(["story-execution","diagnostic","research","review","qa","recovery","planning"].includes(e.retrievalProfile)||e.commandId==="tech-debt")&&s(r,{path:".neocortex/tech-debt-registry.json",nodeType:"Debt",stableId:"tech-debt-registry",reasonCode:"debt_area_match",confidence:.74,budgetCost:3,score:76,maxSnippetChars:o}),["story-execution","diagnostic","research","review","qa","recovery","planning","architecture"].includes(e.retrievalProfile)&&s(r,{path:"core/standards/spec-driven-development.md",nodeType:"Guardrail",stableId:"spec-driven-development",reasonCode:"guardrail_match",confidence:.82,budgetCost:3,score:78,maxSnippetChars:o}),e.retrievalProfile==="security"&&s(r,{path:"docs/architecture/solyd-security-system-contract.md",nodeType:"Guardrail",stableId:"solyd-security-system-contract",reasonCode:"guardrail_match",confidence:.86,budgetCost:3,score:84,maxSnippetChars:o}),e.retrievalProfile==="continuity"&&(s(r,{path:"core/standards/enterprise-continuity-plane.md",nodeType:"Guardrail",stableId:"enterprise-continuity-plane",reasonCode:"guardrail_match",confidence:.86,budgetCost:3,score:84,maxSnippetChars:o}),s(r,{path:"docs/runbooks/enterprise-continuity-runner.md",nodeType:"Doc",stableId:"enterprise-continuity-runner",reasonCode:"architecture_reference",confidence:.78,budgetCost:3,score:72,maxSnippetChars:o})),["utility","continuity","recovery"].includes(e.retrievalProfile)&&s(r,{path:".neocortex/state.json",nodeType:"State",stableId:"project-state",reasonCode:"state_status_match",confidence:.68,budgetCost:3,score:70,maxSnippetChars:o}),[x(e),...r.map(a=>R(n,a)).filter(a=>a!==null)]}function z(e){let t=[...e.items],n=e;const o=Math.min(e.budget.maxPayloadBytes,y.maxPayloadBytes);for(;Buffer.byteLength(JSON.stringify(n),"utf8")>o&&t.length>0;){const r=t.pop(),a=g({retrievalId:e.retrievalId,query:e.query,items:t,generatedAt:e.generatedAt,warnings:e.warnings,budgets:e.budget});n={...a,skipped:r?[...a.skipped,{stableId:r.stableId,source:r.source,reasonCode:"budget_exceeded"}]:a.skipped,contractVersion:u,command:e.command}}return n}async function j(e){const t=E(e.args);if(!t)return{applied:!1,reason:"command_not_allowlisted"};const n=t.commandId;try{const o=M(t,e.args,e.projectRoot);if(o.length===0)return{applied:!1,reason:"no_items",command:n,profile:t.retrievalProfile};const r=b(e.args.trim().slice(0,240)).text,a=p(`${u}:${n}:${r}:${o.map(d=>`${d.source.path}:${d.source.contentHash??""}`).sort().join("|")}`).slice(0,24),c=g({retrievalId:a,query:r,items:o,generatedAt:e.nowIso??P,budgets:t.retrievalBudget}),l=z({...c,contractVersion:u,command:n});return{applied:!0,reason:"applied",command:n,profile:t.retrievalProfile,metadata:l}}catch(o){const r=o instanceof Error?o.message:String(o);return e.logger?.warn?.(`[neocortex] graph retrieval hook failed: ${r}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",command:n,profile:t.retrievalProfile,warning:r}}}export{j as runGraphRetrievalHook};
@@ -0,0 +1,99 @@
1
+ /**
2
+ * P158.06 client-side SSoT shadow for graph retrieval metadata.
3
+ *
4
+ * Mirrored from @neocortex/shared/graph-retrieval-contract and the public
5
+ * P198.01 command context policy for globally installed clients, where importing
6
+ * shared source/dist subpaths can break before the monorepo build has
7
+ * materialized dist files.
8
+ */
9
+ export declare const GRAPH_RETRIEVAL_SCHEMA_VERSION: 1;
10
+ export declare const GRAPH_RETRIEVAL_CLIENT_CONTRACT_VERSION: "client-pre-command-v1";
11
+ export type GraphRetrievalCommand = string;
12
+ export declare const COMMAND_CONTEXT_RETRIEVAL_PROFILES: readonly ["utility", "planning", "architecture", "diagnostic", "research", "story-execution", "review", "qa", "security", "continuity", "recovery"];
13
+ export type CommandContextRetrievalProfile = (typeof COMMAND_CONTEXT_RETRIEVAL_PROFILES)[number];
14
+ export interface ClientCommandContextPolicyEntry {
15
+ readonly commandId: GraphRetrievalCommand;
16
+ readonly number?: number;
17
+ readonly aliases: readonly string[];
18
+ readonly retrievalProfile: CommandContextRetrievalProfile;
19
+ readonly retrievalBudget: GraphRetrievalBudgets;
20
+ }
21
+ export type GraphRetrievalNodeType = 'CanonicalMemory' | 'PlatformMemory' | 'Doc' | 'Epic' | 'Story' | 'Command' | 'State' | 'Debt' | 'Package' | 'Api' | 'Route' | 'DbSchema' | 'Flag' | 'BusinessRule' | 'Guardrail' | 'Risk';
22
+ export type GraphRetrievalEdgeType = 'references' | 'derived_from' | 'updates' | 'governs' | 'implements' | 'depends_on' | 'conflicts_with' | 'supersedes' | 'documents' | 'affects' | 'retrieved_for';
23
+ export type GraphRetrievalReasonCode = 'canonical_memory_seed' | 'platform_memory_reference' | 'architecture_reference' | 'story_scope_match' | 'epic_scope_match' | 'command_surface_match' | 'state_status_match' | 'debt_area_match' | 'package_surface_match' | 'api_surface_match' | 'route_surface_match' | 'db_schema_surface_match' | 'flag_surface_match' | 'business_rule_match' | 'guardrail_match' | 'risk_match' | 'dependency_match' | 'conflict_warning' | 'stale_source_warning' | 'budget_exceeded' | 'redacted_sensitive_content' | 'invalid_source_rejected';
24
+ export interface GraphRetrievalBudgets {
25
+ readonly maxItems: number;
26
+ readonly maxEdges: number;
27
+ readonly maxPayloadBytes: number;
28
+ readonly maxSnippetChars: number;
29
+ readonly maxLabelChars: number;
30
+ readonly maxTotalCost: number;
31
+ }
32
+ export declare const DEFAULT_GRAPH_RETRIEVAL_BUDGETS: GraphRetrievalBudgets;
33
+ export declare const CLIENT_GRAPH_RETRIEVAL_PROFILE_BUDGETS: Readonly<Record<CommandContextRetrievalProfile, GraphRetrievalBudgets>>;
34
+ export declare const CLIENT_PUBLIC_COMMAND_CONTEXT_POLICIES: readonly ClientCommandContextPolicyEntry[];
35
+ export declare const CLIENT_INTERNAL_COMMAND_CONTEXT_POLICIES: readonly ClientCommandContextPolicyEntry[];
36
+ export declare const CLIENT_COMMAND_CONTEXT_POLICIES: readonly ClientCommandContextPolicyEntry[];
37
+ export declare const CLIENT_COMMAND_CONTEXT_POLICY_BY_ID: Readonly<Record<string, ClientCommandContextPolicyEntry>>;
38
+ export declare const CLIENT_COMMAND_CONTEXT_POLICY_BY_NUMBER: Readonly<Record<number, ClientCommandContextPolicyEntry>>;
39
+ export declare const CLIENT_COMMAND_CONTEXT_POLICY_ALIAS_MAP: Readonly<Record<string, string>>;
40
+ export declare function normalizeCommandToken(input: string): string;
41
+ export declare function listClientPublicCommandContextPolicies(): readonly ClientCommandContextPolicyEntry[];
42
+ export declare function listClientInternalCommandContextPolicies(): readonly ClientCommandContextPolicyEntry[];
43
+ export declare function listClientCommandContextPolicies(): readonly ClientCommandContextPolicyEntry[];
44
+ export declare function resolveClientCommandContextPolicy(input: string): ClientCommandContextPolicyEntry | null;
45
+ export interface GraphRetrievalSource {
46
+ readonly kind: 'repo-path' | 'state' | 'command' | 'generated-summary';
47
+ readonly path: string;
48
+ readonly contentHash?: string;
49
+ readonly mtimeMs?: number;
50
+ }
51
+ export interface GraphRetrievalEdge {
52
+ readonly type: GraphRetrievalEdgeType;
53
+ readonly targetNodeType: GraphRetrievalNodeType;
54
+ readonly targetStableId: string;
55
+ readonly source: GraphRetrievalSource;
56
+ readonly confidence: number;
57
+ readonly reasonCode: GraphRetrievalReasonCode;
58
+ }
59
+ export interface GraphRetrievalItem {
60
+ readonly nodeType: GraphRetrievalNodeType;
61
+ readonly stableId: string;
62
+ readonly source: GraphRetrievalSource;
63
+ readonly confidence: number;
64
+ readonly reasonCode: GraphRetrievalReasonCode;
65
+ readonly budgetCost: number;
66
+ readonly summary: string;
67
+ readonly edges?: readonly GraphRetrievalEdge[];
68
+ readonly warnings?: readonly GraphRetrievalReasonCode[];
69
+ readonly score?: number;
70
+ }
71
+ export interface GraphRetrievalSkippedItem {
72
+ readonly stableId: string;
73
+ readonly reasonCode: 'budget_exceeded' | 'redacted_sensitive_content' | 'invalid_source_rejected';
74
+ readonly source?: GraphRetrievalSource;
75
+ }
76
+ export interface GraphRetrievalMetadata {
77
+ readonly schemaVersion: typeof GRAPH_RETRIEVAL_SCHEMA_VERSION;
78
+ readonly contractVersion?: typeof GRAPH_RETRIEVAL_CLIENT_CONTRACT_VERSION;
79
+ readonly command?: GraphRetrievalCommand;
80
+ readonly retrievalId: string;
81
+ readonly query: string;
82
+ readonly budget: GraphRetrievalBudgets & {
83
+ readonly totalCost: number;
84
+ };
85
+ readonly items: readonly GraphRetrievalItem[];
86
+ readonly skipped: readonly GraphRetrievalSkippedItem[];
87
+ readonly warnings: readonly GraphRetrievalReasonCode[];
88
+ readonly generatedAt: string;
89
+ }
90
+ export declare function normalizeGraphRetrievalPath(path: string): string;
91
+ export declare function compareGraphRetrievalItems(a: GraphRetrievalItem, b: GraphRetrievalItem): number;
92
+ export declare function createGraphRetrievalMetadata(params: {
93
+ readonly retrievalId: string;
94
+ readonly query: string;
95
+ readonly items: readonly GraphRetrievalItem[];
96
+ readonly generatedAt: string;
97
+ readonly budgets?: Partial<GraphRetrievalBudgets>;
98
+ readonly warnings?: readonly GraphRetrievalReasonCode[];
99
+ }): GraphRetrievalMetadata;
@@ -0,0 +1 @@
1
+ const L=1,O="client-pre-command-v1",N=["utility","planning","architecture","diagnostic","research","story-execution","review","qa","security","continuity","recovery"],P={maxItems:24,maxEdges:64,maxPayloadBytes:12288,maxSnippetChars:480,maxLabelChars:160,maxTotalCost:100},i=e=>Object.freeze({...e}),v=Object.freeze({utility:i({maxItems:4,maxEdges:8,maxPayloadBytes:4*1024,maxSnippetChars:280,maxLabelChars:96,maxTotalCost:40}),planning:i({maxItems:12,maxEdges:48,maxPayloadBytes:8*1024,maxSnippetChars:360,maxLabelChars:128,maxTotalCost:70}),architecture:i({maxItems:10,maxEdges:48,maxPayloadBytes:8*1024,maxSnippetChars:360,maxLabelChars:128,maxTotalCost:65}),diagnostic:i({maxItems:10,maxEdges:32,maxPayloadBytes:8*1024,maxSnippetChars:360,maxLabelChars:128,maxTotalCost:60}),research:i({maxItems:10,maxEdges:32,maxPayloadBytes:8*1024,maxSnippetChars:360,maxLabelChars:128,maxTotalCost:60}),"story-execution":i({maxItems:6,maxEdges:32,maxPayloadBytes:8*1024,maxSnippetChars:320,maxLabelChars:128,maxTotalCost:50}),review:i({maxItems:8,maxEdges:32,maxPayloadBytes:8*1024,maxSnippetChars:320,maxLabelChars:128,maxTotalCost:55}),qa:i({maxItems:6,maxEdges:24,maxPayloadBytes:8*1024,maxSnippetChars:320,maxLabelChars:128,maxTotalCost:50}),security:i({maxItems:8,maxEdges:24,maxPayloadBytes:8*1024,maxSnippetChars:320,maxLabelChars:128,maxTotalCost:55}),continuity:i({maxItems:6,maxEdges:16,maxPayloadBytes:4*1024,maxSnippetChars:280,maxLabelChars:96,maxTotalCost:45}),recovery:i({maxItems:8,maxEdges:32,maxPayloadBytes:8*1024,maxSnippetChars:320,maxLabelChars:128,maxTotalCost:55})}),u=e=>Object.freeze({commandId:e.commandId,...e.number===void 0?{}:{number:e.number},aliases:Object.freeze([...e.aliases??[]]),retrievalProfile:e.retrievalProfile,retrievalBudget:v[e.retrievalProfile]}),C=[{commandId:"status",number:1,aliases:["st"],retrievalProfile:"utility"},{commandId:"init",number:2,aliases:["inicializar"],retrievalProfile:"utility"},{commandId:"arch-plan",number:3,aliases:["arquitetura","architecture","arch"],retrievalProfile:"architecture"},{commandId:"arch-prd",number:4,aliases:["prd","product-requirements"],retrievalProfile:"architecture"},{commandId:"arch-architecture",number:5,aliases:["arch-doc","tech-architecture"],retrievalProfile:"architecture"},{commandId:"arch-api-contracts",number:6,aliases:["api-contracts","api-contract"],retrievalProfile:"architecture"},{commandId:"arch-api-integrations",number:7,aliases:["api-integrations","api-int"],retrievalProfile:"architecture"},{commandId:"arch-database",number:8,aliases:["database-schema","db-schema","db"],retrievalProfile:"architecture"},{commandId:"arch-security",number:9,aliases:["cyber-security","security","sec"],retrievalProfile:"architecture"},{commandId:"arch-design-system",number:10,aliases:["design-system","ds","atomic-design"],retrievalProfile:"architecture"},{commandId:"arch-ux-design",number:11,aliases:["ux-design","ux","wireframes","wireframe","user-flows"],retrievalProfile:"architecture"},{commandId:"arch-performance",number:12,aliases:["performance","perf","capacity-planning","capacity","arch-perf","performance-strategy"],retrievalProfile:"architecture"},{commandId:"arch-testing",number:13,aliases:["testing-strategy","test-plan","test-strategy","arch-test"],retrievalProfile:"architecture"},{commandId:"arch-infrastructure",number:14,aliases:["infrastructure","infra","deploy-plan","deployment","arch-infra","arch-deploy"],retrievalProfile:"architecture"},{commandId:"arch-review",number:15,aliases:["review-consolidation","consolidation","architecture-review","arch-consolidation"],retrievalProfile:"architecture"},{commandId:"arch-fitness-functions",number:16,aliases:["fitness","fitness-functions","archfit","arch-fit","fit-funcs"],retrievalProfile:"architecture"},{commandId:"create-epic",number:17,aliases:["criar-epic","planejamento"],retrievalProfile:"planning"},{commandId:"idea-diagnose",number:18,aliases:["idea-diag"],retrievalProfile:"planning"},{commandId:"idea-research",number:19,aliases:["idea-pesq"],retrievalProfile:"planning"},{commandId:"generate-epic",number:20,aliases:["gerar-epic"],retrievalProfile:"planning"},{commandId:"exec",number:21,aliases:["executar","pipeline"],retrievalProfile:"story-execution"},{commandId:"yolo",number:22,retrievalProfile:"story-execution"},{commandId:"epic",number:23,aliases:["parallel-epic"],retrievalProfile:"story-execution"},{commandId:"setup-branch",number:24,aliases:["setup","branch"],retrievalProfile:"story-execution"},{commandId:"diagnose",number:25,aliases:["diag","diagnostico","c02"],retrievalProfile:"diagnostic"},{commandId:"research",number:26,aliases:["pesquisar","pesq","research-fix","c03"],retrievalProfile:"research"},{commandId:"write-spec",number:27,aliases:["spec","especificacao","c04"],retrievalProfile:"story-execution"},{commandId:"create-tasks",number:28,aliases:["tasks","tarefas","c05"],retrievalProfile:"story-execution"},{commandId:"implement",number:29,aliases:["impl","implementar","c06"],retrievalProfile:"story-execution"},{commandId:"commit",number:30,aliases:["push","commit-push","commit_push","cp","c07"],retrievalProfile:"story-execution"},{commandId:"sync",number:31,aliases:["sincronizar","c08"],retrievalProfile:"story-execution"},{commandId:"create-pr",number:32,aliases:["pr","c09"],retrievalProfile:"story-execution"},{commandId:"review",number:33,aliases:["revisar","c11"],retrievalProfile:"review"},{commandId:"merge",number:34,aliases:["mesclar","c12"],retrievalProfile:"story-execution"},{commandId:"fix-blocked",number:35,aliases:["fix","corrigir"],retrievalProfile:"recovery"},{commandId:"finalize-epic",number:36,aliases:["finalizar"],retrievalProfile:"recovery"},{commandId:"resolve-conflicts",number:37,aliases:["conflitos"],retrievalProfile:"recovery"},{commandId:"update-memory",number:38,aliases:["memoria"],retrievalProfile:"recovery"},{commandId:"refactor",number:39,aliases:["refactoring","refact","refac","rf","cleanup-code","code-cleanup","code-quality","improve-code","modernize","modernization","legacy","legacy-code","debt-pay","pay-debt","debt-reduction","smell-fix","fix-smells","code-smells","strangler","strangler-fig"],retrievalProfile:"recovery"},{commandId:"cleanup",number:40,aliases:["limpar","limpeza"],retrievalProfile:"utility"},{commandId:"audit",number:41,aliases:["auditar","auditoria"],retrievalProfile:"utility"},{commandId:"tech-debt",number:42,aliases:["debt","debts","debt-list","tech-debts","td"],retrievalProfile:"utility"},{commandId:"menu",number:43,aliases:["help","ajuda","?","commands","cmds"],retrievalProfile:"utility"},{commandId:"plans",number:44,aliases:["planos","pricing"],retrievalProfile:"utility"},{commandId:"billing",number:45,aliases:["bill","subscription","sub"],retrievalProfile:"utility"},{commandId:"subscribe",number:46,aliases:["upgrade","checkout"],retrievalProfile:"utility"},{commandId:"qa-scan",number:47,aliases:["qa","qa-test","visual-qa","e2e-scan","troubleshoot","debug-ui","scan","a11y","accessibility","wcag"],retrievalProfile:"qa"},{commandId:"yoloop",number:48,aliases:["auto-yolo","epic-runner","story-runner","loop-yolo","auto-epic"],retrievalProfile:"utility"},{commandId:"migrate-state",number:49,aliases:["migrate","state-migrate","schema-migrate"],retrievalProfile:"utility"},{commandId:"policy-audit",number:50,aliases:["policy","audit-policy","policy-history","policies"],retrievalProfile:"utility"},{commandId:"mutation-test",number:51,aliases:["mutation","stryker","kill-mutants"],retrievalProfile:"qa"},{commandId:"sync-openapi",number:52,aliases:["openapi-sync","api-sync","spec-sync","regen-openapi"],retrievalProfile:"utility"},{commandId:"generate-pacts",number:53,aliases:["pacts","gen-pacts","regen-pacts","create-pacts"],retrievalProfile:"utility"},{commandId:"verify-pacts",number:54,aliases:["verify-pact","pact-verify","check-pacts","pact-check"],retrievalProfile:"utility"},{commandId:"property-test",number:55,aliases:["property","pbt","proptest","property-tests","invariant-test"],retrievalProfile:"qa"},{commandId:"chaos-plan",number:56,aliases:["chaos","gameday","resilience-test"],retrievalProfile:"utility"},{commandId:"ui-ux-review",number:57,aliases:["ux-review","design-review","visual-review","product-polish"],retrievalProfile:"utility"},{commandId:"solyd-system",number:58,aliases:["security-system","authorized-security","sec-system"],retrievalProfile:"security"},{commandId:"goal",number:59,aliases:["goals","durable-goal","continuity-goal"],retrievalProfile:"continuity"},{commandId:"loop",number:60,aliases:["loops","durable-loop","continuity-loop"],retrievalProfile:"continuity"},{commandId:"jobs",number:61,aliases:["job","continuity-jobs"],retrievalProfile:"continuity"},{commandId:"runner",number:62,aliases:["neocortex-runner","continuity-runner"],retrievalProfile:"continuity"}],g=[{commandId:"diagnose-inline",retrievalProfile:"diagnostic"},{commandId:"research-inline",retrievalProfile:"research"},{commandId:"yolo-inline",retrievalProfile:"story-execution"},{commandId:"goal-tick",retrievalProfile:"continuity"},{commandId:"loop-tick",retrievalProfile:"continuity"}],l=Object.freeze(C.map(u)),p=Object.freeze(g.map(u)),f=Object.freeze([...l,...p]),m=Object.freeze(Object.fromEntries(f.map(e=>[e.commandId,e]))),E=Object.freeze(Object.fromEntries(l.filter(e=>e.number!==void 0).map(e=>[e.number,e]))),_=Object.freeze(Object.fromEntries(l.flatMap(e=>e.aliases.map(a=>[y(a),e.commandId]))));function y(e){return e.trim().toLowerCase().replace(/^\*/,"")}function T(e){return e.trim().split(/\s+/,1)[0]??""}function R(){return l}function S(){return p}function A(){return f}function M(e){const a=T(e);if(!a)return m.menu??null;const t=y(a);return/^\d+$/.test(t)?E[Number.parseInt(t,10)]??null:m[t]??m[_[t]??""]??null}const b={CanonicalMemory:0,Guardrail:1,Debt:2,State:3,Story:4,Epic:5,Command:6,Doc:7,Package:8,Api:9,Route:10,DbSchema:11,Flag:12,BusinessRule:13,Risk:14,PlatformMemory:15};function d(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\.\//,"")}function I(e){return[e.nodeType,`${e.source.kind}:${d(e.source.path).toLowerCase()}`,e.stableId.toLowerCase()].join("|")}function x(e){return e.score??0}function h(e,a){const t=x(a)-x(e);if(t!==0)return t;const o=a.confidence-e.confidence;if(o!==0)return o;const s=e.budgetCost-a.budgetCost;if(s!==0)return s;const n=b[e.nodeType]-b[a.nodeType];if(n!==0)return n;const r=d(e.source.path).localeCompare(d(a.source.path),"en-US");return r!==0?r:e.stableId.localeCompare(a.stableId,"en-US")}function D(e){const a={...P,...e.budgets},t=new Map;for(const r of e.items){const c=t.get(I(r));(!c||h(r,c)<0)&&t.set(I(r),r)}const o=[],s=[];let n=0;for(const r of[...t.values()].sort(h)){const c=n+Math.max(1,r.budgetCost);if(o.length>=a.maxItems||c>a.maxTotalCost){s.push({stableId:r.stableId,source:r.source,reasonCode:"budget_exceeded"});continue}o.push(r),n=c}return{schemaVersion:1,retrievalId:e.retrievalId,query:e.query,budget:{...a,totalCost:n},items:o,skipped:s,warnings:e.warnings??[],generatedAt:e.generatedAt}}export{f as CLIENT_COMMAND_CONTEXT_POLICIES,_ as CLIENT_COMMAND_CONTEXT_POLICY_ALIAS_MAP,m as CLIENT_COMMAND_CONTEXT_POLICY_BY_ID,E as CLIENT_COMMAND_CONTEXT_POLICY_BY_NUMBER,v as CLIENT_GRAPH_RETRIEVAL_PROFILE_BUDGETS,p as CLIENT_INTERNAL_COMMAND_CONTEXT_POLICIES,l as CLIENT_PUBLIC_COMMAND_CONTEXT_POLICIES,N as COMMAND_CONTEXT_RETRIEVAL_PROFILES,P as DEFAULT_GRAPH_RETRIEVAL_BUDGETS,O as GRAPH_RETRIEVAL_CLIENT_CONTRACT_VERSION,L as GRAPH_RETRIEVAL_SCHEMA_VERSION,h as compareGraphRetrievalItems,D as createGraphRetrievalMetadata,A as listClientCommandContextPolicies,S as listClientInternalCommandContextPolicies,R as listClientPublicCommandContextPolicies,y as normalizeCommandToken,d as normalizeGraphRetrievalPath,M as resolveClientCommandContextPolicy};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * First-run messages -- localized welcome strings shown on the user's
6
+ * first `neocortex-client invoke` call. Writes to stderr so it never
7
+ * contaminates instruction output. See P76.02.
8
+ */
9
+ export type FirstRunLocale = 'pt-BR' | 'en';
10
+ export interface FirstRunMessage {
11
+ readonly banner: string;
12
+ readonly intro: string;
13
+ readonly commands: readonly {
14
+ label: string;
15
+ description: string;
16
+ }[];
17
+ readonly tip: string;
18
+ }
19
+ export declare const FIRST_RUN_MESSAGES: Record<FirstRunLocale, FirstRunMessage>;
20
+ /** Detect the best locale from process.env.LANG / LC_ALL. Falls back to en. */
21
+ export declare function detectFirstRunLocale(env?: NodeJS.ProcessEnv): FirstRunLocale;
22
+ /** Render the first-run message as a plain-text block suitable for stderr. */
23
+ export declare function renderFirstRunMessage(locale: FirstRunLocale): string;
@@ -0,0 +1,2 @@
1
+ const i={en:{banner:"\u2500\u2500 Welcome to Neocortex \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",intro:"Looks like this is your first time here. Here are a few commands to get started:",commands:[{label:"@neocortex *menu",description:"See all available commands"},{label:"@neocortex *arch-plan",description:"Plan a new project architecture"},{label:"@neocortex *yolo",description:"Quick implementation mode"},{label:"@neocortex *status",description:"Check your project status"}],tip:"Tip: run `@neocortex *menu` for the full, tier-aware command list."},"pt-BR":{banner:"\u2500\u2500 Bem-vindo ao Neocortex \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",intro:"Parece que esta \xE9 a sua primeira vez por aqui. Alguns comandos para come\xE7ar:",commands:[{label:"@neocortex *menu",description:"Ver todos os comandos dispon\xEDveis"},{label:"@neocortex *arch-plan",description:"Planejar a arquitetura de um novo projeto"},{label:"@neocortex *yolo",description:"Modo de implementa\xE7\xE3o r\xE1pida"},{label:"@neocortex *status",description:"Ver o status do seu projeto"}],tip:"Dica: execute `@neocortex *menu` para a lista completa (j\xE1 filtrada pelo seu tier)."}};function c(t=process.env){return(t.LC_ALL??t.LANG??"").toLowerCase().startsWith("pt")?"pt-BR":"en"}function p(t){const o=i[t],n=62,s=o.commands.reduce((r,a)=>Math.max(r,a.label.length),0),e=[];e.push(o.banner),e.push(""),e.push(o.intro),e.push("");for(const r of o.commands){const a=r.label.padEnd(s+2);e.push(` ${a}${r.description}`)}return e.push(""),e.push(o.tip),e.push("".padEnd(n,"\u2500")),e.push(""),e.join(`
2
+ `)}export{i as FIRST_RUN_MESSAGES,c as detectFirstRunLocale,p as renderFirstRunMessage};
@@ -0,0 +1,56 @@
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 - Thin Client Abstraction Layer
15
+ *
16
+ * Strategy pattern for transparent asset resolution from either
17
+ * local filesystem (development) or remote server (production).
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { createResolver, collectContext } from '@neocortex/client';
22
+ *
23
+ * // Auto-detect resolver based on environment
24
+ * const resolver = await createResolver();
25
+ *
26
+ * // Collect pipeline context
27
+ * const context = await collectContext({
28
+ * projectRoot: process.cwd(),
29
+ * storyFilePath: 'docs/stories/1.1.story.md',
30
+ * storyId: '1.1',
31
+ * stepId: 'step-c-06-implement-tasks',
32
+ * });
33
+ *
34
+ * // Resolve a step (works the same whether local or remote)
35
+ * const step = await resolver.resolveStep('step-c-01-setup-branch', context);
36
+ * ```
37
+ */
38
+ export type { AssembledPrompt, CacheProvider, CodebaseMetadata, CreateResolverOptions, LocalResolverOptions, PipelineContext, RemoteResolverOptions, SkillContent, StandardContent, StepContent, StepRegistry, StepRegistryEntry, StoryMetadata, } from './types/index.js';
39
+ export { ResolverMode, NoOpCache } from './types/index.js';
40
+ export type { AssetResolver } from './resolvers/asset-resolver.js';
41
+ export { LocalResolver } from './resolvers/local-resolver.js';
42
+ export { RemoteResolver, RemoteResolverError } from './resolvers/remote-resolver.js';
43
+ export { EncryptedCache, type EncryptedCacheOptions } from './cache/index.js';
44
+ export { createResolver, selectResolver, type ResolverSelectionResult, } from './config/resolver-selection.js';
45
+ export { collectContext, type CollectContextOptions, } from './context/context-collector.js';
46
+ export { sanitizeValue, sanitizeRecord, sanitizeObject, } from './context/context-sanitizer.js';
47
+ export { getMachineFingerprint } from './machine/index.js';
48
+ export { LicenseClient, type LicenseClientOptions } from './license/index.js';
49
+ export type { InjectionMethod, PlatformInstructions, TargetAdapter, TargetCapabilities, TargetConfig, DetectionContext, DetectionResult, FileExistsCheck, TargetId, } from './adapters/index.js';
50
+ export { ClaudeCodeAdapter, CursorAdapter, VSCodeAdapter, GeminiAdapter, CodexAdapter, AntigravityAdapter, AdapterRegistry, UnknownTargetError, createDefaultRegistry, detectPlatform, isValidTargetId, } from './adapters/index.js';
51
+ export { ClientCircuitBreaker, type CircuitState, type CircuitBreakerConfig, type CircuitBreakerState, DegradationManager, DegradationLevel, type DegradationContext, type DegradationDecision, FreshnessIndicator, type FreshnessInfo, RecoveryDetector, type RecoveryActions, type RecoveryResult, } from './resilience/index.js';
52
+ export { OfflineTelemetryQueue, type TelemetryEvent, type QueueConfig, type QueueStats, type FlushResult, } from './telemetry/index.js';
53
+ export { getCacheStatus, formatCacheStatus, type CacheStatusInfo, type CacheStatusOptions, } from './commands/cache-status.js';
54
+ export { invoke, invokeCliHandler, collectStateSnapshot, type InvokeOptions, type InvokeResult, } from './commands/invoke.js';
55
+ export { TierAwareClient, type TierAwareClientOptions, type PreFlightResult, type QuotaSnapshot, } from './tier/index.js';
56
+ export { buildProjectMemoryContent, createNodeProjectMemoryFs, writeProjectMemory, writeProjectMemoryTargetFiles, type WriteProjectMemoryFileResult, type ProjectMemoryWriterFs, type WriteProjectMemoryOptions, type WriteProjectMemoryResult, type WriteProjectMemoryTargetFilesResult, } from './memory/project-memory-writer.js';
@@ -0,0 +1 @@
1
+ import{ResolverMode as t,NoOpCache as o}from"./types/index.js";import{LocalResolver as i}from"./resolvers/local-resolver.js";import{RemoteResolver as c,RemoteResolverError as l}from"./resolvers/remote-resolver.js";import{EncryptedCache as m}from"./cache/index.js";import{createResolver as s,selectResolver as f}from"./config/resolver-selection.js";import{collectContext as C}from"./context/context-collector.js";import{sanitizeValue as R,sanitizeRecord as v,sanitizeObject as u}from"./context/context-sanitizer.js";import{getMachineFingerprint as A}from"./machine/index.js";import{LicenseClient as M}from"./license/index.js";import{ClaudeCodeAdapter as P,CursorAdapter as S,VSCodeAdapter as T,GeminiAdapter as k,CodexAdapter as w,AntigravityAdapter as D,AdapterRegistry as F,UnknownTargetError as z,createDefaultRegistry as E,detectPlatform as L,isValidTargetId as O}from"./adapters/index.js";import{ClientCircuitBreaker as b,DegradationManager as I,DegradationLevel as N,FreshnessIndicator as B,RecoveryDetector as G}from"./resilience/index.js";import{OfflineTelemetryQueue as Q}from"./telemetry/index.js";import{getCacheStatus as q,formatCacheStatus as J}from"./commands/cache-status.js";import{invoke as W,invokeCliHandler as X,collectStateSnapshot as Y}from"./commands/invoke.js";import{TierAwareClient as _}from"./tier/index.js";import{buildProjectMemoryContent as ee,createNodeProjectMemoryFs as re,writeProjectMemory as te,writeProjectMemoryTargetFiles as oe}from"./memory/project-memory-writer.js";export{F as AdapterRegistry,D as AntigravityAdapter,P as ClaudeCodeAdapter,b as ClientCircuitBreaker,w as CodexAdapter,S as CursorAdapter,N as DegradationLevel,I as DegradationManager,m as EncryptedCache,B as FreshnessIndicator,k as GeminiAdapter,M as LicenseClient,i as LocalResolver,o as NoOpCache,Q as OfflineTelemetryQueue,G as RecoveryDetector,c as RemoteResolver,l as RemoteResolverError,t as ResolverMode,_ as TierAwareClient,z as UnknownTargetError,T as VSCodeAdapter,ee as buildProjectMemoryContent,C as collectContext,Y as collectStateSnapshot,E as createDefaultRegistry,re as createNodeProjectMemoryFs,s as createResolver,L as detectPlatform,J as formatCacheStatus,q as getCacheStatus,A as getMachineFingerprint,W as invoke,X as invokeCliHandler,O as isValidTargetId,u as sanitizeObject,v as sanitizeRecord,R as sanitizeValue,f as selectResolver,te as writeProjectMemory,oe as writeProjectMemoryTargetFiles};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ */
5
+ export { LicenseClient, type LicenseClientOptions } from './license-client.js';
@@ -0,0 +1 @@
1
+ import{LicenseClient as n}from"./license-client.js";export{n as LicenseClient};
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * This file is part of Neocortex CLI, licensed under the
6
+ * Functional Source License, Version 1.1 (FSL-1.1).
7
+ *
8
+ * Change Date: February 20, 2029
9
+ * Change License: MIT
10
+ *
11
+ * See the LICENSE file in the project root for full license text.
12
+ */
13
+ import type { CacheProvider } from '../types/index.js';
14
+ export interface LicenseClientOptions {
15
+ readonly serverUrl: string;
16
+ readonly licenseKey: string;
17
+ readonly cacheProvider?: CacheProvider;
18
+ readonly clientVersion?: string;
19
+ }
20
+ interface ActivationResult {
21
+ readonly token: string;
22
+ readonly expiresIn: number;
23
+ readonly refreshToken?: string;
24
+ }
25
+ export declare class LicenseClient {
26
+ private readonly serverUrl;
27
+ private readonly licenseKey;
28
+ private readonly cache;
29
+ private readonly clientVersion;
30
+ private readonly machineId;
31
+ private token;
32
+ private refreshToken;
33
+ constructor(options: LicenseClientOptions);
34
+ /**
35
+ * Get a valid JWT token. Checks memory, cache, refresh token, then activation.
36
+ * NEVER throws - returns null on failure.
37
+ *
38
+ * Flow:
39
+ * 1. in-memory JWT valid? -> return
40
+ * 2. in-memory JWT needs-refresh? -> refresh(refresh_token) -> return
41
+ * 3. cached JWT valid? -> return
42
+ * 4. cached JWT needs-refresh? -> refresh(refresh_token) -> return
43
+ * 5. cached refresh_token exists? -> refresh(refresh_token) -> return (Story 31.02)
44
+ * 6. activate() -> return
45
+ */
46
+ getToken(): Promise<string | null>;
47
+ /**
48
+ * Activate the license by calling POST /api/v1/license/activate.
49
+ * Stores token and refresh_token in memory and cache on success.
50
+ * NEVER throws - returns null on failure.
51
+ */
52
+ activate(): Promise<ActivationResult | null>;
53
+ /**
54
+ * Refresh using refresh_token by calling POST /api/v1/license/refresh.
55
+ * Sends refresh_token in body (no Authorization header needed).
56
+ * Handles token rotation: stores the new refresh_token from response.
57
+ * NEVER throws - returns null on failure.
58
+ *
59
+ * Story 31.02: Signature changed from refresh(currentToken) to refresh().
60
+ * The refresh_token in the body is the credential, not the JWT.
61
+ *
62
+ * @param _currentToken - Deprecated. Kept for backward compat but ignored.
63
+ */
64
+ refresh(_currentToken?: string): Promise<ActivationResult | null>;
65
+ /**
66
+ * Force-refresh the token.
67
+ * Used when tier_changed is detected or a 401 response indicates the token is expired.
68
+ * Falls back to re-activation if refresh fails.
69
+ * NEVER throws - returns new token or null on failure.
70
+ *
71
+ * Story 18.8: Updated to prefer refresh over re-activate (preserves updated tier).
72
+ * Story 31.02: Uses refresh_token flow instead of JWT-based refresh.
73
+ */
74
+ forceRefresh(): Promise<string | null>;
75
+ private checkTokenValidity;
76
+ private loadFromCache;
77
+ private loadRefreshTokenFromCache;
78
+ }
79
+ export {};
@@ -0,0 +1 @@
1
+ import{decodeJwt as c}from"jose";import{NoOpCache as o}from"../types/index.js";import{getMachineFingerprint as a}from"../machine/fingerprint.js";const i="neocortex:jwt:token",s="neocortex:jwt:refresh_token",l=300,h=10080*60*1e3,f="0.1.0";class T{serverUrl;licenseKey;cache;clientVersion;machineId;token=null;refreshToken=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new o,this.clientVersion=e.clientVersion??f,this.machineId=a()}async getToken(){try{if(this.token){const r=this.checkTokenValidity(this.token);if(r==="valid")return this.token;if(r==="needs-refresh")return(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const r=this.checkTokenValidity(e);if(r==="valid")return e;if(r==="needs-refresh")return(await this.refresh())?.token??e;this.token=null}if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const r=await this.refresh();if(r?.token)return r.token}return(await this.activate())?.token??null}catch{return null}}async activate(){try{const e=await fetch(`${this.serverUrl}/api/v1/license/activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({license_key:this.licenseKey,machine_id:this.machineId,client_version:this.clientVersion})});if(!e.ok)return null;const t=await e.json();return this.token=t.token,this.refreshToken=t.refresh_token??null,this.cache.set(i,t.token,t.expires_in*1e3).catch(()=>{}),t.refresh_token&&this.cache.set(s,t.refresh_token,h).catch(()=>{}),{token:t.token,expiresIn:t.expires_in,refreshToken:t.refresh_token}}catch{return null}}async refresh(e){try{const t=this.refreshToken??await this.loadRefreshTokenFromCache();if(!t)return null;const r=await fetch(`${this.serverUrl}/api/v1/license/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t})});if(!r.ok)return this.refreshToken=null,this.cache.set(s,"",1).catch(()=>{}),null;const n=await r.json();return this.token=n.token,this.refreshToken=n.refresh_token??null,this.cache.set(i,n.token,n.expires_in*1e3).catch(()=>{}),n.refresh_token&&this.cache.set(s,n.refresh_token,h).catch(()=>{}),{token:n.token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}catch{return null}}async forceRefresh(){try{const e=await this.refresh();return e?.token?e.token:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const t=c(e);if(!t.exp)return"expired";const r=Math.floor(Date.now()/1e3);return t.exp<=r?"expired":t.exp-r<=l?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(i)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(s);return e&&e.length>0?e:null}catch{return null}}}export{T as LicenseClient};
@@ -0,0 +1,34 @@
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
+ * Generate a hardware-based fingerprint (not persisted).
15
+ * This is the original computation used as fallback and for seeding.
16
+ *
17
+ * @returns 64-character hex string (SHA-256 digest)
18
+ */
19
+ export declare function computeHardwareFingerprint(): string;
20
+ /**
21
+ * Generate a stable machine fingerprint as a SHA-256 hex digest.
22
+ *
23
+ * Story P26.01: On first call, generates from hardware and persists to
24
+ * ~/.neocortex/.machine-id. On subsequent calls, reads from disk.
25
+ * This ensures the fingerprint remains stable even if hardware attributes
26
+ * change (e.g., USB NIC added/removed, hostname change).
27
+ *
28
+ * Backward compat: if config.json has machineId, uses that to seed .machine-id.
29
+ *
30
+ * Fail-open: if disk operations fail, falls back to hardware-generated fingerprint.
31
+ *
32
+ * @returns 64-character hex string (SHA-256 digest)
33
+ */
34
+ export declare function getMachineFingerprint(): string;
@@ -0,0 +1,2 @@
1
+ import{createHash as p}from"node:crypto";import{existsSync as s,readFileSync as a,writeFileSync as h,mkdirSync as d,chmodSync as g}from"node:fs";import{join as o}from"node:path";import{arch as y,cpus as F,homedir as I,hostname as M,networkInterfaces as S,platform as w}from"node:os";const $="00:00:00:00:00:00",i=o(I(),".neocortex"),c=o(i,".machine-id");function E(){const t=S(),n=[];for(const e of Object.values(t))if(e)for(const r of e)!r.internal&&r.mac!==$&&n.push(r.mac);return[...new Set(n)].sort()}function x(){const t=M(),n=w(),e=y(),r=F(),u=r.length>0?r[0].model:"",m=E(),l=`${t}|${n}|${e}|${u}|${m.join(",")}`;return p("sha256").update(l).digest("hex")}function C(t){try{process.platform!=="win32"&&g(t,384)}catch{}}function O(){try{if(!s(c))return null;const t=a(c,"utf-8").trim();return/^[a-f0-9]{64}$/.test(t)?t:null}catch{return null}}function f(t){try{d(i,{recursive:!0}),h(c,t+`
2
+ `,"utf-8"),C(c)}catch{}}function _(){try{const t=o(i,"config.json");if(!s(t))return null;const n=a(t,"utf-8"),r=JSON.parse(n.replace(/^\uFEFF/,"")).machineId;return typeof r=="string"&&/^[a-f0-9]{64}$/.test(r)?r:null}catch{return null}}function N(){const t=O();if(t)return t;const n=_();if(n)return f(n),n;const e=x();return f(e),e}export{x as computeHardwareFingerprint,N as getMachineFingerprint};
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ */
5
+ export { getMachineFingerprint } from './fingerprint.js';
@@ -0,0 +1 @@
1
+ import{getMachineFingerprint as i}from"./fingerprint.js";export{i as getMachineFingerprint};
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Project memory writer for platform-specific always-loaded files.
3
+ *
4
+ * The writer owns only the NEOCORTEX-MEMORY block. Everything outside that
5
+ * block is preserved byte-for-byte so users can keep local instructions.
6
+ */
7
+ import { type ArchitectureReference, type BootstrapArchitectureMemory, type ProjectMemoryTarget, type ProjectMemoryTargetId } from './shared-project-memory-types.js';
8
+ export interface ProjectMemoryWriterFs {
9
+ readFile(path: string): string | undefined;
10
+ writeFileAtomic(path: string, content: string): {
11
+ backupPath?: string;
12
+ };
13
+ join(...parts: string[]): string;
14
+ }
15
+ export interface WriteProjectMemoryOptions {
16
+ readonly projectRoot: string;
17
+ readonly targetId: ProjectMemoryTargetId;
18
+ readonly memoryNotes?: readonly string[];
19
+ readonly architectureReferences?: readonly ArchitectureReference[];
20
+ readonly bootstrapArchitecture?: BootstrapArchitectureMemory;
21
+ readonly fs?: ProjectMemoryWriterFs;
22
+ readonly symlinkCapability?: ProjectMemorySymlinkCapability;
23
+ readonly dryRun?: boolean;
24
+ }
25
+ export interface ProjectMemorySymlinkCapability {
26
+ readonly os: NodeJS.Platform | string;
27
+ readonly supported: boolean;
28
+ readonly permission: 'ok' | 'denied' | 'unknown';
29
+ readonly filesystem: 'supports-symlink' | 'no-symlink-support' | 'unknown';
30
+ readonly targetPolicy: ProjectMemoryTarget['linkRequirement']['policy'];
31
+ readonly targetPolicyAllowsSymlink: boolean;
32
+ readonly requiresWrapperPreservation: boolean;
33
+ readonly reason?: string;
34
+ }
35
+ export interface WriteProjectMemoryResult {
36
+ readonly filePath: string;
37
+ readonly changed: boolean;
38
+ readonly content: string;
39
+ readonly safeDiff?: string;
40
+ readonly backupPath?: string;
41
+ readonly reasonCodes?: readonly string[];
42
+ }
43
+ export interface WriteProjectMemoryFileResult extends WriteProjectMemoryResult {
44
+ readonly relativeFile: string;
45
+ readonly mode: 'canonical' | 'semantic-symlink' | 'managed-wrapper' | 'compatibility-materialized-fallback';
46
+ readonly canonicalSource: string;
47
+ readonly symlinkCapability?: ProjectMemorySymlinkCapability;
48
+ readonly fallbackReason?: string;
49
+ readonly remediationDebt?: string;
50
+ }
51
+ export interface WriteProjectMemoryTargetFilesResult {
52
+ readonly targetId: ProjectMemoryTargetId;
53
+ readonly canonicalFilePath: string;
54
+ readonly files: readonly WriteProjectMemoryFileResult[];
55
+ readonly changed: boolean;
56
+ }
57
+ export declare function createNodeProjectMemoryFs(): ProjectMemoryWriterFs;
58
+ export declare const PROJECT_MEMORY_LAYER_CATEGORIES: readonly ["skills-agents", "frontend", "backend", "api", "db", "schemas", "envs", "devops", "cyber-security", "testing-qa", "observability", "product-business", "docs-architecture", "platform-memory", "command-behavior", "generic"];
59
+ export type ProjectMemoryLayerCategory = typeof PROJECT_MEMORY_LAYER_CATEGORIES[number];
60
+ export type ProjectMemoryChangeKind = 'feature' | 'rule' | 'flag' | 'route' | 'api' | 'db-schema' | 'architecture' | 'debt' | 'decision' | 'generic';
61
+ export interface ClassifiedProjectMemoryUpdate {
62
+ readonly kind: ProjectMemoryChangeKind;
63
+ readonly layer: ProjectMemoryLayerCategory;
64
+ readonly sectionTitle: string;
65
+ readonly summary: string;
66
+ readonly reasonCode: string;
67
+ }
68
+ export declare function classifyProjectMemoryUpdate(value: string): ClassifiedProjectMemoryUpdate;
69
+ export declare function createSafeProjectMemoryDiff(before: string | undefined, after: string): string;
70
+ export declare function bootstrapArchitectureMemory(projectRoot: string): BootstrapArchitectureMemory;
71
+ export declare function buildProjectMemoryContent(target: ProjectMemoryTarget, existingContent: string | undefined, memoryNotes?: readonly string[], architectureReferences?: readonly ArchitectureReference[], bootstrapArchitecture?: BootstrapArchitectureMemory): string;
72
+ export declare function writeProjectMemory(options: WriteProjectMemoryOptions): WriteProjectMemoryResult;
73
+ export declare function writeCanonicalProjectMemory(options: Omit<WriteProjectMemoryOptions, 'targetId'>): WriteProjectMemoryResult;
74
+ export declare function writeProjectMemoryTargetFiles(options: WriteProjectMemoryOptions): WriteProjectMemoryTargetFilesResult;