@ornexus/neocortex 4.61.5 → 4.62.0

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 (279) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +1 -1
  5. package/package.json +5 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.d.ts +8 -1
  20. package/packages/client/dist/agent/update-description.js +2 -260
  21. package/packages/client/dist/cache/crypto-utils.js +1 -78
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  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 -364
  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 +17 -0
  39. package/packages/client/dist/commands/invoke.js +148 -7822
  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 -174
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  77. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  78. package/packages/client/dist/commands/story-worktree.js +5 -258
  79. package/packages/client/dist/config/host-auth-broker.js +1 -60
  80. package/packages/client/dist/config/host-auth-reference.js +1 -93
  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 -224
  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.js +1 -105
  99. package/packages/client/dist/continuity/outbox.js +1 -117
  100. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  101. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  102. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  103. package/packages/client/dist/errors/error-messages.js +2 -258
  104. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  105. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  106. package/packages/client/dist/evidence/collector.js +1 -347
  107. package/packages/client/dist/evidence/index.js +1 -1
  108. package/packages/client/dist/evidence/types.js +0 -2
  109. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  110. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  111. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  112. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  113. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +94 -9
  114. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -1592
  115. package/packages/client/dist/git/epic-operational-state.js +2 -672
  116. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  117. package/packages/client/dist/git/git-lifecycle-store.d.ts +88 -0
  118. package/packages/client/dist/git/git-lifecycle-store.js +9 -2529
  119. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  120. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  121. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  122. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  123. package/packages/client/dist/git/release-gate-env.d.ts +62 -0
  124. package/packages/client/dist/git/release-gate-env.js +1 -0
  125. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  126. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -186
  127. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  128. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  129. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  130. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  131. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  132. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  133. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  134. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  135. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  136. package/packages/client/dist/i18n/first-run.js +2 -60
  137. package/packages/client/dist/index.js +1 -50
  138. package/packages/client/dist/invocation/invoke-input.js +1 -24
  139. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  140. package/packages/client/dist/license/index.js +1 -5
  141. package/packages/client/dist/license/license-client.js +1 -337
  142. package/packages/client/dist/machine/fingerprint.js +2 -163
  143. package/packages/client/dist/machine/index.js +1 -5
  144. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  145. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  146. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  147. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  148. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  149. package/packages/client/dist/migrations/project-identity.js +7 -493
  150. package/packages/client/dist/migrations/state-json.js +4 -393
  151. package/packages/client/dist/policy/architecture-policy.js +2 -184
  152. package/packages/client/dist/policy/index.js +1 -7
  153. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  154. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  155. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  156. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  157. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  158. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  159. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  160. package/packages/client/dist/private-execution/delivery.js +13 -410
  161. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  162. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  163. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  164. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  165. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  166. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  167. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  168. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  169. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  170. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  171. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  172. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  173. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  174. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  175. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  176. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  177. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  178. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  179. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  180. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  181. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  182. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  183. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  184. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  185. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  186. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  187. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  188. package/packages/client/dist/private-execution/session-lease.js +1 -63
  189. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  190. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  191. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  192. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  193. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  194. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  195. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  196. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  197. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  198. package/packages/client/dist/resilience/index.js +1 -8
  199. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  200. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  201. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  202. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  203. package/packages/client/dist/runner/binary.js +1 -404
  204. package/packages/client/dist/runner/cli.js +17 -1571
  205. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  206. package/packages/client/dist/runner/headless/adapters.js +1 -49
  207. package/packages/client/dist/runner/headless/background-root.js +1 -85
  208. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  209. package/packages/client/dist/runner/headless/child-env.js +1 -0
  210. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  211. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  212. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  213. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  214. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
  215. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  216. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  217. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  218. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  219. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  220. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  221. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  222. package/packages/client/dist/runner/headless/resolver.js +1 -231
  223. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  224. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  225. package/packages/client/dist/runner/headless/types.js +2 -575
  226. package/packages/client/dist/runner/host-capacity.js +1 -59
  227. package/packages/client/dist/runner/local-console.js +13 -396
  228. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  229. package/packages/client/dist/runner/project-identity.js +1 -106
  230. package/packages/client/dist/runner/scheduler.js +7 -995
  231. package/packages/client/dist/runner-cli.js +2 -18
  232. package/packages/client/dist/state/invocation-shape.js +1 -13
  233. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  234. package/packages/client/dist/state/state-json-repair.js +3 -785
  235. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  236. package/packages/client/dist/telemetry/index.js +1 -5
  237. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  238. package/packages/client/dist/tier/index.js +1 -5
  239. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  240. package/packages/client/dist/types/index.js +1 -38
  241. package/packages/client/dist/version.js +1 -27
  242. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  243. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  244. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  245. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  246. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  247. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  248. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  249. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  250. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  251. package/packages/client/dist/yoloop/index.js +1 -8
  252. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  253. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
  254. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  255. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  256. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  257. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  258. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  259. package/packages/shared/dist/project-manifest-projection.js +199 -0
  260. package/packages/shared/dist/project-validation-commands.js +14 -6
  261. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  262. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  263. package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
  264. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  265. package/targets-stubs/antigravity/gemini.md +1 -1
  266. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  267. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  268. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  269. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  270. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  271. package/targets-stubs/claude-code/neocortex.md +5 -5
  272. package/targets-stubs/codex/AGENTS.md +1 -1
  273. package/targets-stubs/cursor/agent.md +2 -2
  274. package/targets-stubs/gemini-cli/agent.md +2 -2
  275. package/targets-stubs/lib/managed-config-merge.js +77 -1
  276. package/targets-stubs/lib/managed-profile.sh +7 -0
  277. package/targets-stubs/opencode/neocortex-root.md +1 -1
  278. package/targets-stubs/vscode/install-vscode.sh +21 -0
  279. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,224 +1,2 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
2
- import { homedir } from 'node:os';
3
- import { dirname, join } from 'node:path';
4
- import { SUBAGENT_APPROVAL_MANAGED_DEFAULT, SUBAGENT_APPROVAL_EVIDENCE, SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION, createSubagentApprovalAuditEvent, isSubagentApprovalMode, resolveSubagentApprovalPolicy, } from './policy/subagent-approval-policy.js';
5
- import { setSecureDirPermissions, setSecureFilePermissions, } from './config/secure-config.js';
6
- const POLICY_KEY = 'subagentApprovalPolicy';
7
- const AUDIT_KEY = 'subagentApprovalPolicyAudit';
8
- const MAX_AUDIT_EVENTS = 25;
9
- const AUDIT_EVENTS = new Set([
10
- 'managed-default-materialized',
11
- 'user-override-updated',
12
- 'user-override-reset',
13
- ]);
14
- const APPROVAL_SOURCES = new Set(['managed-default', 'user-override']);
15
- const APPROVAL_SCOPES = new Set([
16
- 'child',
17
- 'session',
18
- 'global',
19
- 'inherited',
20
- 'none',
21
- ]);
22
- const EFFECTIVE_REASONS = new Set([
23
- 'requested-mode-honored',
24
- 'host-policy-reduced',
25
- 'host-capability-unvalidated',
26
- 'host-capability-unsupported',
27
- 'platform-target-unknown',
28
- ]);
29
- const FALLBACK_MODES = new Set(['none', 'root-inline', 'shell-loop']);
30
- const PLATFORM_TARGETS = new Set([
31
- 'claude-code',
32
- 'opencode',
33
- 'codex',
34
- 'gemini',
35
- 'vscode',
36
- 'github-copilot-cli',
37
- 'kimi',
38
- 'cursor',
39
- 'antigravity',
40
- 'openclaw',
41
- 'grok',
42
- 'deepseek',
43
- 'runner',
44
- 'unknown',
45
- ]);
46
- export class ApprovalPolicyConfigError extends Error {
47
- reasonCode;
48
- constructor(reasonCode, message) {
49
- super(message);
50
- this.reasonCode = reasonCode;
51
- this.name = 'ApprovalPolicyConfigError';
52
- }
53
- }
54
- function configFilePath(options) {
55
- return options.configFilePath ?? join(homedir(), '.neocortex', 'config.json');
56
- }
57
- function readConfig(options) {
58
- const path = configFilePath(options);
59
- if (!existsSync(path))
60
- return {};
61
- try {
62
- const parsed = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
63
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
64
- throw new Error('Config root must be an object');
65
- }
66
- return parsed;
67
- }
68
- catch (error) {
69
- if (error instanceof ApprovalPolicyConfigError)
70
- throw error;
71
- throw new ApprovalPolicyConfigError('approval-config-invalid', 'Neocortex config is not valid JSON; approval policy was not changed.');
72
- }
73
- }
74
- function readStoredPolicy(config) {
75
- const value = config[POLICY_KEY];
76
- if (value === undefined)
77
- return undefined;
78
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
79
- throw new ApprovalPolicyConfigError('approval-config-invalid', 'Stored subagent approval policy is invalid.');
80
- }
81
- const policy = value;
82
- if (policy.schemaVersion !== SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION) {
83
- throw new ApprovalPolicyConfigError('approval-policy-schema-unsupported', 'Stored subagent approval policy schema is not supported.');
84
- }
85
- if (policy.userOverride !== undefined &&
86
- !isSubagentApprovalMode(policy.userOverride)) {
87
- throw new ApprovalPolicyConfigError('approval-policy-mode-invalid', 'Stored subagent approval mode is invalid.');
88
- }
89
- return policy;
90
- }
91
- function resolveFromConfig(config, options) {
92
- const policy = readStoredPolicy(config);
93
- return resolveSubagentApprovalPolicy({
94
- userOverride: policy?.userOverride,
95
- hostPolicy: options.hostPolicy,
96
- platformTarget: options.platformTarget,
97
- });
98
- }
99
- function appendAudit(config, event) {
100
- const existing = Array.isArray(config[AUDIT_KEY])
101
- ? config[AUDIT_KEY]
102
- .map(normalizeStoredAuditEvent)
103
- .filter((entry) => entry !== null)
104
- : [];
105
- config[AUDIT_KEY] = [...existing, event].slice(-MAX_AUDIT_EVENTS);
106
- }
107
- function normalizeStoredAuditEvent(value) {
108
- if (!value || typeof value !== 'object' || Array.isArray(value))
109
- return null;
110
- const entry = value;
111
- if (entry.evidence !== SUBAGENT_APPROVAL_EVIDENCE ||
112
- entry.schemaVersion !== SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION ||
113
- !AUDIT_EVENTS.has(String(entry.event)) ||
114
- !isSubagentApprovalMode(entry.requestedMode) ||
115
- !isSubagentApprovalMode(entry.effectiveMode) ||
116
- !APPROVAL_SOURCES.has(String(entry.source)) ||
117
- !PLATFORM_TARGETS.has(String(entry.platformTarget)) ||
118
- !APPROVAL_SCOPES.has(String(entry.scope)) ||
119
- !EFFECTIVE_REASONS.has(String(entry.effectiveReason)) ||
120
- typeof entry.occurredAt !== 'string' ||
121
- !Number.isFinite(Date.parse(entry.occurredAt))) {
122
- return null;
123
- }
124
- const derivedFallback = resolveSubagentApprovalPolicy({
125
- userOverride: entry.requestedMode,
126
- platformTarget: String(entry.platformTarget),
127
- });
128
- const fallbackMode = FALLBACK_MODES.has(String(entry.fallbackMode))
129
- ? entry.fallbackMode
130
- : derivedFallback.fallbackMode;
131
- const fallbackReasonCode = entry.fallbackReasonCode === null ||
132
- typeof entry.fallbackReasonCode === 'string'
133
- ? entry.fallbackReasonCode
134
- : derivedFallback.fallbackReasonCode;
135
- return createSubagentApprovalAuditEvent(entry.event, {
136
- schemaVersion: SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION,
137
- requestedMode: entry.requestedMode,
138
- effectiveMode: entry.effectiveMode,
139
- source: entry.source,
140
- platformTarget: entry.platformTarget,
141
- scope: entry.scope,
142
- effectiveReason: entry.effectiveReason,
143
- fallbackMode,
144
- fallbackReasonCode,
145
- }, entry.occurredAt);
146
- }
147
- function writeConfig(config, options) {
148
- const path = configFilePath(options);
149
- const dir = dirname(path);
150
- const temporaryPath = `${path}.tmp`;
151
- mkdirSync(dir, { recursive: true });
152
- setSecureDirPermissions(dir);
153
- try {
154
- writeFileSync(temporaryPath, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
155
- setSecureFilePermissions(temporaryPath);
156
- renameSync(temporaryPath, path);
157
- setSecureFilePermissions(path);
158
- }
159
- catch (error) {
160
- try {
161
- if (existsSync(temporaryPath))
162
- unlinkSync(temporaryPath);
163
- }
164
- catch {
165
- // Best-effort cleanup; preserve the original write failure.
166
- }
167
- throw error;
168
- }
169
- }
170
- function occurredAt(options) {
171
- return (options.now?.() ?? new Date()).toISOString();
172
- }
173
- export function getSubagentApprovalPolicy(options = {}) {
174
- return { resolution: resolveFromConfig(readConfig(options), options) };
175
- }
176
- export function ensureManagedSubagentApprovalPolicy(options = {}) {
177
- const config = readConfig(options);
178
- const existing = readStoredPolicy(config);
179
- if (existing) {
180
- return { resolution: resolveFromConfig(config, options) };
181
- }
182
- const at = occurredAt(options);
183
- config[POLICY_KEY] = {
184
- schemaVersion: SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION,
185
- managedDefault: SUBAGENT_APPROVAL_MANAGED_DEFAULT,
186
- updatedAt: at,
187
- };
188
- const resolution = resolveFromConfig(config, options);
189
- const auditEvent = createSubagentApprovalAuditEvent('managed-default-materialized', resolution, at);
190
- appendAudit(config, auditEvent);
191
- writeConfig(config, options);
192
- return { resolution, auditEvent };
193
- }
194
- export function setSubagentApprovalMode(mode, options = {}) {
195
- if (!isSubagentApprovalMode(mode)) {
196
- throw new ApprovalPolicyConfigError('approval-policy-mode-invalid', 'Requested subagent approval mode is invalid.');
197
- }
198
- const config = readConfig(options);
199
- const existing = readStoredPolicy(config);
200
- const at = occurredAt(options);
201
- config[POLICY_KEY] = {
202
- ...(existing ?? {}),
203
- schemaVersion: SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION,
204
- managedDefault: SUBAGENT_APPROVAL_MANAGED_DEFAULT,
205
- userOverride: mode,
206
- updatedAt: at,
207
- };
208
- const resolution = resolveFromConfig(config, options);
209
- const auditEvent = createSubagentApprovalAuditEvent('user-override-updated', resolution, at);
210
- appendAudit(config, auditEvent);
211
- writeConfig(config, options);
212
- return { resolution, auditEvent };
213
- }
214
- export function resetSubagentApprovalMode(options = {}) {
215
- const config = readConfig(options);
216
- readStoredPolicy(config);
217
- delete config[POLICY_KEY];
218
- const at = occurredAt(options);
219
- const resolution = resolveFromConfig(config, options);
220
- const auditEvent = createSubagentApprovalAuditEvent('user-override-reset', resolution, at);
221
- appendAudit(config, auditEvent);
222
- writeConfig(config, options);
223
- return { resolution, auditEvent };
224
- }
1
+ import{existsSync as y,mkdirSync as w,readFileSync as O,renameSync as C,unlinkSync as M,writeFileSync as T}from"node:fs";import{homedir as R}from"node:os";import{dirname as _,join as k}from"node:path";import{SUBAGENT_APPROVAL_MANAGED_DEFAULT as h,SUBAGENT_APPROVAL_EVIDENCE as F,SUBAGENT_APPROVAL_POLICY_SCHEMA_VERSION as c,createSubagentApprovalAuditEvent as l,isSubagentApprovalMode as d,resolveSubagentApprovalPolicy as E}from"./policy/subagent-approval-policy.js";import{setSecureDirPermissions as V,setSecureFilePermissions as b}from"./config/secure-config.js";const u="subagentApprovalPolicy",g="subagentApprovalPolicyAudit",x=25,N=new Set(["managed-default-materialized","user-override-updated","user-override-reset"]),D=new Set(["managed-default","user-override"]),L=new Set(["child","session","global","inherited","none"]),I=new Set(["requested-mode-honored","host-policy-reduced","host-capability-unvalidated","host-capability-unsupported","platform-target-unknown"]),U=new Set(["none","root-inline","shell-loop"]),j=new Set(["claude-code","opencode","codex","gemini","vscode","github-copilot-cli","kimi","cursor","antigravity","openclaw","grok","deepseek","runner","unknown"]);class i extends Error{reasonCode;constructor(e,t){super(t),this.reasonCode=e,this.name="ApprovalPolicyConfigError"}}function P(r){return r.configFilePath??k(R(),".neocortex","config.json")}function p(r){const e=P(r);if(!y(e))return{};try{const t=JSON.parse(O(e,"utf8").replace(/^\uFEFF/,""));if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Config root must be an object");return t}catch(t){throw t instanceof i?t:new i("approval-config-invalid","Neocortex config is not valid JSON; approval policy was not changed.")}}function f(r){const e=r[u];if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new i("approval-config-invalid","Stored subagent approval policy is invalid.");const t=e;if(t.schemaVersion!==c)throw new i("approval-policy-schema-unsupported","Stored subagent approval policy schema is not supported.");if(t.userOverride!==void 0&&!d(t.userOverride))throw new i("approval-policy-mode-invalid","Stored subagent approval mode is invalid.");return t}function s(r,e){const t=f(r);return E({userOverride:t?.userOverride,hostPolicy:e.hostPolicy,platformTarget:e.platformTarget})}function v(r,e){const t=Array.isArray(r[g])?r[g].map(q).filter(n=>n!==null):[];r[g]=[...t,e].slice(-x)}function q(r){if(!r||typeof r!="object"||Array.isArray(r))return null;const e=r;if(e.evidence!==F||e.schemaVersion!==c||!N.has(String(e.event))||!d(e.requestedMode)||!d(e.effectiveMode)||!D.has(String(e.source))||!j.has(String(e.platformTarget))||!L.has(String(e.scope))||!I.has(String(e.effectiveReason))||typeof e.occurredAt!="string"||!Number.isFinite(Date.parse(e.occurredAt)))return null;const t=E({userOverride:e.requestedMode,platformTarget:String(e.platformTarget)}),n=U.has(String(e.fallbackMode))?e.fallbackMode:t.fallbackMode,o=e.fallbackReasonCode===null||typeof e.fallbackReasonCode=="string"?e.fallbackReasonCode:t.fallbackReasonCode;return l(e.event,{schemaVersion:c,requestedMode:e.requestedMode,effectiveMode:e.effectiveMode,source:e.source,platformTarget:e.platformTarget,scope:e.scope,effectiveReason:e.effectiveReason,fallbackMode:n,fallbackReasonCode:o},e.occurredAt)}function A(r,e){const t=P(e),n=_(t),o=`${t}.tmp`;w(n,{recursive:!0}),V(n);try{T(o,`${JSON.stringify(r,null,2)}
2
+ `,"utf8"),b(o),C(o,t),b(t)}catch(a){try{y(o)&&M(o)}catch{}throw a}}function S(r){return(r.now?.()??new Date).toISOString()}function K(r={}){return{resolution:s(p(r),r)}}function $(r={}){const e=p(r);if(f(e))return{resolution:s(e,r)};const n=S(r);e[u]={schemaVersion:c,managedDefault:h,updatedAt:n};const o=s(e,r),a=l("managed-default-materialized",o,n);return v(e,a),A(e,r),{resolution:o,auditEvent:a}}function H(r,e={}){if(!d(r))throw new i("approval-policy-mode-invalid","Requested subagent approval mode is invalid.");const t=p(e),n=f(t),o=S(e);t[u]={...n??{},schemaVersion:c,managedDefault:h,userOverride:r,updatedAt:o};const a=s(t,e),m=l("user-override-updated",a,o);return v(t,m),A(t,e),{resolution:a,auditEvent:m}}function X(r={}){const e=p(r);f(e),delete e[u];const t=S(r),n=s(e,r),o=l("user-override-reset",n,t);return v(e,o),A(e,r),{resolution:n,auditEvent:o}}export{i as ApprovalPolicyConfigError,$ as ensureManagedSubagentApprovalPolicy,K as getSubagentApprovalPolicy,X as resetSubagentApprovalMode,H as setSubagentApprovalMode};
@@ -1,25 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * This file is part of Neocortex CLI, licensed under the
6
- * Functional Source License, Version 1.1 (FSL-1.1).
7
- *
8
- * Change Date: February 20, 2029
9
- * Change License: MIT
10
- *
11
- * See the LICENSE file in the project root for full license text.
12
- */
13
- /**
14
- * Production server URL.
15
- *
16
- * Single Source of Truth for the default Neocortex IP Protection Server URL.
17
- * All client-side code MUST import this constant instead of hardcoding the URL.
18
- *
19
- * Shell scripts (install.sh, install.ps1) cannot import from TypeScript,
20
- * so they maintain a hardcoded copy with a comment referencing this file.
21
- *
22
- * Epic 70 - Story 70.03
23
- * Epic P46 - Story P46.01: migrated legacy API host to api.neocortex.sh
24
- */
25
- export const DEFAULT_SERVER_URL = 'https://api.neocortex.sh';
1
+ const t="https://api.neocortex.sh";export{t as DEFAULT_SERVER_URL};
@@ -1,222 +1,2 @@
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 - Context Collector
15
- *
16
- * Collects pipeline context from state.json, package.json, and story files.
17
- * Sanitizes all sensitive data before returning the context.
18
- */
19
- import { readFile } from 'node:fs/promises';
20
- import { join } from 'node:path';
21
- import { sanitizeObject } from './context-sanitizer.js';
22
- // ── Frontmatter extraction (reused from local-resolver) ──────────────────
23
- const FRONTMATTER_REGEX = /^---\n([\s\S]*?)\n---/;
24
- function extractFrontmatter(content) {
25
- const match = content.match(FRONTMATTER_REGEX);
26
- if (!match)
27
- return {};
28
- const result = {};
29
- for (const line of match[1].split('\n')) {
30
- const colonIndex = line.indexOf(':');
31
- if (colonIndex === -1)
32
- continue;
33
- const key = line.slice(0, colonIndex).trim().replace(/^['"]|['"]$/g, '');
34
- const value = line.slice(colonIndex + 1).trim().replace(/^['"]|['"]$/g, '');
35
- result[key] = value;
36
- }
37
- return result;
38
- }
39
- // ── Acceptance Criteria Extraction ───────────────────────────────────────
40
- function extractAcceptanceCriteria(content) {
41
- const criteria = [];
42
- const acPattern = /\*\*AC\d+:?\s*([^*]+)\*\*/g;
43
- let match;
44
- while ((match = acPattern.exec(content)) !== null) {
45
- criteria.push(match[1].trim());
46
- }
47
- return criteria;
48
- }
49
- // ── Framework Detection ──────────────────────────────────────────────────
50
- const FRAMEWORK_INDICATORS = {
51
- react: 'React',
52
- next: 'Next.js',
53
- vue: 'Vue',
54
- nuxt: 'Nuxt',
55
- angular: 'Angular',
56
- svelte: 'Svelte',
57
- express: 'Express',
58
- fastify: 'Fastify',
59
- nest: 'NestJS',
60
- koa: 'Koa',
61
- hapi: 'Hapi',
62
- };
63
- function detectFrameworks(deps) {
64
- const frameworks = [];
65
- for (const [dep, name] of Object.entries(FRAMEWORK_INDICATORS)) {
66
- if (dep in deps) {
67
- frameworks.push(name);
68
- }
69
- }
70
- return frameworks;
71
- }
72
- // ── Language Detection ───────────────────────────────────────────────────
73
- function detectLanguages(deps) {
74
- const languages = new Set();
75
- languages.add('JavaScript'); // Always present in Node.js projects
76
- if ('typescript' in deps || Object.keys(deps).some((d) => d.includes('ts-'))) {
77
- languages.add('TypeScript');
78
- }
79
- return [...languages];
80
- }
81
- /**
82
- * Collect complete pipeline context.
83
- *
84
- * Reads state.json, package.json, and story file to build
85
- * a sanitized PipelineContext for the remote server.
86
- */
87
- export async function collectContext(options) {
88
- const { projectRoot, storyFilePath, storyId, stepId, platformTarget } = options;
89
- // Collect state context
90
- const stateContext = await collectStateContext(projectRoot, storyId);
91
- // Collect codebase metadata
92
- const codebaseMetadata = await collectCodebaseMetadata(projectRoot);
93
- // Collect story metadata
94
- const storyMetadata = await collectStoryMetadata(storyFilePath);
95
- // Build context
96
- const context = {
97
- storyId,
98
- stepId,
99
- epicId: storyMetadata.epicId || stateContext.epicId || '',
100
- storyTitle: storyMetadata.title,
101
- currentStatus: stateContext.status,
102
- stepsCompleted: stateContext.stepsCompleted,
103
- branchName: stateContext.branchName,
104
- platformTarget: platformTarget || detectPlatform(),
105
- codebaseMetadata,
106
- storyMetadata,
107
- };
108
- // Sanitize before returning
109
- return sanitizeObject(context, projectRoot);
110
- }
111
- /**
112
- * Collect state context from state.json.
113
- */
114
- async function collectStateContext(projectRoot, storyId) {
115
- try {
116
- const statePath = join(projectRoot, '.neocortex', 'state.json');
117
- const raw = await readFile(statePath, 'utf-8');
118
- const state = JSON.parse(raw);
119
- const story = state.stories?.[storyId];
120
- return {
121
- status: story?.status || 'unknown',
122
- stepsCompleted: story?.steps_completed || [],
123
- branchName: story?.branch_name || '',
124
- epicId: story?.epic_id || '',
125
- };
126
- }
127
- catch {
128
- return {
129
- status: 'unknown',
130
- stepsCompleted: [],
131
- branchName: '',
132
- epicId: '',
133
- };
134
- }
135
- }
136
- /**
137
- * Collect codebase metadata from package.json.
138
- */
139
- async function collectCodebaseMetadata(projectRoot) {
140
- try {
141
- const pkgPath = join(projectRoot, 'package.json');
142
- const raw = await readFile(pkgPath, 'utf-8');
143
- const pkg = JSON.parse(raw);
144
- const allDeps = {
145
- ...(pkg.dependencies || {}),
146
- ...(pkg.devDependencies || {}),
147
- };
148
- return {
149
- projectName: pkg.name || 'unknown',
150
- languages: detectLanguages(allDeps),
151
- frameworks: detectFrameworks(allDeps),
152
- dependencies: pkg.dependencies || {},
153
- nodeVersion: process.version,
154
- };
155
- }
156
- catch {
157
- return {
158
- projectName: 'unknown',
159
- languages: ['JavaScript'],
160
- frameworks: [],
161
- dependencies: {},
162
- nodeVersion: process.version,
163
- };
164
- }
165
- }
166
- /**
167
- * Collect story metadata from the story file.
168
- */
169
- async function collectStoryMetadata(storyFilePath) {
170
- try {
171
- const raw = await readFile(storyFilePath, 'utf-8');
172
- const fm = extractFrontmatter(raw);
173
- const acs = extractAcceptanceCriteria(raw);
174
- // Parse dependencies array from frontmatter
175
- let deps = [];
176
- const depsStr = fm['dependencies'];
177
- if (depsStr) {
178
- try {
179
- deps = JSON.parse(depsStr.replace(/'/g, '"'));
180
- }
181
- catch {
182
- deps = depsStr.split(',').map((d) => d.trim().replace(/[[\]"']/g, ''));
183
- }
184
- }
185
- return {
186
- id: fm['id'] || '',
187
- epicId: fm['epic_id'] || '',
188
- title: fm['title'] || '',
189
- status: fm['status'] || fm['currentStatus'] || '',
190
- dependencies: deps,
191
- acceptanceCriteria: acs,
192
- };
193
- }
194
- catch {
195
- return {
196
- id: '',
197
- epicId: '',
198
- title: '',
199
- status: '',
200
- dependencies: [],
201
- acceptanceCriteria: [],
202
- };
203
- }
204
- }
205
- /**
206
- * Detect the platform target from environment.
207
- */
208
- function detectPlatform() {
209
- if (process.env['CLAUDE_CODE'] || process.env['CLAUDE_AGENT']) {
210
- return 'claude-code';
211
- }
212
- if (process.env['CURSOR_SESSION_ID']) {
213
- return 'cursor';
214
- }
215
- if (process.env['VSCODE_PID']) {
216
- return 'vscode';
217
- }
218
- if (process.env['GEMINI_CLI']) {
219
- return 'gemini';
220
- }
221
- return 'unknown';
222
- }
1
+ import{readFile as i}from"node:fs/promises";import{join as p}from"node:path";import{sanitizeObject as l}from"./context-sanitizer.js";const f=/^---\n([\s\S]*?)\n---/;function m(s){const e=s.match(f);if(!e)return{};const t={};for(const n of e[1].split(`
2
+ `)){const c=n.indexOf(":");if(c===-1)continue;const a=n.slice(0,c).trim().replace(/^['"]|['"]$/g,""),r=n.slice(c+1).trim().replace(/^['"]|['"]$/g,"");t[a]=r}return t}function g(s){const e=[],t=/\*\*AC\d+:?\s*([^*]+)\*\*/g;let n;for(;(n=t.exec(s))!==null;)e.push(n[1].trim());return e}const S={react:"React",next:"Next.js",vue:"Vue",nuxt:"Nuxt",angular:"Angular",svelte:"Svelte",express:"Express",fastify:"Fastify",nest:"NestJS",koa:"Koa",hapi:"Hapi"};function w(s){const e=[];for(const[t,n]of Object.entries(S))t in s&&e.push(n);return e}function y(s){const e=new Set;return e.add("JavaScript"),("typescript"in s||Object.keys(s).some(t=>t.includes("ts-")))&&e.add("TypeScript"),[...e]}async function O(s){const{projectRoot:e,storyFilePath:t,storyId:n,stepId:c,platformTarget:a}=s,r=await h(e,n),u=await C(e),o=await I(t),d={storyId:n,stepId:c,epicId:o.epicId||r.epicId||"",storyTitle:o.title,currentStatus:r.status,stepsCompleted:r.stepsCompleted,branchName:r.branchName,platformTarget:a||x(),codebaseMetadata:u,storyMetadata:o};return l(d,e)}async function h(s,e){try{const t=p(s,".neocortex","state.json"),n=await i(t,"utf-8"),a=JSON.parse(n).stories?.[e];return{status:a?.status||"unknown",stepsCompleted:a?.steps_completed||[],branchName:a?.branch_name||"",epicId:a?.epic_id||""}}catch{return{status:"unknown",stepsCompleted:[],branchName:"",epicId:""}}}async function C(s){try{const e=p(s,"package.json"),t=await i(e,"utf-8"),n=JSON.parse(t),c={...n.dependencies||{},...n.devDependencies||{}};return{projectName:n.name||"unknown",languages:y(c),frameworks:w(c),dependencies:n.dependencies||{},nodeVersion:process.version}}catch{return{projectName:"unknown",languages:["JavaScript"],frameworks:[],dependencies:{},nodeVersion:process.version}}}async function I(s){try{const e=await i(s,"utf-8"),t=m(e),n=g(e);let c=[];const a=t.dependencies;if(a)try{c=JSON.parse(a.replace(/'/g,'"'))}catch{c=a.split(",").map(r=>r.trim().replace(/[[\]"']/g,""))}return{id:t.id||"",epicId:t.epic_id||"",title:t.title||"",status:t.status||t.currentStatus||"",dependencies:c,acceptanceCriteria:n}}catch{return{id:"",epicId:"",title:"",status:"",dependencies:[],acceptanceCriteria:[]}}}function x(){return process.env.CLAUDE_CODE||process.env.CLAUDE_AGENT?"claude-code":process.env.CURSOR_SESSION_ID?"cursor":process.env.VSCODE_PID?"vscode":process.env.GEMINI_CLI?"gemini":"unknown"}export{O as collectContext};
@@ -1,145 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * This file is part of Neocortex CLI, licensed under the
6
- * Functional Source License, Version 1.1 (FSL-1.1).
7
- *
8
- * Change Date: February 20, 2029
9
- * Change License: MIT
10
- *
11
- * See the LICENSE file in the project root for full license text.
12
- */
13
- /**
14
- * @neocortex/client - Context Sanitizer
15
- *
16
- * Removes sensitive data from pipeline context before sending
17
- * to the remote server. Strips absolute paths, tokens, credentials,
18
- * and other sensitive information.
19
- */
20
- import { homedir } from 'node:os';
21
- // ── Sensitive Patterns ───────────────────────────────────────────────────
22
- /** Environment variable name patterns that indicate sensitive values */
23
- const SENSITIVE_ENV_PATTERNS = [
24
- /token/i,
25
- /key/i,
26
- /secret/i,
27
- /password/i,
28
- /credential/i,
29
- /auth/i,
30
- /github_pat_/i,
31
- /npm_token/i,
32
- /api_key/i,
33
- ];
34
- /** Regex patterns for sensitive values in strings */
35
- const SENSITIVE_VALUE_PATTERNS = [
36
- /github_pat_[A-Za-z0-9_]{36,}/g,
37
- /ghp_[A-Za-z0-9]{36,}/g,
38
- /gho_[A-Za-z0-9]{36,}/g,
39
- /sk-[A-Za-z0-9]{32,}/g,
40
- /Bearer\s+[A-Za-z0-9._\-]+/g,
41
- /-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----[\s\S]*?-----END/g,
42
- ];
43
- /** Maximum allowed string length before truncation */
44
- const MAX_VALUE_LENGTH = 1000;
45
- // ── Sanitization Functions ───────────────────────────────────────────────
46
- /**
47
- * Replace absolute paths with relative ones.
48
- *
49
- * Converts paths like /Users/john/projects/neocortex/src/file.ts
50
- * to ./src/file.ts based on the project root.
51
- */
52
- function sanitizePaths(value, projectRoot) {
53
- let result = value;
54
- // Replace project root path with ./
55
- if (projectRoot) {
56
- const escapedRoot = projectRoot.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
57
- result = result.replace(new RegExp(escapedRoot, 'g'), '.');
58
- }
59
- // Replace home directory with ~
60
- const home = homedir();
61
- if (home) {
62
- const escapedHome = home.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
63
- result = result.replace(new RegExp(escapedHome, 'g'), '~');
64
- }
65
- return result;
66
- }
67
- /**
68
- * Remove sensitive tokens and credentials from a string.
69
- */
70
- function sanitizeTokens(value) {
71
- let result = value;
72
- for (const pattern of SENSITIVE_VALUE_PATTERNS) {
73
- result = result.replace(pattern, '[REDACTED]');
74
- }
75
- return result;
76
- }
77
- /**
78
- * Truncate a string value if it exceeds the maximum length.
79
- */
80
- function truncateValue(value) {
81
- if (value.length <= MAX_VALUE_LENGTH) {
82
- return value;
83
- }
84
- return `${value.slice(0, MAX_VALUE_LENGTH)}...[truncated, ${value.length} chars total]`;
85
- }
86
- /**
87
- * Check if an environment variable name indicates a sensitive value.
88
- */
89
- function isSensitiveKey(key) {
90
- return SENSITIVE_ENV_PATTERNS.some((pattern) => pattern.test(key));
91
- }
92
- // ── Public API ───────────────────────────────────────────────────────────
93
- /**
94
- * Sanitize a single string value.
95
- *
96
- * Applies path sanitization, token removal, and truncation.
97
- */
98
- export function sanitizeValue(value, projectRoot) {
99
- let result = sanitizePaths(value, projectRoot);
100
- result = sanitizeTokens(result);
101
- result = truncateValue(result);
102
- return result;
103
- }
104
- /**
105
- * Sanitize a record of key-value pairs.
106
- *
107
- * Removes entries with sensitive keys and sanitizes remaining values.
108
- */
109
- export function sanitizeRecord(record, projectRoot) {
110
- const sanitized = {};
111
- for (const [key, value] of Object.entries(record)) {
112
- if (isSensitiveKey(key)) {
113
- continue; // Drop sensitive keys entirely
114
- }
115
- sanitized[key] = sanitizeValue(value, projectRoot);
116
- }
117
- return sanitized;
118
- }
119
- /**
120
- * Deep sanitize an object, processing all string values recursively.
121
- */
122
- export function sanitizeObject(obj, projectRoot) {
123
- if (obj === null || obj === undefined) {
124
- return obj;
125
- }
126
- if (typeof obj === 'string') {
127
- return sanitizeValue(obj, projectRoot);
128
- }
129
- if (Array.isArray(obj)) {
130
- return obj.map((item) => sanitizeObject(item, projectRoot));
131
- }
132
- if (typeof obj === 'object') {
133
- const result = {};
134
- for (const [key, value] of Object.entries(obj)) {
135
- if (isSensitiveKey(key) && typeof value === 'string') {
136
- result[key] = '[REDACTED]';
137
- }
138
- else {
139
- result[key] = sanitizeObject(value, projectRoot);
140
- }
141
- }
142
- return result;
143
- }
144
- return obj;
145
- }
1
+ import{homedir as o}from"node:os";const f=[/token/i,/key/i,/secret/i,/password/i,/credential/i,/auth/i,/github_pat_/i,/npm_token/i,/api_key/i],l=[/github_pat_[A-Za-z0-9_]{36,}/g,/ghp_[A-Za-z0-9]{36,}/g,/gho_[A-Za-z0-9]{36,}/g,/sk-[A-Za-z0-9]{32,}/g,/Bearer\s+[A-Za-z0-9._\-]+/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----[\s\S]*?-----END/g],s=1e3;function p(e,n){let t=e;if(n){const i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(i,"g"),".")}const r=o();if(r){const i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(i,"g"),"~")}return t}function g(e){let n=e;for(const t of l)n=n.replace(t,"[REDACTED]");return n}function E(e){return e.length<=s?e:`${e.slice(0,s)}...[truncated, ${e.length} chars total]`}function a(e){return f.some(n=>n.test(e))}function c(e,n){let t=p(e,n);return t=g(t),t=E(t),t}function _(e,n){const t={};for(const[r,i]of Object.entries(e))a(r)||(t[r]=c(i,n));return t}function u(e,n){if(e==null)return e;if(typeof e=="string")return c(e,n);if(Array.isArray(e))return e.map(t=>u(t,n));if(typeof e=="object"){const t={};for(const[r,i]of Object.entries(e))a(r)&&typeof i=="string"?t[r]="[REDACTED]":t[r]=u(i,n);return t}return e}export{u as sanitizeObject,_ as sanitizeRecord,c as sanitizeValue};