@ornexus/neocortex 4.60.73 → 4.60.75

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 (269) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -212
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.d.ts +27 -0
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  23. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  24. package/packages/client/dist/cache/index.js +1 -13
  25. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  26. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  27. package/packages/client/dist/checkpoint/index.js +1 -11
  28. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  29. package/packages/client/dist/cli.js +5 -358
  30. package/packages/client/dist/commands/activate.js +8 -394
  31. package/packages/client/dist/commands/architecture-answers.js +7 -274
  32. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  33. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  34. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  35. package/packages/client/dist/commands/cache-status.js +2 -112
  36. package/packages/client/dist/commands/config.js +1 -88
  37. package/packages/client/dist/commands/doctor.js +2 -635
  38. package/packages/client/dist/commands/invoke.d.ts +38 -1
  39. package/packages/client/dist/commands/invoke.js +143 -7200
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  41. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  42. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  44. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  45. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  46. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  47. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  49. package/packages/client/dist/commands/mutation-qa.js +1 -220
  50. package/packages/client/dist/commands/native-agent.js +2 -136
  51. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  52. package/packages/client/dist/commands/planning-generation.js +1 -53
  53. package/packages/client/dist/commands/planning-memory.js +1 -40
  54. package/packages/client/dist/commands/planning-research.js +1 -42
  55. package/packages/client/dist/commands/private-session.js +1 -75
  56. package/packages/client/dist/commands/property-qa.js +1 -139
  57. package/packages/client/dist/commands/qa-control.js +1 -16
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  60. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  61. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  62. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  68. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  69. package/packages/client/dist/commands/refactor-commit.js +13 -399
  70. package/packages/client/dist/commands/refactor-control.js +3 -142
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  72. package/packages/client/dist/commands/refactor-review.js +5 -283
  73. package/packages/client/dist/commands/refactor-root.js +7 -588
  74. package/packages/client/dist/commands/refresh-memory.js +3 -156
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  77. package/packages/client/dist/config/host-auth-broker.d.ts +31 -0
  78. package/packages/client/dist/config/host-auth-broker.js +1 -0
  79. package/packages/client/dist/config/host-auth-reference.d.ts +32 -0
  80. package/packages/client/dist/config/host-auth-reference.js +1 -0
  81. package/packages/client/dist/config/profile-directory.js +1 -13
  82. package/packages/client/dist/config/resolver-selection.js +1 -278
  83. package/packages/client/dist/config/secure-config.js +12 -281
  84. package/packages/client/dist/config.js +2 -223
  85. package/packages/client/dist/constants.js +1 -25
  86. package/packages/client/dist/context/context-collector.js +2 -222
  87. package/packages/client/dist/context/context-sanitizer.js +1 -145
  88. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  89. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  90. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  91. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  92. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  93. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  94. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  95. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  96. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  97. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  98. package/packages/client/dist/continuity/native-agent-types.d.ts +11 -0
  99. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  100. package/packages/client/dist/continuity/outbox.js +1 -117
  101. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  102. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  103. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  104. package/packages/client/dist/errors/error-messages.d.ts +3 -0
  105. package/packages/client/dist/errors/error-messages.js +2 -228
  106. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  107. package/packages/client/dist/evidence/collector.js +1 -347
  108. package/packages/client/dist/evidence/index.js +1 -1
  109. package/packages/client/dist/evidence/types.js +0 -2
  110. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  111. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  112. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  113. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  114. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +11 -1
  115. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  116. package/packages/client/dist/git/epic-operational-state.js +2 -672
  117. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  118. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  119. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  120. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  121. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  122. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  123. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  124. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  125. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  126. package/packages/client/dist/i18n/first-run.js +2 -60
  127. package/packages/client/dist/index.d.ts +2 -0
  128. package/packages/client/dist/index.js +1 -47
  129. package/packages/client/dist/invocation/invoke-input.js +1 -24
  130. package/packages/client/dist/license/host-auth-recovery.d.ts +158 -0
  131. package/packages/client/dist/license/host-auth-recovery.js +1 -0
  132. package/packages/client/dist/license/index.js +1 -5
  133. package/packages/client/dist/license/license-client.d.ts +10 -1
  134. package/packages/client/dist/license/license-client.js +1 -304
  135. package/packages/client/dist/machine/fingerprint.js +2 -163
  136. package/packages/client/dist/machine/index.js +1 -5
  137. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  138. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  139. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  140. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  141. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  142. package/packages/client/dist/migrations/project-identity.js +7 -493
  143. package/packages/client/dist/migrations/state-json.js +4 -393
  144. package/packages/client/dist/policy/architecture-policy.js +2 -184
  145. package/packages/client/dist/policy/index.js +1 -7
  146. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  147. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  148. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  149. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  150. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  151. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  152. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  153. package/packages/client/dist/private-execution/delivery.js +13 -410
  154. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  155. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  156. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  157. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  158. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  159. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  160. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  161. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  162. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  163. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  164. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  165. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  166. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  167. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  168. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  169. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  170. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  171. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  172. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  173. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  174. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  175. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  176. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  177. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  178. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  179. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  180. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  181. package/packages/client/dist/private-execution/session-lease.js +1 -63
  182. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  183. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  184. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  185. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  186. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  187. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  188. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  189. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  190. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  191. package/packages/client/dist/resilience/index.js +1 -8
  192. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  193. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  194. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  195. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  196. package/packages/client/dist/runner/binary.js +1 -404
  197. package/packages/client/dist/runner/cli.js +17 -1571
  198. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +61 -0
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -0
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.d.ts +65 -0
  202. package/packages/client/dist/runner/headless/background-root.js +1 -0
  203. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  204. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  205. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  206. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  207. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  208. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  209. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  210. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +27 -2
  211. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  212. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  213. package/packages/client/dist/runner/headless/managed-environment-cleanup.d.ts +95 -0
  214. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -0
  215. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  216. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  217. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  218. package/packages/client/dist/runner/headless/resolver.js +1 -231
  219. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  220. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  221. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  222. package/packages/client/dist/runner/headless/types.js +2 -574
  223. package/packages/client/dist/runner/local-console.js +13 -396
  224. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  225. package/packages/client/dist/runner/project-identity.js +1 -106
  226. package/packages/client/dist/runner/scheduler.js +7 -995
  227. package/packages/client/dist/runner-cli.js +2 -18
  228. package/packages/client/dist/state/invocation-shape.js +1 -13
  229. package/packages/client/dist/state/project-state-snapshot.d.ts +7 -0
  230. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  231. package/packages/client/dist/state/state-json-repair.js +3 -785
  232. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  233. package/packages/client/dist/telemetry/index.js +1 -5
  234. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  235. package/packages/client/dist/tier/index.js +1 -5
  236. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  237. package/packages/client/dist/types/index.js +1 -38
  238. package/packages/client/dist/version.js +1 -27
  239. package/packages/client/dist/yolo/change-evidence-collector.d.ts +21 -1
  240. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  241. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  242. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  243. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  244. package/packages/client/dist/yoloop/index.js +1 -8
  245. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  246. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  247. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  248. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  249. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  250. package/packages/shared/dist/invocation/explicit-intent-recovery.d.ts +83 -0
  251. package/packages/shared/dist/invocation/explicit-intent-recovery.js +187 -0
  252. package/packages/shared/dist/invocation/index.d.ts +7 -0
  253. package/packages/shared/dist/invocation/index.js +22 -0
  254. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  255. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  256. package/targets-stubs/antigravity/gemini.md +1 -1
  257. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  258. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  259. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  260. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  261. package/targets-stubs/claude-code/neocortex.md +2 -2
  262. package/targets-stubs/codex/AGENTS.md +24 -21
  263. package/targets-stubs/codex/README.md +6 -1
  264. package/targets-stubs/codex/neocortex.toml +7 -2
  265. package/targets-stubs/cursor/agent.md +2 -2
  266. package/targets-stubs/gemini-cli/agent.md +2 -2
  267. package/targets-stubs/opencode/neocortex-root.md +16 -1
  268. package/targets-stubs/opencode/neocortex.md +6 -0
  269. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,233 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * This file is part of Neocortex CLI, licensed under the
6
- * Functional Source License, Version 1.1 (FSL-1.1).
7
- *
8
- * Change Date: February 20, 2029
9
- * Change License: MIT
10
- *
11
- * See the LICENSE file in the project root for full license text.
12
- */
13
- 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
- }
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,404 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P181.02 -- shared trusted neocortex-runner binary resolution.
6
- */
7
- import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
8
- import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';
9
- export const RUNNER_BINARY_REASON_CODES = Object.freeze({
10
- OK: 'continuity-ok',
11
- MISSING: 'runner-binary-missing',
12
- AMBIGUOUS: 'runner-binary-ambiguous',
13
- NON_EXECUTABLE: 'runner-binary-non-executable',
14
- VERSION_MISMATCHED: 'runner-binary-version-mismatched',
15
- UNTRUSTED: 'runner-binary-untrusted',
16
- });
17
- export const HEADLESS_RUNTIME_BINARY_REASON_CODES = Object.freeze({
18
- OK: 'continuity-ok',
19
- UNAVAILABLE: 'headless-adapter-unavailable',
20
- UNTRUSTED: 'headless-runtime-untrusted',
21
- });
22
- const ACCEPTED_PACKAGE_NAMES = new Set(['@ornexus/neocortex', '@neocortex/client']);
23
- const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
24
- export function resolveTrustedRunnerBinary(options = {}) {
25
- const startDir = resolveStartDirectory(options);
26
- if (!startDir)
27
- return failure(RUNNER_BINARY_REASON_CODES.MISSING, 'Runner binary resolution did not receive a usable start path.');
28
- const packageInfo = findNearestAcceptedPackage(startDir);
29
- if (!packageInfo)
30
- return failure(RUNNER_BINARY_REASON_CODES.AMBIGUOUS, 'Runner binary was not inside an accepted Neocortex package.');
31
- const { packageRoot, pkg } = packageInfo;
32
- const packageName = typeof pkg.name === 'string' ? pkg.name : undefined;
33
- const packageVersion = typeof pkg.version === 'string' ? pkg.version : undefined;
34
- const provenance = inferProvenance(packageRoot, packageName);
35
- if (!packageName || !ACCEPTED_PACKAGE_NAMES.has(packageName)) {
36
- return failure(RUNNER_BINARY_REASON_CODES.AMBIGUOUS, 'Runner package identity was not accepted.', { packageName, packageVersion, packageRoot, provenance });
37
- }
38
- if (!packageVersion || !VERSION_PATTERN.test(packageVersion)) {
39
- return failure(RUNNER_BINARY_REASON_CODES.VERSION_MISMATCHED, 'Runner package version was missing or invalid.', { packageName, packageVersion, packageRoot, provenance });
40
- }
41
- const expectedRelativePath = expectedRunnerBinRelativePath(pkg, packageName);
42
- if (!expectedRelativePath) {
43
- return failure(RUNNER_BINARY_REASON_CODES.MISSING, 'Runner package did not declare an accepted runner bin target.', { packageName, packageVersion, packageRoot, provenance });
44
- }
45
- const expectedPath = resolvePackageRelative(packageRoot, expectedRelativePath);
46
- const executablePath = safeRealpath(expectedPath);
47
- if (!executablePath || !existsSync(executablePath)) {
48
- return failure(RUNNER_BINARY_REASON_CODES.MISSING, 'Runner package bin target was not present.', { packageName, packageVersion, packageRoot, expectedRelativePath, provenance });
49
- }
50
- const executableCheck = checkExecutableFile(executablePath, options.platform, options.requireExecutable);
51
- if (executableCheck) {
52
- return failure(executableCheck, reasonSummary(executableCheck), { packageName, packageVersion, packageRoot, executablePath, expectedRelativePath, provenance });
53
- }
54
- const versionMismatch = packageVersionMismatch(packageRoot, packageName, packageVersion);
55
- if (versionMismatch) {
56
- return failure(RUNNER_BINARY_REASON_CODES.VERSION_MISMATCHED, 'Runner package version did not match the development workspace root.', { packageName, packageVersion, packageRoot, executablePath, expectedRelativePath, provenance });
57
- }
58
- return {
59
- ok: true,
60
- trusted: true,
61
- command: executablePath,
62
- args: [],
63
- executablePath,
64
- packageName,
65
- packageVersion,
66
- packageRoot,
67
- expectedRelativePath,
68
- provenance,
69
- reasonCodes: [RUNNER_BINARY_REASON_CODES.OK],
70
- publicSummary: `Resolved trusted ${provenance} runner for ${packageName}.`,
71
- publicSafe: true,
72
- };
73
- }
74
- export function checkRunnerBinaryTrust(executablePath, options = {}) {
75
- const absoluteExecutable = safeAbsolutePath(executablePath);
76
- if (!absoluteExecutable)
77
- return untrusted(RUNNER_BINARY_REASON_CODES.MISSING, 'Runner executable path was missing.');
78
- const resolvedExecutable = safeRealpath(absoluteExecutable);
79
- if (!resolvedExecutable || !existsSync(resolvedExecutable)) {
80
- return untrusted(RUNNER_BINARY_REASON_CODES.MISSING, 'Runner executable was not present.', { executablePath: absoluteExecutable });
81
- }
82
- const packageInfo = findNearestAcceptedPackage(dirname(resolvedExecutable));
83
- if (!packageInfo) {
84
- return untrusted(RUNNER_BINARY_REASON_CODES.AMBIGUOUS, 'Runner executable was not inside an accepted Neocortex package.', { executablePath: resolvedExecutable });
85
- }
86
- const { packageRoot, pkg } = packageInfo;
87
- const packageName = typeof pkg.name === 'string' ? pkg.name : undefined;
88
- const packageVersion = typeof pkg.version === 'string' ? pkg.version : undefined;
89
- const provenance = inferProvenance(packageRoot, packageName);
90
- if (!packageName || !ACCEPTED_PACKAGE_NAMES.has(packageName)) {
91
- return untrusted(RUNNER_BINARY_REASON_CODES.AMBIGUOUS, 'Runner package identity was not accepted.', { executablePath: resolvedExecutable, packageName, packageVersion, packageRoot, provenance });
92
- }
93
- if (!packageVersion || !VERSION_PATTERN.test(packageVersion)) {
94
- return untrusted(RUNNER_BINARY_REASON_CODES.VERSION_MISMATCHED, 'Runner package version was missing or invalid.', { executablePath: resolvedExecutable, packageName, packageVersion, packageRoot, provenance });
95
- }
96
- const expectedRelativePath = expectedRunnerBinRelativePath(pkg, packageName);
97
- if (!expectedRelativePath) {
98
- return untrusted(RUNNER_BINARY_REASON_CODES.MISSING, 'Runner package did not declare an accepted runner bin target.', { executablePath: resolvedExecutable, packageName, packageVersion, packageRoot, provenance });
99
- }
100
- const expectedPath = safeRealpath(resolvePackageRelative(packageRoot, expectedRelativePath));
101
- if (!expectedPath || !existsSync(expectedPath)) {
102
- return untrusted(RUNNER_BINARY_REASON_CODES.MISSING, 'Runner package bin target was not present.', { executablePath: resolvedExecutable, packageName, packageVersion, packageRoot, expectedRelativePath, provenance });
103
- }
104
- if (expectedPath !== resolvedExecutable) {
105
- return untrusted(RUNNER_BINARY_REASON_CODES.AMBIGUOUS, 'Runner executable did not match the package-declared bin target.', { executablePath: resolvedExecutable, packageName, packageVersion, packageRoot, expectedRelativePath, provenance });
106
- }
107
- const executableCheck = checkExecutableFile(resolvedExecutable, options.platform, options.requireExecutable);
108
- if (executableCheck) {
109
- return untrusted(executableCheck, reasonSummary(executableCheck), { executablePath: resolvedExecutable, packageName, packageVersion, packageRoot, expectedRelativePath, provenance });
110
- }
111
- if (packageVersionMismatch(packageRoot, packageName, packageVersion)) {
112
- return untrusted(RUNNER_BINARY_REASON_CODES.VERSION_MISMATCHED, 'Runner package version did not match the development workspace root.', { executablePath: resolvedExecutable, packageName, packageVersion, packageRoot, expectedRelativePath, provenance });
113
- }
114
- return {
115
- trusted: true,
116
- packageName,
117
- packageVersion,
118
- packageRoot,
119
- executablePath: resolvedExecutable,
120
- expectedRelativePath,
121
- provenance,
122
- reasonCodes: [RUNNER_BINARY_REASON_CODES.OK],
123
- publicSummary: `Trusted ${provenance} runner for ${packageName}.`,
124
- publicSafe: true,
125
- };
126
- }
127
- export function runnerTrustRelativePath(packageRoot, executablePath) {
128
- if (looksWindowsPath(packageRoot) || looksWindowsPath(executablePath)) {
129
- return win32.relative(packageRoot, executablePath).split('\\').join('/');
130
- }
131
- return relative(packageRoot, executablePath).split('\\').join('/');
132
- }
133
- export function checkTrustedHeadlessRuntimeBinary(options) {
134
- const commandName = options.commandName;
135
- const realpathBasenamePolicy = options.realpathBasenamePolicy ?? 'strict';
136
- if (!isSafeCommandName(commandName)) {
137
- return headlessRuntimeBinaryFailure(HEADLESS_RUNTIME_BINARY_REASON_CODES.UNTRUSTED, 'Headless runtime command name was not allowlisted by adapter code.', commandName, 'commandName', 'unsafe_key');
138
- }
139
- const locator = options.commandLocator ?? defaultHeadlessRuntimeCommandLocator;
140
- const candidate = locator(commandName, options.env);
141
- if (!candidate) {
142
- return headlessRuntimeBinaryFailure(HEADLESS_RUNTIME_BINARY_REASON_CODES.UNAVAILABLE, 'Headless runtime command was not found on PATH.', commandName, 'runtimeBinary', 'missing');
143
- }
144
- if (!isSafeRuntimeExecutableCandidate(candidate, commandName, options.platform)) {
145
- return headlessRuntimeBinaryFailure(HEADLESS_RUNTIME_BINARY_REASON_CODES.UNTRUSTED, 'Headless runtime executable path did not match adapter-owned command constraints.', commandName, 'runtimeBinary', 'executable_path');
146
- }
147
- const resolvedExecutable = safeRealpath(candidate);
148
- if (!resolvedExecutable || !existsSync(resolvedExecutable)) {
149
- return headlessRuntimeBinaryFailure(HEADLESS_RUNTIME_BINARY_REASON_CODES.UNAVAILABLE, 'Headless runtime executable was not present.', commandName, 'runtimeBinary', 'missing');
150
- }
151
- if (!isTrustedRuntimeRealpathBasename(resolvedExecutable, commandName, options.platform, realpathBasenamePolicy)) {
152
- return headlessRuntimeBinaryFailure(HEADLESS_RUNTIME_BINARY_REASON_CODES.UNTRUSTED, 'Headless runtime executable realpath did not match adapter-owned command constraints.', commandName, 'runtimeBinary', 'executable_path');
153
- }
154
- const executableCheck = checkExecutableFile(resolvedExecutable, options.platform, options.requireExecutable ?? true);
155
- if (executableCheck) {
156
- return headlessRuntimeBinaryFailure(executableCheck === RUNNER_BINARY_REASON_CODES.NON_EXECUTABLE || executableCheck === RUNNER_BINARY_REASON_CODES.MISSING
157
- ? HEADLESS_RUNTIME_BINARY_REASON_CODES.UNAVAILABLE
158
- : HEADLESS_RUNTIME_BINARY_REASON_CODES.UNTRUSTED, reasonSummary(executableCheck), commandName, 'runtimeBinary', executableCheck);
159
- }
160
- const result = {
161
- ok: true,
162
- trusted: true,
163
- commandName,
164
- reasonCodes: [HEADLESS_RUNTIME_BINARY_REASON_CODES.OK],
165
- publicSummary: `Trusted headless runtime command ${commandName} is available.`,
166
- redactionSummary: [],
167
- publicSafe: true,
168
- };
169
- Object.defineProperty(result, 'executablePath', {
170
- value: resolvedExecutable,
171
- enumerable: false,
172
- configurable: false,
173
- });
174
- return result;
175
- }
176
- export function defaultHeadlessRuntimeCommandLocator(commandName, env = process.env) {
177
- if (!isSafeCommandName(commandName))
178
- return undefined;
179
- const pathValue = env.PATH ?? '';
180
- const pathExt = process.platform === 'win32'
181
- ? (env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)
182
- : [''];
183
- for (const entry of pathValue.split(delimiter)) {
184
- if (!entry || /[\r\n\0]/.test(entry))
185
- continue;
186
- for (const ext of pathExt) {
187
- const candidate = resolve(entry, `${commandName}${ext}`);
188
- if (existsSync(candidate))
189
- return candidate;
190
- }
191
- }
192
- return undefined;
193
- }
194
- function resolveStartDirectory(options) {
195
- if (options.packageRoot)
196
- return safeAbsolutePath(options.packageRoot);
197
- const from = safeAbsolutePath(options.from ?? process.argv[1]);
198
- if (!from)
199
- return null;
200
- const real = safeRealpath(from);
201
- if (real) {
202
- try {
203
- const stat = statSync(real);
204
- return stat.isDirectory() ? real : dirname(real);
205
- }
206
- catch {
207
- return dirname(real);
208
- }
209
- }
210
- return dirname(from);
211
- }
212
- function safeAbsolutePath(value) {
213
- if (!value || /[\r\n\0]/.test(value))
214
- return null;
215
- const resolved = isAbsolute(value) ? value : resolve(value);
216
- return isAbsolute(resolved) ? resolved : null;
217
- }
218
- function safeRealpath(path) {
219
- try {
220
- return realpathSync(path);
221
- }
222
- catch {
223
- return null;
224
- }
225
- }
226
- function findNearestAcceptedPackage(startDir) {
227
- let current = startDir;
228
- for (let depth = 0; depth < 10; depth++) {
229
- const pkg = readPackageJson(join(current, 'package.json'));
230
- if (pkg && typeof pkg.name === 'string' && ACCEPTED_PACKAGE_NAMES.has(pkg.name)) {
231
- return { packageRoot: current, pkg };
232
- }
233
- const parent = dirname(current);
234
- if (parent === current)
235
- break;
236
- current = parent;
237
- }
238
- return null;
239
- }
240
- function findRootPackage(startDir) {
241
- let current = startDir;
242
- for (let depth = 0; depth < 10; depth++) {
243
- const pkg = readPackageJson(join(current, 'package.json'));
244
- if (pkg?.name === '@ornexus/neocortex')
245
- return { packageRoot: current, pkg };
246
- const parent = dirname(current);
247
- if (parent === current)
248
- break;
249
- current = parent;
250
- }
251
- return null;
252
- }
253
- function readPackageJson(path) {
254
- try {
255
- return JSON.parse(readFileSync(path, 'utf8'));
256
- }
257
- catch {
258
- return null;
259
- }
260
- }
261
- function expectedRunnerBinRelativePath(pkg, packageName) {
262
- const bin = isRecord(pkg.bin) ? pkg.bin['neocortex-runner'] : undefined;
263
- if (typeof bin !== 'string' || bin.length === 0)
264
- return null;
265
- const normalized = normalizePackageRelativePath(bin);
266
- if (packageName === '@ornexus/neocortex' && normalized !== 'packages/client/dist/runner-cli.js')
267
- return null;
268
- if (packageName === '@neocortex/client' && normalized !== 'dist/runner-cli.js')
269
- return null;
270
- return normalized;
271
- }
272
- function normalizePackageRelativePath(value) {
273
- return value.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '');
274
- }
275
- function resolvePackageRelative(packageRoot, normalizedRelativePath) {
276
- return resolve(packageRoot, ...normalizedRelativePath.split('/').filter(Boolean));
277
- }
278
- function inferProvenance(packageRoot, packageName) {
279
- if (packageName === '@ornexus/neocortex')
280
- return 'published-root-package';
281
- if (packageName !== '@neocortex/client')
282
- return 'published-client-package';
283
- const rootInfo = findRootPackage(dirname(packageRoot));
284
- return rootInfo ? 'development-workspace' : 'published-client-package';
285
- }
286
- function packageVersionMismatch(packageRoot, packageName, packageVersion) {
287
- if (packageName !== '@neocortex/client')
288
- return false;
289
- const rootInfo = findRootPackage(dirname(packageRoot));
290
- return Boolean(rootInfo && rootInfo.pkg.version !== packageVersion);
291
- }
292
- function checkExecutableFile(executablePath, platform = process.platform, requireExecutable = true) {
293
- try {
294
- const stat = statSync(executablePath);
295
- if (!stat.isFile())
296
- return RUNNER_BINARY_REASON_CODES.AMBIGUOUS;
297
- if (requireExecutable && platform !== 'win32' && (stat.mode & 0o111) === 0)
298
- return RUNNER_BINARY_REASON_CODES.NON_EXECUTABLE;
299
- return null;
300
- }
301
- catch {
302
- return RUNNER_BINARY_REASON_CODES.MISSING;
303
- }
304
- }
305
- function failure(reasonCode, publicSummary, details = {}) {
306
- const safeDetails = publicFailureDetails(details);
307
- return {
308
- ok: false,
309
- trusted: false,
310
- reasonCode,
311
- reasonCodes: [reasonCode],
312
- publicSummary: boundPublicSummary(publicSummary),
313
- publicSafe: true,
314
- ...safeDetails,
315
- };
316
- }
317
- function untrusted(reasonCode, publicSummary, details = {}) {
318
- const safeDetails = publicFailureDetails(details);
319
- return {
320
- trusted: false,
321
- reasonCode,
322
- reasonCodes: [reasonCode],
323
- publicSummary: boundPublicSummary(publicSummary),
324
- publicSafe: true,
325
- ...safeDetails,
326
- };
327
- }
328
- function publicFailureDetails(details) {
329
- return {
330
- ...(details.packageName ? { packageName: details.packageName } : {}),
331
- ...(details.packageVersion ? { packageVersion: details.packageVersion } : {}),
332
- ...(details.expectedRelativePath ? { expectedRelativePath: details.expectedRelativePath } : {}),
333
- ...(details.provenance ? { provenance: details.provenance } : {}),
334
- };
335
- }
336
- function reasonSummary(reasonCode) {
337
- switch (reasonCode) {
338
- case RUNNER_BINARY_REASON_CODES.MISSING:
339
- return 'Runner package bin target was not present.';
340
- case RUNNER_BINARY_REASON_CODES.AMBIGUOUS:
341
- return 'Runner binary candidate was ambiguous.';
342
- case RUNNER_BINARY_REASON_CODES.NON_EXECUTABLE:
343
- return 'Runner package bin target was not executable.';
344
- case RUNNER_BINARY_REASON_CODES.VERSION_MISMATCHED:
345
- return 'Runner package version did not match the development workspace root.';
346
- default:
347
- return 'Runner binary trust check failed.';
348
- }
349
- }
350
- function boundPublicSummary(value) {
351
- return value.length <= 180 ? value : `${value.slice(0, 180)}…[TRUNCATED:${value.length - 180}]`;
352
- }
353
- function looksWindowsPath(value) {
354
- return /^[A-Za-z]:[\\/]/.test(value) || value.includes('\\') || sep === '\\';
355
- }
356
- function isRecord(value) {
357
- return Boolean(value && typeof value === 'object' && !Array.isArray(value));
358
- }
359
- function isSafeCommandName(value) {
360
- return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value) && !/[\\/\s;&|`$<>\r\n\0]/.test(value);
361
- }
362
- function isSafeRuntimeExecutableCandidate(value, commandName, platform = process.platform) {
363
- if (!value || /[\r\n\0]/.test(value) || !isAbsolute(value))
364
- return false;
365
- const base = basename(value).toLowerCase();
366
- const expected = commandName.toLowerCase();
367
- if (platform === 'win32') {
368
- return base === expected || ['.exe', '.cmd', '.bat', '.com'].some((ext) => base === `${expected}${ext}`);
369
- }
370
- return base === expected;
371
- }
372
- function isTrustedRuntimeRealpathBasename(value, commandName, platform = process.platform, policy = 'strict') {
373
- if (isSafeRuntimeExecutableCandidate(value, commandName, platform))
374
- return true;
375
- if (policy === 'opencode-npm-native' && commandName === 'opencode') {
376
- if (!value || /[\r\n\0]/.test(value) || !isAbsolute(value))
377
- return false;
378
- return basename(value).toLowerCase() === 'opencode.exe';
379
- }
380
- if (policy !== 'claude-code-versioned' || commandName !== 'claude')
381
- return false;
382
- if (!value || /[\r\n\0]/.test(value) || !isAbsolute(value))
383
- return false;
384
- return isClaudeCodeVersionedRealpathBasename(basename(value), platform);
385
- }
386
- function isClaudeCodeVersionedRealpathBasename(value, platform = process.platform) {
387
- const lower = value.toLowerCase();
388
- const normalized = platform === 'win32'
389
- ? lower.replace(/\.(?:exe|cmd|bat|com)$/i, '')
390
- : lower;
391
- return /^(?:(?:claude|claude-code)[._-])?v?\d+\.\d+\.\d+(?:[-+][0-9a-z][0-9a-z.-]*)?(?:\.(?:js|mjs|cjs))?$/.test(normalized);
392
- }
393
- function headlessRuntimeBinaryFailure(reasonCode, publicSummary, commandName, field, reason) {
394
- return {
395
- ok: false,
396
- trusted: false,
397
- ...(commandName && isSafeCommandName(commandName) ? { commandName } : {}),
398
- reasonCode,
399
- reasonCodes: [reasonCode],
400
- publicSummary: boundPublicSummary(publicSummary),
401
- redactionSummary: [{ field, reason, evidence: 'value-denied', publicSafe: true }],
402
- publicSafe: true,
403
- };
404
- }
1
+ import{existsSync as g,readFileSync as j,realpathSync as z,statSync as P}from"node:fs";import{basename as E,delimiter as K,dirname as p,isAbsolute as R,join as B,relative as X,resolve as y,sep as F,win32 as Z}from"node:path";const o=Object.freeze({OK:"continuity-ok",MISSING:"runner-binary-missing",AMBIGUOUS:"runner-binary-ambiguous",NON_EXECUTABLE:"runner-binary-non-executable",VERSION_MISMATCHED:"runner-binary-version-mismatched",UNTRUSTED:"runner-binary-untrusted"}),m=Object.freeze({OK:"continuity-ok",UNAVAILABLE:"headless-adapter-unavailable",UNTRUSTED:"headless-runtime-untrusted"}),I=new Set(["@ornexus/neocortex","@neocortex/client"]),w=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function re(e={}){const t=J(e);if(!t)return b(o.MISSING,"Runner binary resolution did not receive a usable start path.");const r=v(t);if(!r)return b(o.AMBIGUOUS,"Runner binary was not inside an accepted Neocortex package.");const{packageRoot:n,pkg:c}=r,a=typeof c.name=="string"?c.name:void 0,u=typeof c.version=="string"?c.version:void 0,i=G(n,a);if(!a||!I.has(a))return b(o.AMBIGUOUS,"Runner package identity was not accepted.",{packageName:a,packageVersion:u,packageRoot:n,provenance:i});if(!u||!w.test(u))return b(o.VERSION_MISMATCHED,"Runner package version was missing or invalid.",{packageName:a,packageVersion:u,packageRoot:n,provenance:i});const s=_(c,a);if(!s)return b(o.MISSING,"Runner package did not declare an accepted runner bin target.",{packageName:a,packageVersion:u,packageRoot:n,provenance:i});const d=D(n,s),l=x(d);if(!l||!g(l))return b(o.MISSING,"Runner package bin target was not present.",{packageName:a,packageVersion:u,packageRoot:n,expectedRelativePath:s,provenance:i});const S=N(l,e.platform,e.requireExecutable);return S?b(S,T(S),{packageName:a,packageVersion:u,packageRoot:n,executablePath:l,expectedRelativePath:s,provenance:i}):L(n,a,u)?b(o.VERSION_MISMATCHED,"Runner package version did not match the development workspace root.",{packageName:a,packageVersion:u,packageRoot:n,executablePath:l,expectedRelativePath:s,provenance:i}):{ok:!0,trusted:!0,command:l,args:[],executablePath:l,packageName:a,packageVersion:u,packageRoot:n,expectedRelativePath:s,provenance:i,reasonCodes:[o.OK],publicSummary:`Resolved trusted ${i} runner for ${a}.`,publicSafe:!0}}function ae(e,t={}){const r=A(e);if(!r)return f(o.MISSING,"Runner executable path was missing.");const n=x(r);if(!n||!g(n))return f(o.MISSING,"Runner executable was not present.",{executablePath:r});const c=v(p(n));if(!c)return f(o.AMBIGUOUS,"Runner executable was not inside an accepted Neocortex package.",{executablePath:n});const{packageRoot:a,pkg:u}=c,i=typeof u.name=="string"?u.name:void 0,s=typeof u.version=="string"?u.version:void 0,d=G(a,i);if(!i||!I.has(i))return f(o.AMBIGUOUS,"Runner package identity was not accepted.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,provenance:d});if(!s||!w.test(s))return f(o.VERSION_MISMATCHED,"Runner package version was missing or invalid.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,provenance:d});const l=_(u,i);if(!l)return f(o.MISSING,"Runner package did not declare an accepted runner bin target.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,provenance:d});const S=x(D(a,l));if(!S||!g(S))return f(o.MISSING,"Runner package bin target was not present.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d});if(S!==n)return f(o.AMBIGUOUS,"Runner executable did not match the package-declared bin target.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d});const k=N(n,t.platform,t.requireExecutable);return k?f(k,T(k),{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d}):L(a,i,s)?f(o.VERSION_MISMATCHED,"Runner package version did not match the development workspace root.",{executablePath:n,packageName:i,packageVersion:s,packageRoot:a,expectedRelativePath:l,provenance:d}):{trusted:!0,packageName:i,packageVersion:s,packageRoot:a,executablePath:n,expectedRelativePath:l,provenance:d,reasonCodes:[o.OK],publicSummary:`Trusted ${d} runner for ${i}.`,publicSafe:!0}}function ce(e,t){return H(e)||H(t)?Z.relative(e,t).split("\\").join("/"):X(e,t).split("\\").join("/")}function oe(e){const t=e.commandName,r=e.realpathBasenamePolicy??"strict";if(!M(t))return h(m.UNTRUSTED,"Headless runtime command name was not allowlisted by adapter code.",t,"commandName","unsafe_key");const c=(e.commandLocator??q)(t,e.env);if(!c)return h(m.UNAVAILABLE,"Headless runtime command was not found on PATH.",t,"runtimeBinary","missing");if(!$(c,t,e.platform))return h(m.UNTRUSTED,"Headless runtime executable path did not match adapter-owned command constraints.",t,"runtimeBinary","executable_path");const a=x(c);if(!a||!g(a))return h(m.UNAVAILABLE,"Headless runtime executable was not present.",t,"runtimeBinary","missing");if(!Q(a,t,e.platform,r))return h(m.UNTRUSTED,"Headless runtime executable realpath did not match adapter-owned command constraints.",t,"runtimeBinary","executable_path");const u=N(a,e.platform,e.requireExecutable??!0);if(u)return h(u===o.NON_EXECUTABLE||u===o.MISSING?m.UNAVAILABLE:m.UNTRUSTED,T(u),t,"runtimeBinary",u);const i={ok:!0,trusted:!0,commandName:t,reasonCodes:[m.OK],publicSummary:`Trusted headless runtime command ${t} is available.`,redactionSummary:[],publicSafe:!0};return Object.defineProperty(i,"executablePath",{value:a,enumerable:!1,configurable:!1}),i}function q(e,t=process.env){if(!M(e))return;const r=t.PATH??"",n=process.platform==="win32"?(t.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean):[""];for(const c of r.split(K))if(!(!c||/[\r\n\0]/.test(c)))for(const a of n){const u=y(c,`${e}${a}`);if(g(u))return u}}function J(e){if(e.packageRoot)return A(e.packageRoot);const t=A(e.from??process.argv[1]);if(!t)return null;const r=x(t);if(r)try{return P(r).isDirectory()?r:p(r)}catch{return p(r)}return p(t)}function A(e){if(!e||/[\r\n\0]/.test(e))return null;const t=R(e)?e:y(e);return R(t)?t:null}function x(e){try{return z(e)}catch{return null}}function v(e){let t=e;for(let r=0;r<10;r++){const n=O(B(t,"package.json"));if(n&&typeof n.name=="string"&&I.has(n.name))return{packageRoot:t,pkg:n};const c=p(t);if(c===t)break;t=c}return null}function C(e){let t=e;for(let r=0;r<10;r++){const n=O(B(t,"package.json"));if(n?.name==="@ornexus/neocortex")return{packageRoot:t,pkg:n};const c=p(t);if(c===t)break;t=c}return null}function O(e){try{return JSON.parse(j(e,"utf8"))}catch{return null}}function _(e,t){const r=W(e.bin)?e.bin["neocortex-runner"]:void 0;if(typeof r!="string"||r.length===0)return null;const n=Y(r);return t==="@ornexus/neocortex"&&n!=="packages/client/dist/runner-cli.js"||t==="@neocortex/client"&&n!=="dist/runner-cli.js"?null:n}function Y(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function D(e,t){return y(e,...t.split("/").filter(Boolean))}function G(e,t){return t==="@ornexus/neocortex"?"published-root-package":t!=="@neocortex/client"?"published-client-package":C(p(e))?"development-workspace":"published-client-package"}function L(e,t,r){if(t!=="@neocortex/client")return!1;const n=C(p(e));return!!(n&&n.pkg.version!==r)}function N(e,t=process.platform,r=!0){try{const n=P(e);return n.isFile()?r&&t!=="win32"&&(n.mode&73)===0?o.NON_EXECUTABLE:null:o.AMBIGUOUS}catch{return o.MISSING}}function b(e,t,r={}){const n=V(r);return{ok:!1,trusted:!1,reasonCode:e,reasonCodes:[e],publicSummary:U(t),publicSafe:!0,...n}}function f(e,t,r={}){const n=V(r);return{trusted:!1,reasonCode:e,reasonCodes:[e],publicSummary:U(t),publicSafe:!0,...n}}function V(e){return{...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{},...e.expectedRelativePath?{expectedRelativePath:e.expectedRelativePath}:{},...e.provenance?{provenance:e.provenance}:{}}}function T(e){switch(e){case o.MISSING:return"Runner package bin target was not present.";case o.AMBIGUOUS:return"Runner binary candidate was ambiguous.";case o.NON_EXECUTABLE:return"Runner package bin target was not executable.";case o.VERSION_MISMATCHED:return"Runner package version did not match the development workspace root.";default:return"Runner binary trust check failed."}}function U(e){return e.length<=180?e:`${e.slice(0,180)}\u2026[TRUNCATED:${e.length-180}]`}function H(e){return/^[A-Za-z]:[\\/]/.test(e)||e.includes("\\")||F==="\\"}function W(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function M(e){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(e)&&!/[\\/\s;&|`$<>\r\n\0]/.test(e)}function $(e,t,r=process.platform){if(!e||/[\r\n\0]/.test(e)||!R(e))return!1;const n=E(e).toLowerCase(),c=t.toLowerCase();return r==="win32"?n===c||[".exe",".cmd",".bat",".com"].some(a=>n===`${c}${a}`):n===c}function Q(e,t,r=process.platform,n="strict"){return $(e,t,r)?!0:n==="opencode-npm-native"&&t==="opencode"?!e||/[\r\n\0]/.test(e)||!R(e)?!1:E(e).toLowerCase()==="opencode.exe":n!=="claude-code-versioned"||t!=="claude"||!e||/[\r\n\0]/.test(e)||!R(e)?!1:ee(E(e),r)}function ee(e,t=process.platform){const r=e.toLowerCase(),n=t==="win32"?r.replace(/\.(?:exe|cmd|bat|com)$/i,""):r;return/^(?:(?:claude|claude-code)[._-])?v?\d+\.\d+\.\d+(?:[-+][0-9a-z][0-9a-z.-]*)?(?:\.(?:js|mjs|cjs))?$/.test(n)}function h(e,t,r,n,c){return{ok:!1,trusted:!1,...r&&M(r)?{commandName:r}:{},reasonCode:e,reasonCodes:[e],publicSummary:U(t),redactionSummary:[{field:n,reason:c,evidence:"value-denied",publicSafe:!0}],publicSafe:!0}}export{m as HEADLESS_RUNTIME_BINARY_REASON_CODES,o as RUNNER_BINARY_REASON_CODES,ae as checkRunnerBinaryTrust,oe as checkTrustedHeadlessRuntimeBinary,q as defaultHeadlessRuntimeCommandLocator,re as resolveTrustedRunnerBinary,ce as runnerTrustRelativePath};