@ornexus/neocortex 4.60.66 → 4.60.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1598 -1640
  3. package/install.ps1 +1 -1
  4. package/install.sh +2 -1
  5. package/package.json +10 -7
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +212 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +417 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +251 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +108 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +303 -3
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.d.ts +135 -0
  37. package/packages/client/dist/commands/doctor.js +635 -0
  38. package/packages/client/dist/commands/invoke.d.ts +18 -0
  39. package/packages/client/dist/commands/invoke.js +7140 -142
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  41. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  42. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  44. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  45. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  46. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  47. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  49. package/packages/client/dist/commands/mutation-qa.js +220 -1
  50. package/packages/client/dist/commands/native-agent.js +136 -2
  51. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  52. package/packages/client/dist/commands/planning-generation.js +53 -1
  53. package/packages/client/dist/commands/planning-memory.js +40 -1
  54. package/packages/client/dist/commands/planning-research.js +42 -1
  55. package/packages/client/dist/commands/private-session.js +75 -1
  56. package/packages/client/dist/commands/property-qa.js +139 -1
  57. package/packages/client/dist/commands/qa-control.js +16 -1
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  60. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  61. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  62. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  68. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  69. package/packages/client/dist/commands/refactor-commit.js +399 -13
  70. package/packages/client/dist/commands/refactor-control.js +142 -3
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  72. package/packages/client/dist/commands/refactor-review.js +283 -5
  73. package/packages/client/dist/commands/refactor-root.js +588 -7
  74. package/packages/client/dist/commands/refresh-memory.js +156 -3
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  76. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  77. package/packages/client/dist/config/profile-directory.js +13 -1
  78. package/packages/client/dist/config/resolver-selection.js +278 -1
  79. package/packages/client/dist/config/secure-config.js +281 -12
  80. package/packages/client/dist/config.js +223 -2
  81. package/packages/client/dist/constants.js +25 -1
  82. package/packages/client/dist/context/context-collector.js +222 -2
  83. package/packages/client/dist/context/context-sanitizer.js +145 -1
  84. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  85. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  86. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  87. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  88. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  89. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  90. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  91. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  92. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  93. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  94. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  95. package/packages/client/dist/continuity/outbox.js +117 -1
  96. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  97. package/packages/client/dist/continuity/sqlite-store.js +2536 -81
  98. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  99. package/packages/client/dist/errors/error-messages.js +228 -2
  100. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  101. package/packages/client/dist/evidence/collector.js +347 -1
  102. package/packages/client/dist/evidence/index.js +1 -1
  103. package/packages/client/dist/evidence/types.js +2 -0
  104. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  105. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  106. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  107. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  108. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  109. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  110. package/packages/client/dist/git/git-lifecycle-store.js +1938 -9
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  113. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  117. package/packages/client/dist/i18n/first-run.js +60 -2
  118. package/packages/client/dist/index.js +47 -1
  119. package/packages/client/dist/invocation/invoke-input.js +24 -1
  120. package/packages/client/dist/license/index.js +5 -1
  121. package/packages/client/dist/license/license-client.js +304 -1
  122. package/packages/client/dist/machine/fingerprint.js +163 -2
  123. package/packages/client/dist/machine/index.js +5 -1
  124. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  125. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  126. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  127. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  128. package/packages/client/dist/migrations/project-identity.js +493 -7
  129. package/packages/client/dist/migrations/state-json.js +344 -4
  130. package/packages/client/dist/policy/architecture-policy.js +184 -2
  131. package/packages/client/dist/policy/index.js +7 -1
  132. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  133. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  134. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  135. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  136. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  137. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  138. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  139. package/packages/client/dist/private-execution/delivery.js +410 -13
  140. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  141. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  142. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  143. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  144. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  145. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  146. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  147. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  148. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  149. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  150. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  151. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  152. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  153. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  154. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  155. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  156. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  157. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  158. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  159. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  160. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  161. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  162. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  163. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  164. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  165. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  166. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  167. package/packages/client/dist/private-execution/session-lease.js +63 -1
  168. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  169. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  170. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  171. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  172. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  173. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  174. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  175. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  176. package/packages/client/dist/resilience/index.js +8 -1
  177. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  178. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  179. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  180. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  181. package/packages/client/dist/runner/binary.js +404 -1
  182. package/packages/client/dist/runner/cli.js +1571 -17
  183. package/packages/client/dist/runner/headless/adapters.js +49 -1
  184. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  185. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  186. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  187. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  188. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  189. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  190. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  191. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  192. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  193. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  194. package/packages/client/dist/runner/headless/resolver.js +231 -1
  195. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  196. package/packages/client/dist/runner/headless/run-yoloop.d.ts +4 -1
  197. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  198. package/packages/client/dist/runner/headless/types.js +574 -2
  199. package/packages/client/dist/runner/local-console.js +396 -13
  200. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  201. package/packages/client/dist/runner/project-identity.js +106 -1
  202. package/packages/client/dist/runner/scheduler.js +995 -7
  203. package/packages/client/dist/runner-cli.js +18 -2
  204. package/packages/client/dist/state/invocation-shape.js +13 -1
  205. package/packages/client/dist/state/project-state-snapshot.js +1677 -1
  206. package/packages/client/dist/state/state-json-repair.js +785 -3
  207. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  208. package/packages/client/dist/telemetry/index.js +5 -1
  209. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  210. package/packages/client/dist/tier/index.js +5 -1
  211. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  212. package/packages/client/dist/types/index.js +38 -1
  213. package/packages/client/dist/version.js +27 -1
  214. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  215. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  216. package/packages/client/dist/yolo/spec-envelope-collector.js +185 -5
  217. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  218. package/packages/client/dist/yoloop/index.js +8 -1
  219. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  220. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  221. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  222. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  223. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1723 -1
  224. package/packages/shared/dist/compatibility/index.js +476 -0
  225. package/packages/shared/dist/yoloop/release-blocked.js +653 -0
  226. package/targets-stubs/antigravity/gemini.md +1 -1
  227. package/targets-stubs/antigravity/skill/SKILL.md +3 -2
  228. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  229. package/targets-stubs/claude-code/neocortex-root.md +5 -5
  230. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  231. package/targets-stubs/claude-code/neocortex.md +8 -9
  232. package/targets-stubs/codex/AGENTS.md +3 -3
  233. package/targets-stubs/cursor/agent.md +4 -3
  234. package/targets-stubs/gemini-cli/agent.md +5 -4
  235. package/targets-stubs/opencode/neocortex-root.md +3 -3
  236. package/targets-stubs/vscode/neocortex.agent.md +5 -4
@@ -1,8 +1,255 @@
1
- import{readFile as f,access as d}from"node:fs/promises";import{join as h,resolve as y}from"node:path";import{ResolverMode as w}from"../types/index.js";const v=/^---\n([\s\S]*?)\n---/;function u(p){const t=p.match(v);if(!t)return{frontmatter:{},body:p};const s={},e=t[1].split(`
2
- `);for(const o of e){const n=o.indexOf(":");if(n===-1)continue;const a=o.slice(0,n).trim().replace(/^['"]|['"]$/g,"");let r=o.slice(n+1).trim();typeof r=="string"&&(r=r.replace(/^['"]|['"]$/g,"")),r==="true"?r=!0:r==="false"&&(r=!1),s[a]=r}const c=p.slice(t[0].length).trimStart();return{frontmatter:s,body:c}}class P{mode=w.LOCAL;projectRoot;stepPathIndex;constructor(t){this.projectRoot=y(t.projectRoot)}async resolveStep(t,s){const e=(await this.resolveStepPathIndex()).get(t);if(!e)throw new Error(`Step '${t}' is not present in the canonical registry`);const c=h(this.projectRoot,e),o=await f(c,"utf-8"),{frontmatter:n,body:a}=u(o);return{id:t,content:a,frontmatter:n}}resolveStepPathIndex(){return this.stepPathIndex??=this.loadStepPathIndex(),this.stepPathIndex}async loadStepPathIndex(){const t=h(this.projectRoot,"core","data","step-registry.json"),s=JSON.parse(await f(t,"utf8")),e=new Map,c=s.asset_bootstrap;if(c&&typeof c=="object"&&!Array.isArray(c)){const o=c.assets;if(!Array.isArray(o))throw new Error("manifest-generation-mismatch");for(const n of o){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("manifest-schema-invalid");const a=n;if(a.type!=="step")continue;const r=a.relative_path;if(typeof r!="string"||!r.startsWith("steps/")||r.includes(".."))throw new Error("manifest-schema-invalid");const i=`core/${r}`,{frontmatter:l}=u(await f(h(this.projectRoot,i),"utf8")),m=l.id;if(typeof m!="string"||!/^step-[a-z0-9][a-z0-9._-]*$/.test(m))throw new Error("manifest-required-step-unresolved");if(e.has(m))throw new Error("manifest-duplicate-reference");e.set(m,i)}}else{const o=s.steps;if(!o||typeof o!="object"||Array.isArray(o))throw new Error("manifest-generation-mismatch");for(const n of Object.values(o))if(Array.isArray(n))for(const a of n){if(!a||typeof a!="object"||Array.isArray(a))throw new Error("manifest-schema-invalid");const r=a,i=r.id,l=r.file;if(typeof i!="string"||typeof l!="string"||!l.startsWith("core/steps/")||l.includes(".."))throw new Error("manifest-schema-invalid");if(e.has(i))throw new Error("manifest-duplicate-reference");e.set(i,l)}}if(e.size===0)throw new Error("manifest-generation-mismatch");return e}async resolveSkill(t,s){const e=[`core/skills/${t}.md`,`core/skills/step-skills/${t}.md`];t.includes("/")&&(e.unshift(`core/skills/step-skills/${t}.md`),e.unshift(`core/skills/${t}.md`));let c=null,o="";for(const r of e){const i=h(this.projectRoot,r);try{c=await f(i,"utf-8"),o=r;break}catch{}}if(c===null)throw new Error(`Skill '${t}' not found. Searched: ${e.join(", ")}`);const{frontmatter:n,body:a}=u(c);return{id:t,content:a,metadata:{...n,resolvedPath:o}}}async resolveStandard(t){const s=h(this.projectRoot,"core","standards",t);let e;try{e=await f(s,"utf-8")}catch{if(!t.endsWith(".md"))e=await f(`${s}.md`,"utf-8");else throw new Error(`Standard '${t}' not found at ${s}`)}return{id:t,content:e}}async resolveRegistry(){const t=h(this.projectRoot,"core","data","step-registry.json"),s=await f(t,"utf-8");return JSON.parse(s)}async assemblePrompt(t,s){const e=await this.resolveStep(t,s),c={"{story_id}":s.storyId,"{story_title}":s.storyTitle,"{step_id}":t,"{step_name}":e.frontmatter.name||t,"{current_status}":s.currentStatus,"{epic_id}":s.epicId,"{branch_name}":s.branchName,"{platform_target}":s.platformTarget};let o=e.content;for(const[r,i]of Object.entries(c))o=o.replaceAll(r,i);const n=[],a=e.frontmatter.skills;if(a&&typeof a=="string"){const r=a.split(",").map(i=>i.trim());for(const i of r)try{const l=await this.resolveSkill(i,s);o+=`
3
-
4
- ---
5
-
6
- # Skill: ${i}
7
-
8
- ${l.content}`,n.push(i)}catch{}}return{prompt:o,variables:c,includedSkills:n,includedStandards:[]}}async isAvailable(){try{const t=h(this.projectRoot,"core");return await d(t),!0}catch{return!1}}async dispose(){}}export{P as LocalResolver};
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 - LocalResolver
15
+ *
16
+ * Resolves pipeline assets from the local filesystem.
17
+ * Used in development mode when core/ directory is available locally.
18
+ * Replicates the current CLI behavior of reading .md files directly.
19
+ */
20
+ import { readFile, access } from 'node:fs/promises';
21
+ import { join, resolve } from 'node:path';
22
+ import { ResolverMode, } from '../types/index.js';
23
+ // ── Frontmatter Parser ───────────────────────────────────────────────────
24
+ const FRONTMATTER_REGEX = /^---\n([\s\S]*?)\n---/;
25
+ /**
26
+ * Parse YAML-like frontmatter from markdown content.
27
+ * Simple key-value parser sufficient for step/skill frontmatter.
28
+ */
29
+ function parseFrontmatter(content) {
30
+ const match = content.match(FRONTMATTER_REGEX);
31
+ if (!match) {
32
+ return { frontmatter: {}, body: content };
33
+ }
34
+ const frontmatter = {};
35
+ const lines = match[1].split('\n');
36
+ for (const line of lines) {
37
+ const colonIndex = line.indexOf(':');
38
+ if (colonIndex === -1)
39
+ continue;
40
+ const key = line.slice(0, colonIndex).trim().replace(/^['"]|['"]$/g, '');
41
+ let value = line.slice(colonIndex + 1).trim();
42
+ // Remove surrounding quotes
43
+ if (typeof value === 'string') {
44
+ value = value.replace(/^['"]|['"]$/g, '');
45
+ }
46
+ // Parse booleans
47
+ if (value === 'true')
48
+ value = true;
49
+ else if (value === 'false')
50
+ value = false;
51
+ frontmatter[key] = value;
52
+ }
53
+ const body = content.slice(match[0].length).trimStart();
54
+ return { frontmatter, body };
55
+ }
56
+ // ── LocalResolver Implementation ─────────────────────────────────────────
57
+ export class LocalResolver {
58
+ mode = ResolverMode.LOCAL;
59
+ projectRoot;
60
+ stepPathIndex;
61
+ constructor(options) {
62
+ this.projectRoot = resolve(options.projectRoot);
63
+ }
64
+ async resolveStep(stepId, _context) {
65
+ const relativePath = (await this.resolveStepPathIndex()).get(stepId);
66
+ if (!relativePath)
67
+ throw new Error(`Step '${stepId}' is not present in the canonical registry`);
68
+ const fullPath = join(this.projectRoot, relativePath);
69
+ const raw = await readFile(fullPath, 'utf-8');
70
+ const { frontmatter, body } = parseFrontmatter(raw);
71
+ return {
72
+ id: stepId,
73
+ content: body,
74
+ frontmatter,
75
+ };
76
+ }
77
+ resolveStepPathIndex() {
78
+ this.stepPathIndex ??= this.loadStepPathIndex();
79
+ return this.stepPathIndex;
80
+ }
81
+ async loadStepPathIndex() {
82
+ const registryPath = join(this.projectRoot, 'core', 'data', 'step-registry.json');
83
+ const parsed = JSON.parse(await readFile(registryPath, 'utf8'));
84
+ const index = new Map();
85
+ const bootstrap = parsed['asset_bootstrap'];
86
+ if (bootstrap && typeof bootstrap === 'object' && !Array.isArray(bootstrap)) {
87
+ const assets = bootstrap['assets'];
88
+ if (!Array.isArray(assets))
89
+ throw new Error('manifest-generation-mismatch');
90
+ for (const raw of assets) {
91
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
92
+ throw new Error('manifest-schema-invalid');
93
+ const asset = raw;
94
+ if (asset['type'] !== 'step')
95
+ continue;
96
+ const assetPath = asset['relative_path'];
97
+ if (typeof assetPath !== 'string' || !assetPath.startsWith('steps/') || assetPath.includes('..')) {
98
+ throw new Error('manifest-schema-invalid');
99
+ }
100
+ const relativePath = `core/${assetPath}`;
101
+ const { frontmatter } = parseFrontmatter(await readFile(join(this.projectRoot, relativePath), 'utf8'));
102
+ const id = frontmatter['id'];
103
+ if (typeof id !== 'string' || !/^step-[a-z0-9][a-z0-9._-]*$/.test(id)) {
104
+ throw new Error('manifest-required-step-unresolved');
105
+ }
106
+ if (index.has(id))
107
+ throw new Error('manifest-duplicate-reference');
108
+ index.set(id, relativePath);
109
+ }
110
+ }
111
+ else {
112
+ // Explicit legacy partial projection: exact registry files only, with no
113
+ // category/path inference after a miss.
114
+ const groups = parsed['steps'];
115
+ if (!groups || typeof groups !== 'object' || Array.isArray(groups))
116
+ throw new Error('manifest-generation-mismatch');
117
+ for (const entries of Object.values(groups)) {
118
+ if (!Array.isArray(entries))
119
+ continue;
120
+ for (const raw of entries) {
121
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
122
+ throw new Error('manifest-schema-invalid');
123
+ const entry = raw;
124
+ const id = entry['id'];
125
+ const file = entry['file'];
126
+ if (typeof id !== 'string' || typeof file !== 'string' || !file.startsWith('core/steps/') || file.includes('..')) {
127
+ throw new Error('manifest-schema-invalid');
128
+ }
129
+ if (index.has(id))
130
+ throw new Error('manifest-duplicate-reference');
131
+ index.set(id, file);
132
+ }
133
+ }
134
+ }
135
+ if (index.size === 0)
136
+ throw new Error('manifest-generation-mismatch');
137
+ return index;
138
+ }
139
+ async resolveSkill(skillId, _context) {
140
+ // Skills are organized in: core/skills/{category}/{skillId}.md
141
+ // or: core/skills/step-skills/{step}/{skillId}.md
142
+ // Try multiple paths to find the skill
143
+ const searchPaths = [
144
+ `core/skills/${skillId}.md`,
145
+ `core/skills/step-skills/${skillId}.md`,
146
+ ];
147
+ // Also try with nested path: "diagnose/prompt-enricher" -> core/skills/step-skills/diagnose/prompt-enricher.md
148
+ if (skillId.includes('/')) {
149
+ searchPaths.unshift(`core/skills/step-skills/${skillId}.md`);
150
+ searchPaths.unshift(`core/skills/${skillId}.md`);
151
+ }
152
+ let raw = null;
153
+ let resolvedPath = '';
154
+ for (const searchPath of searchPaths) {
155
+ const fullPath = join(this.projectRoot, searchPath);
156
+ try {
157
+ raw = await readFile(fullPath, 'utf-8');
158
+ resolvedPath = searchPath;
159
+ break;
160
+ }
161
+ catch {
162
+ // Try next path
163
+ }
164
+ }
165
+ if (raw === null) {
166
+ throw new Error(`Skill '${skillId}' not found. Searched: ${searchPaths.join(', ')}`);
167
+ }
168
+ const { frontmatter, body } = parseFrontmatter(raw);
169
+ return {
170
+ id: skillId,
171
+ content: body,
172
+ metadata: { ...frontmatter, resolvedPath },
173
+ };
174
+ }
175
+ async resolveStandard(standardId) {
176
+ const fullPath = join(this.projectRoot, 'core', 'standards', standardId);
177
+ let content;
178
+ try {
179
+ content = await readFile(fullPath, 'utf-8');
180
+ }
181
+ catch {
182
+ // Try with .md extension if not present
183
+ if (!standardId.endsWith('.md')) {
184
+ content = await readFile(`${fullPath}.md`, 'utf-8');
185
+ }
186
+ else {
187
+ throw new Error(`Standard '${standardId}' not found at ${fullPath}`);
188
+ }
189
+ }
190
+ return {
191
+ id: standardId,
192
+ content,
193
+ };
194
+ }
195
+ async resolveRegistry() {
196
+ const fullPath = join(this.projectRoot, 'core', 'data', 'step-registry.json');
197
+ const raw = await readFile(fullPath, 'utf-8');
198
+ return JSON.parse(raw);
199
+ }
200
+ async assemblePrompt(stepId, context) {
201
+ // Resolve the step content
202
+ const step = await this.resolveStep(stepId, context);
203
+ // Build variables map from context
204
+ const variables = {
205
+ '{story_id}': context.storyId,
206
+ '{story_title}': context.storyTitle,
207
+ '{step_id}': stepId,
208
+ '{step_name}': step.frontmatter['name'] || stepId,
209
+ '{current_status}': context.currentStatus,
210
+ '{epic_id}': context.epicId,
211
+ '{branch_name}': context.branchName,
212
+ '{platform_target}': context.platformTarget,
213
+ };
214
+ // Substitute variables in step content
215
+ let prompt = step.content;
216
+ for (const [key, value] of Object.entries(variables)) {
217
+ prompt = prompt.replaceAll(key, value);
218
+ }
219
+ // Resolve skills referenced in step frontmatter
220
+ const includedSkills = [];
221
+ const skillsRef = step.frontmatter['skills'];
222
+ if (skillsRef && typeof skillsRef === 'string') {
223
+ const skillIds = skillsRef.split(',').map((s) => s.trim());
224
+ for (const sid of skillIds) {
225
+ try {
226
+ const skill = await this.resolveSkill(sid, context);
227
+ prompt += `\n\n---\n\n# Skill: ${sid}\n\n${skill.content}`;
228
+ includedSkills.push(sid);
229
+ }
230
+ catch {
231
+ // Skill not found - skip
232
+ }
233
+ }
234
+ }
235
+ return {
236
+ prompt,
237
+ variables,
238
+ includedSkills,
239
+ includedStandards: [],
240
+ };
241
+ }
242
+ async isAvailable() {
243
+ try {
244
+ const corePath = join(this.projectRoot, 'core');
245
+ await access(corePath);
246
+ return true;
247
+ }
248
+ catch {
249
+ return false;
250
+ }
251
+ }
252
+ async dispose() {
253
+ // LocalResolver holds no resources to release
254
+ }
255
+ }
@@ -1 +1,233 @@
1
- import{ResolverMode as u,NoOpCache as d}from"../types/index.js";import{CLIENT_VERSION as m}from"../version.js";const y=3e4,f=3,p=1e3,C=1e4;class i extends Error{statusCode;endpoint;constructor(t,e,r){super(t),this.statusCode=e,this.endpoint=r,this.name="RemoteResolverError"}}class v{mode=u.REMOTE;serverUrl;licenseKey;timeout;retryCount;cache;licenseClient;constructor(t){this.serverUrl=t.serverUrl.replace(/\/+$/,""),this.licenseKey=t.licenseKey,this.timeout=t.timeout??y,this.retryCount=t.retryCount??f,this.cache=t.cacheProvider??new d,this.licenseClient=t.licenseClient??null}async resolveStep(t,e){return this.fetchWithRetry({method:"GET",path:`/api/v1/steps/${encodeURIComponent(t)}`})}async resolveSkill(t,e){return this.fetchWithRetry({method:"GET",path:`/api/v1/skills/${encodeURIComponent(t)}`})}async resolveStandard(t){return this.fetchWithRetry({method:"GET",path:`/api/v1/standards/${encodeURIComponent(t)}`})}async resolveRegistry(){return this.fetchWithCacheFallback("registry",{method:"GET",path:"/api/v1/registry"})}async assemblePrompt(t,e){return this.fetchWithRetry({method:"POST",path:"/api/v1/prompts/assemble",body:{stepId:t,context:e}})}async isAvailable(){try{const t=new AbortController,e=setTimeout(()=>t.abort(),5e3),r=await fetch(`${this.serverUrl}/api/v1/health`,{method:"GET",headers:await this.buildHeaders(),signal:t.signal});return clearTimeout(e),r.ok}catch{return!1}}async dispose(){await this.cache.clear()}async buildHeaders(){const t={"Content-Type":"application/json","X-Client-Version":m};if(this.licenseClient){const e=await this.licenseClient.getToken();e&&(t.Authorization=`Bearer ${e}`)}return t}async fetchWithRetry(t){let e,r=!1;for(let a=0;a<=this.retryCount;a++)try{const o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout),c=`${this.serverUrl}${t.path}`,h={method:t.method,headers:await this.buildHeaders(),signal:o.signal};t.body&&(h.body=JSON.stringify(t.body));const s=await fetch(c,h);if(clearTimeout(n),!s.ok){if(s.status===401&&!r&&this.licenseClient){if(r=!0,await this.licenseClient.forceRefresh()){a--;continue}throw new i(`API error: ${s.status}`,s.status)}throw s.status>=400&&s.status<500&&s.status!==429?new i(`API error: ${s.status}`,s.status):new i(`Server error: ${s.status}`,s.status)}return await s.json()}catch(o){if(e=o instanceof i?o:new i("Request failed"),o instanceof i&&o.statusCode&&o.statusCode>=400&&o.statusCode<500&&o.statusCode!==429)throw o;if(a<this.retryCount){const n=Math.min(p*Math.pow(2,a),C),c=Math.random()*n*.25;await this.sleep(n+c)}}throw e??new i("All retry attempts failed")}async fetchWithCacheFallback(t,e){try{const r=await this.fetchWithRetry(e);return this.cache.set(t,JSON.stringify(r)).catch(()=>{}),r}catch(r){const a=await this.cache.get(t);if(a!==null)try{return JSON.parse(a)}catch{}throw r}}sleep(t){return new Promise(e=>setTimeout(e,t))}}export{v as RemoteResolver,i as RemoteResolverError};
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 { ResolverMode, NoOpCache, } from '../types/index.js';
14
+ import { CLIENT_VERSION } from '../version.js';
15
+ // ── Constants ────────────────────────────────────────────────────────────
16
+ const DEFAULT_TIMEOUT_MS = 30_000;
17
+ const DEFAULT_RETRY_COUNT = 3;
18
+ const BACKOFF_BASE_MS = 1_000;
19
+ const BACKOFF_MAX_MS = 10_000;
20
+ // ── Error Types ──────────────────────────────────────────────────────────
21
+ export class RemoteResolverError extends Error {
22
+ statusCode;
23
+ endpoint;
24
+ constructor(message, statusCode, endpoint) {
25
+ super(message);
26
+ this.statusCode = statusCode;
27
+ this.endpoint = endpoint;
28
+ this.name = 'RemoteResolverError';
29
+ }
30
+ }
31
+ // ── RemoteResolver Implementation ───────────────────────────────────────
32
+ export class RemoteResolver {
33
+ mode = ResolverMode.REMOTE;
34
+ serverUrl;
35
+ licenseKey;
36
+ timeout;
37
+ retryCount;
38
+ /**
39
+ * Persistent cache -- used for registry metadata only, never protected
40
+ * step/skill/standard content.
41
+ */
42
+ cache;
43
+ licenseClient;
44
+ constructor(options) {
45
+ this.serverUrl = options.serverUrl.replace(/\/+$/, '');
46
+ this.licenseKey = options.licenseKey;
47
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS;
48
+ this.retryCount = options.retryCount ?? DEFAULT_RETRY_COUNT;
49
+ this.cache = options.cacheProvider ?? new NoOpCache();
50
+ this.licenseClient = options.licenseClient ?? null;
51
+ }
52
+ async resolveStep(stepId, _context) {
53
+ return this.fetchWithRetry({
54
+ method: 'GET',
55
+ path: `/api/v1/steps/${encodeURIComponent(stepId)}`,
56
+ });
57
+ }
58
+ async resolveSkill(skillId, _context) {
59
+ return this.fetchWithRetry({
60
+ method: 'GET',
61
+ path: `/api/v1/skills/${encodeURIComponent(skillId)}`,
62
+ });
63
+ }
64
+ async resolveStandard(standardId) {
65
+ return this.fetchWithRetry({
66
+ method: 'GET',
67
+ path: `/api/v1/standards/${encodeURIComponent(standardId)}`,
68
+ });
69
+ }
70
+ async resolveRegistry() {
71
+ // Registry is NOT asset content -- it's tokenized metadata (P70.02).
72
+ // Persistent cache is acceptable here.
73
+ const cacheKey = 'registry';
74
+ return this.fetchWithCacheFallback(cacheKey, {
75
+ method: 'GET',
76
+ path: '/api/v1/registry',
77
+ });
78
+ }
79
+ async assemblePrompt(stepId, context) {
80
+ // assemblePrompt is not cached because it depends on dynamic context
81
+ return this.fetchWithRetry({
82
+ method: 'POST',
83
+ path: '/api/v1/prompts/assemble',
84
+ body: {
85
+ stepId,
86
+ context,
87
+ },
88
+ });
89
+ }
90
+ async isAvailable() {
91
+ try {
92
+ const controller = new AbortController();
93
+ const timeoutId = setTimeout(() => controller.abort(), 5_000);
94
+ const response = await fetch(`${this.serverUrl}/api/v1/health`, {
95
+ method: 'GET',
96
+ headers: await this.buildHeaders(),
97
+ signal: controller.signal,
98
+ });
99
+ clearTimeout(timeoutId);
100
+ return response.ok;
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ async dispose() {
107
+ await this.cache.clear();
108
+ }
109
+ // ── Private Methods ─────────────────────────────────────────────────
110
+ /**
111
+ * Build authorization headers for API requests.
112
+ * When a LicenseClient is available, uses JWT token from it.
113
+ * Story 31.04: NEVER sends raw license key as Bearer token.
114
+ * If JWT is unavailable, omits Authorization header entirely.
115
+ * Server will return 401, which fetchWithRetry handles via forceRefresh.
116
+ */
117
+ async buildHeaders() {
118
+ const headers = {
119
+ 'Content-Type': 'application/json',
120
+ 'X-Client-Version': CLIENT_VERSION,
121
+ };
122
+ if (this.licenseClient) {
123
+ const jwt = await this.licenseClient.getToken();
124
+ if (jwt) {
125
+ headers['Authorization'] = `Bearer ${jwt}`;
126
+ }
127
+ // No JWT available: omit Authorization header entirely
128
+ // Server will return 401, which fetchWithRetry handles via forceRefresh
129
+ }
130
+ return headers;
131
+ }
132
+ /**
133
+ * Execute HTTP request with retry and exponential backoff.
134
+ * Handles 401 specially: if a licenseClient is available, attempts
135
+ * forceRefresh() and retries once with the new token.
136
+ */
137
+ async fetchWithRetry(options) {
138
+ let lastError;
139
+ let authRetried = false;
140
+ for (let attempt = 0; attempt <= this.retryCount; attempt++) {
141
+ try {
142
+ const controller = new AbortController();
143
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
144
+ const url = `${this.serverUrl}${options.path}`;
145
+ const fetchOptions = {
146
+ method: options.method,
147
+ headers: await this.buildHeaders(),
148
+ signal: controller.signal,
149
+ };
150
+ if (options.body) {
151
+ fetchOptions.body = JSON.stringify(options.body);
152
+ }
153
+ const response = await fetch(url, fetchOptions);
154
+ clearTimeout(timeoutId);
155
+ if (!response.ok) {
156
+ // 401: attempt token refresh once if licenseClient is available
157
+ if (response.status === 401 && !authRetried && this.licenseClient) {
158
+ authRetried = true;
159
+ const newToken = await this.licenseClient.forceRefresh();
160
+ if (newToken) {
161
+ // Retry immediately with the new token (don't count as a normal retry)
162
+ attempt--; // offset the loop increment so this doesn't consume a retry
163
+ continue;
164
+ }
165
+ // forceRefresh failed - throw immediately
166
+ throw new RemoteResolverError(`API error: ${response.status}`, response.status);
167
+ }
168
+ // Don't retry on 4xx client errors (except 429 rate limit)
169
+ if (response.status >= 400 && response.status < 500 && response.status !== 429) {
170
+ throw new RemoteResolverError(`API error: ${response.status}`, response.status);
171
+ }
172
+ // Retry on 5xx server errors and 429 rate limit
173
+ throw new RemoteResolverError(`Server error: ${response.status}`, response.status);
174
+ }
175
+ return (await response.json());
176
+ }
177
+ catch (error) {
178
+ // Transport and parser exceptions can contain a URL, response fragment
179
+ // or adapter-specific diagnostics. They are not safe CLI output.
180
+ lastError = error instanceof RemoteResolverError
181
+ ? error : new RemoteResolverError('Request failed');
182
+ // Don't retry on non-retryable errors (4xx except 429)
183
+ if (error instanceof RemoteResolverError && error.statusCode && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
184
+ throw error;
185
+ }
186
+ // Apply backoff before next retry (except on last attempt)
187
+ if (attempt < this.retryCount) {
188
+ const backoff = Math.min(BACKOFF_BASE_MS * Math.pow(2, attempt), BACKOFF_MAX_MS);
189
+ // Add jitter (0-25% of backoff)
190
+ const jitter = Math.random() * backoff * 0.25;
191
+ await this.sleep(backoff + jitter);
192
+ }
193
+ }
194
+ }
195
+ throw lastError ?? new RemoteResolverError('All retry attempts failed');
196
+ }
197
+ /**
198
+ * Fetch with persistent cache fallback: try HTTP first, fall back to cache
199
+ * on failure. On successful HTTP response, update the cache.
200
+ *
201
+ * P70.06: ONLY the registry uses this path. Asset content (step/skill/
202
+ * standard) is fetched live and never touches disk or a fallback cache.
203
+ */
204
+ async fetchWithCacheFallback(cacheKey, options) {
205
+ try {
206
+ const result = await this.fetchWithRetry(options);
207
+ // Update cache with fresh data (fire-and-forget)
208
+ this.cache.set(cacheKey, JSON.stringify(result)).catch(() => {
209
+ // Cache write failures are non-critical
210
+ });
211
+ return result;
212
+ }
213
+ catch (error) {
214
+ // Try cache fallback
215
+ const cached = await this.cache.get(cacheKey);
216
+ if (cached !== null) {
217
+ try {
218
+ return JSON.parse(cached);
219
+ }
220
+ catch {
221
+ // Invalid cache data, rethrow original error
222
+ }
223
+ }
224
+ throw error;
225
+ }
226
+ }
227
+ /**
228
+ * Sleep for the specified duration.
229
+ */
230
+ sleep(ms) {
231
+ return new Promise((resolve) => setTimeout(resolve, ms));
232
+ }
233
+ }