@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,150 +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
- * P225.05 -- short, private, cross-OS story worktree paths (P225-CON-WORKTREE).
15
- *
16
- * Identity and root computation are pure: platform, environment and home
17
- * directory are injected seams so linux/darwin/win32 rules are testable on any
18
- * host. Absolute paths returned here are private and must never be printed;
19
- * public output uses `worktreeRef` (`wt/<hash8>`) only.
20
- */
21
- import { createHash } from 'node:crypto';
22
- import { lstat, mkdir, chmod } from 'node:fs/promises';
23
- import { posix, win32 } from 'node:path';
24
- /** Windows keeps the default worktree path well below MAX_PATH-sensitive tools. */
25
- export const STORY_WORKTREE_WIN32_MAX_PATH = 80;
26
- export const STORY_WORKTREE_ROOT_ENV = 'NEOCORTEX_STORY_WORKTREE_ROOT';
27
- export const STORY_WORKTREE_ID_ENV = 'NEOCORTEX_STORY_WORKTREE_ID';
28
- const STORY_ID = /^P[1-9][0-9]*(?:\.[0-9]+)*$/;
29
- const DISPATCH_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;
30
- export function storyWorktreeIdentity(input) {
31
- const { epicId, storyId, dispatchId } = input;
32
- if (typeof epicId !== 'string' || !STORY_ID.test(epicId) || epicId.includes('.')
33
- || typeof storyId !== 'string' || !STORY_ID.test(storyId) || !storyId.startsWith(`${epicId}.`)
34
- || typeof dispatchId !== 'string' || !DISPATCH_ID.test(dispatchId)) {
35
- return { ok: false, reasonCode: 'story-worktree-identity-invalid' };
36
- }
37
- const digest = createHash('sha256').update(`${epicId}|${storyId}|${dispatchId}`).digest('hex');
38
- const hash8 = digest.slice(0, 8);
39
- return {
40
- ok: true,
41
- value: Object.freeze({
42
- epicId,
43
- storyId,
44
- dispatchId,
45
- hash8,
46
- temporaryBranch: `nx/${epicId}/${hash8}`,
47
- executionBranch: `epic/${epicId}`,
48
- leaseId: `swt-${digest.slice(0, 24)}`,
49
- worktreeId: `nxwt-${hash8}`,
50
- worktreeRef: `wt/${hash8}`,
51
- }),
52
- };
53
- }
54
- function pathApi(platform) {
55
- return platform === 'win32' ? win32 : posix;
56
- }
57
- function normalizePlatform(value) {
58
- return value === 'linux' || value === 'darwin' || value === 'win32' ? value : undefined;
59
- }
60
- /** Resolve the private root `<cache>/nx/wt` for the given platform. */
61
- export function resolveStoryWorktreeRoot(input = {}) {
62
- const platform = normalizePlatform(input.platform ?? process.platform);
63
- if (!platform)
64
- return { ok: false, reasonCode: 'story-worktree-platform-unsupported' };
65
- const api = pathApi(platform);
66
- const env = input.env ?? process.env;
67
- const explicit = input.override ?? env[STORY_WORKTREE_ROOT_ENV];
68
- if (explicit !== undefined && explicit !== '') {
69
- if (!api.isAbsolute(explicit))
70
- return { ok: false, reasonCode: 'story-worktree-root-invalid' };
71
- return { ok: true, value: api.normalize(explicit) };
72
- }
73
- const home = input.homedir;
74
- const absoluteOrUndefined = (value) => value && api.isAbsolute(value) ? value : undefined;
75
- let base;
76
- if (platform === 'linux') {
77
- base = absoluteOrUndefined(env.XDG_CACHE_HOME)
78
- ?? (absoluteOrUndefined(home) ? api.join(home, '.cache') : undefined);
79
- }
80
- else if (platform === 'darwin') {
81
- base = absoluteOrUndefined(home) ? api.join(home, 'Library', 'Caches') : undefined;
82
- }
83
- else {
84
- base = absoluteOrUndefined(env.LOCALAPPDATA)
85
- ?? (absoluteOrUndefined(home) ? api.join(home, 'AppData', 'Local') : undefined);
86
- }
87
- if (!base)
88
- return { ok: false, reasonCode: 'story-worktree-root-invalid' };
89
- return { ok: true, value: api.join(base, 'nx', 'wt') };
90
- }
91
- function isInside(api, parent, child, caseInsensitive) {
92
- const fold = (value) => (caseInsensitive ? value.toLowerCase() : value);
93
- const relative = api.relative(fold(parent), fold(child));
94
- const escapes = relative === '..' || relative.startsWith(`..${api.sep}`);
95
- return relative === '' || (!escapes && !api.isAbsolute(relative));
96
- }
97
- /** Compute `<root>/<hash8>` and enforce length and out-of-repository rules. */
98
- export function resolveStoryWorktreePath(input) {
99
- const platform = normalizePlatform(input.platform ?? process.platform);
100
- if (!platform)
101
- return { ok: false, reasonCode: 'story-worktree-platform-unsupported' };
102
- const api = pathApi(platform);
103
- if (!/^[a-f0-9]{8}$/.test(input.hash8))
104
- return { ok: false, reasonCode: 'story-worktree-identity-invalid' };
105
- if (!api.isAbsolute(input.root) || !api.isAbsolute(input.repositoryRoot)) {
106
- return { ok: false, reasonCode: 'story-worktree-root-invalid' };
107
- }
108
- const path = api.join(api.normalize(input.root), input.hash8);
109
- if (platform === 'win32' && path.length > STORY_WORKTREE_WIN32_MAX_PATH) {
110
- return { ok: false, reasonCode: 'story-worktree-path-too-long' };
111
- }
112
- const caseInsensitive = platform !== 'linux';
113
- if (isInside(api, input.repositoryRoot, path, caseInsensitive)
114
- || isInside(api, path, input.repositoryRoot, caseInsensitive)) {
115
- return { ok: false, reasonCode: 'story-worktree-path-inside-repository' };
116
- }
117
- return { ok: true, value: path };
118
- }
119
- /**
120
- * Create the private root (0700 on POSIX), refusing symlinked or non-directory
121
- * segments that already exist under the deepest existing ancestor.
122
- */
123
- export async function ensurePrivateStoryWorktreeRoot(root, platform = process.platform) {
124
- const api = platform === 'win32' ? win32 : posix;
125
- if (!api.isAbsolute(root))
126
- return { ok: false, reasonCode: 'story-worktree-root-invalid' };
127
- // Validate the two private leaf segments (`nx/wt` or the override itself).
128
- const leaves = [api.dirname(root), root];
129
- try {
130
- await mkdir(root, { recursive: true, mode: 0o700 });
131
- for (const segment of leaves) {
132
- const info = await lstat(segment);
133
- if (info.isSymbolicLink() || !info.isDirectory())
134
- return { ok: false, reasonCode: 'story-worktree-root-unsafe' };
135
- }
136
- if (platform !== 'win32') {
137
- await chmod(root, 0o700);
138
- const info = await lstat(root);
139
- if ((info.mode & 0o077) !== 0)
140
- return { ok: false, reasonCode: 'story-worktree-root-unsafe' };
141
- if (typeof process.getuid === 'function' && info.uid !== process.getuid()) {
142
- return { ok: false, reasonCode: 'story-worktree-root-unsafe' };
143
- }
144
- }
145
- }
146
- catch {
147
- return { ok: false, reasonCode: 'story-worktree-root-unsafe' };
148
- }
149
- return { ok: true, value: root };
150
- }
1
+ import{createHash as w}from"node:crypto";import{lstat as c,mkdir as m,chmod as h}from"node:fs/promises";import{posix as d,win32 as l}from"node:path";const R=80,O="NEOCORTEX_STORY_WORKTREE_ROOT",T="NEOCORTEX_STORY_WORKTREE_ID",u=/^P[1-9][0-9]*(?:\.[0-9]+)*$/,C=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;function v(e){const{epicId:r,storyId:o,dispatchId:n}=e;if(typeof r!="string"||!u.test(r)||r.includes(".")||typeof o!="string"||!u.test(o)||!o.startsWith(`${r}.`)||typeof n!="string"||!C.test(n))return{ok:!1,reasonCode:"story-worktree-identity-invalid"};const s=w("sha256").update(`${r}|${o}|${n}`).digest("hex"),t=s.slice(0,8);return{ok:!0,value:Object.freeze({epicId:r,storyId:o,dispatchId:n,hash8:t,temporaryBranch:`nx/${r}/${t}`,executionBranch:`epic/${r}`,leaseId:`swt-${s.slice(0,24)}`,worktreeId:`nxwt-${t}`,worktreeRef:`wt/${t}`})}}function p(e){return e==="win32"?l:d}function k(e){return e==="linux"||e==="darwin"||e==="win32"?e:void 0}function x(e={}){const r=k(e.platform??process.platform);if(!r)return{ok:!1,reasonCode:"story-worktree-platform-unsupported"};const o=p(r),n=e.env??process.env,s=e.override??n[O];if(s!==void 0&&s!=="")return o.isAbsolute(s)?{ok:!0,value:o.normalize(s)}:{ok:!1,reasonCode:"story-worktree-root-invalid"};const t=e.homedir,a=f=>f&&o.isAbsolute(f)?f:void 0;let i;return r==="linux"?i=a(n.XDG_CACHE_HOME)??(a(t)?o.join(t,".cache"):void 0):r==="darwin"?i=a(t)?o.join(t,"Library","Caches"):void 0:i=a(n.LOCALAPPDATA)??(a(t)?o.join(t,"AppData","Local"):void 0),i?{ok:!0,value:o.join(i,"nx","wt")}:{ok:!1,reasonCode:"story-worktree-root-invalid"}}function y(e,r,o,n){const s=i=>n?i.toLowerCase():i,t=e.relative(s(r),s(o)),a=t===".."||t.startsWith(`..${e.sep}`);return t===""||!a&&!e.isAbsolute(t)}function I(e){const r=k(e.platform??process.platform);if(!r)return{ok:!1,reasonCode:"story-worktree-platform-unsupported"};const o=p(r);if(!/^[a-f0-9]{8}$/.test(e.hash8))return{ok:!1,reasonCode:"story-worktree-identity-invalid"};if(!o.isAbsolute(e.root)||!o.isAbsolute(e.repositoryRoot))return{ok:!1,reasonCode:"story-worktree-root-invalid"};const n=o.join(o.normalize(e.root),e.hash8);if(r==="win32"&&n.length>R)return{ok:!1,reasonCode:"story-worktree-path-too-long"};const s=r!=="linux";return y(o,e.repositoryRoot,n,s)||y(o,n,e.repositoryRoot,s)?{ok:!1,reasonCode:"story-worktree-path-inside-repository"}:{ok:!0,value:n}}async function $(e,r=process.platform){const o=r==="win32"?l:d;if(!o.isAbsolute(e))return{ok:!1,reasonCode:"story-worktree-root-invalid"};const n=[o.dirname(e),e];try{await m(e,{recursive:!0,mode:448});for(const s of n){const t=await c(s);if(t.isSymbolicLink()||!t.isDirectory())return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}if(r!=="win32"){await h(e,448);const s=await c(e);if((s.mode&63)!==0)return{ok:!1,reasonCode:"story-worktree-root-unsafe"};if(typeof process.getuid=="function"&&s.uid!==process.getuid())return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}}catch{return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}return{ok:!0,value:e}}export{T as STORY_WORKTREE_ID_ENV,O as STORY_WORKTREE_ROOT_ENV,R as STORY_WORKTREE_WIN32_MAX_PATH,$ as ensurePrivateStoryWorktreeRoot,I as resolveStoryWorktreePath,x as resolveStoryWorktreeRoot,v as storyWorktreeIdentity};
@@ -0,0 +1,44 @@
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
+ export interface StoryWriteSetExtensionValue {
14
+ readonly storyId: string;
15
+ readonly epicId: string;
16
+ readonly outcome: 'recorded' | 'unchanged';
17
+ readonly extensionPathCount: number;
18
+ readonly extensionDigest: string;
19
+ readonly authorizedPathCount: number;
20
+ /** Digest of the sorted union (the claim revision every C08/integration binds). */
21
+ readonly claimRevision: string;
22
+ }
23
+ export type StoryWriteSetExtensionResult = {
24
+ readonly ok: true;
25
+ readonly value: StoryWriteSetExtensionValue;
26
+ } | {
27
+ readonly ok: false;
28
+ readonly reasonCode: string;
29
+ };
30
+ export interface ExtendStoryWriteSetOptions {
31
+ /** Root (main) checkout; secondary worktrees are refused. */
32
+ readonly projectRoot: string;
33
+ readonly storyId: string;
34
+ readonly paths: readonly string[];
35
+ readonly nowIso?: string;
36
+ /** Test seam between the authority read and the CAS write (race reproduction). */
37
+ readonly beforeCas?: () => Promise<void>;
38
+ }
39
+ /**
40
+ * Root-only, idempotent: re-applying the same set is a no-op, a superset
41
+ * replaces it under CAS (expected runtime revision + runtime lock), and the
42
+ * integration lock serializes it with the single integrator.
43
+ */
44
+ export declare function extendStoryWriteSet(options: ExtendStoryWriteSetOptions): Promise<StoryWriteSetExtensionResult>;
@@ -0,0 +1 @@
1
+ import{execFile as E}from"node:child_process";import{createHash as D}from"node:crypto";import{readFile as k,realpath as S}from"node:fs/promises";import{join as P,resolve as A}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLock as C,ensureRuntimeStory as L,isStoryWorktreeIntegrationReceiptRecord as b,isStoryWriteSetExtensionPath as T,mutateGitLifecycleRuntime as W,readGitLifecycleRuntime as j,readStoryWorktreeEvidence as O,releaseGitLifecyclePhysicalIntegrationLock as G,STORY_WRITE_SET_MAX_ENTRIES as I,storyWriteSetExtensionDigest as $,storyWriteSetExtensionPaths as z,verifyGitLifecyclePhysicalIntegrationLock as M}from"./git-lifecycle-store.js";const N=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class p extends Error{reasonCode;constructor(n){super(n),this.reasonCode=n}}function t(e){throw new p(e)}function _(e,n){return new Promise((i,r)=>{E("git",[...n],{cwd:e,encoding:"utf8",timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(c,s)=>c?r(new p("story-write-set-extension-not-root")):i(String(s).trim()))})}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function q(e){return D("sha256").update([...e].sort().join("\0")).digest("hex")}function v(e,n,i,r,c){const s=g(g(n.stories)?.[i]);s||t("story-write-set-extension-story-missing");const d=typeof s.epic_id=="string"?s.epic_id:i.split(".")[0];i.startsWith(`${d}.`)||t("story-write-set-extension-story-missing");const y=e.stories[i];(O(e,d)?.receipts??[]).filter(b).some(a=>a.storyId===i&&a.outcome==="integrated")&&t("story-write-set-extension-story-integrated"),(y?.checkpoint||s.checkpoint)&&t("story-write-set-extension-checkpoint-accepted");const u=g(e.epics[d]?.branch_lease);u&&Date.parse(String(u.expiresAt))>c&&t("story-write-set-extension-writer-active");const f=z(y);y?.write_set_extension!==void 0&&f.length===0&&t("story-write-set-extension-invalid"),f.some(a=>!r.includes(a))&&t("story-write-set-extension-not-superset");const l=Array.isArray(s.files_to_modify)?s.files_to_modify.filter(a=>typeof a=="string"):[],w=[...new Set([...l,...r])].sort();return w.length>I&&t("story-write-set-extension-too-large"),{epicId:d,union:w,unchanged:f.length===r.length}}async function V(e){const n=A(e.projectRoot);let i;try{(typeof e.storyId!="string"||!N.test(e.storyId))&&t("story-write-set-extension-story-invalid"),(!Array.isArray(e.paths)||e.paths.length===0||e.paths.length>I||e.paths.some(o=>!T(o)))&&t("story-write-set-extension-path-invalid");const r=[...new Set(e.paths)].sort(),c=await S(await _(n,["rev-parse","--absolute-git-dir"])),s=await S(await _(n,["rev-parse","--path-format=absolute","--git-common-dir"]));c!==s&&t("story-write-set-extension-not-root");const d=new Date(e.nowIso??Date.now()).toISOString(),y=P(n,".neocortex","state.json"),h=await k(y,"utf8"),u=g(JSON.parse(h))??t("story-write-set-extension-state-invalid"),f=await j(n,{required:!0}),l=v(f,u,e.storyId,r,Date.now()),w=$(r),a=o=>({ok:!0,value:Object.freeze({storyId:e.storyId,epicId:l.epicId,outcome:o,extensionPathCount:r.length,extensionDigest:w,authorizedPathCount:l.union.length,claimRevision:q(l.union)})});if(l.unchanged)return a("unchanged");const x=`write-set-extension-${w.slice(0,40)}`;i=await C(n,{kind:"direct",storyId:e.storyId,sessionId:x,idempotencyKey:x,expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1}),i.ok||t(i.reasonCode==="git-lifecycle-integration-backpressure"?"story-write-set-extension-backpressure":"story-write-set-extension-lock-failed");const m=i;await e.beforeCas?.();const R={schemaVersion:1,kind:"root-write-set-extension",paths:r,digest:w,approvedAt:d,approvedBy:"root_agent"};try{await W(n,o=>{v(o,u,e.storyId,r,Date.now()).unchanged&&t("story-write-set-extension-raced"),L(o,e.storyId).write_set_extension=R},{expectedRevision:f.revision,preCommit:async()=>{await M(m.path,m.owner)||t("story-write-set-extension-lock-raced"),await k(y,"utf8")!==h&&t("story-write-set-extension-raced")}})}catch(o){throw o instanceof Error&&o.message==="git-lifecycle-runtime-revision-conflict"&&t("story-write-set-extension-raced"),o}return a("recorded")}catch(r){if(r instanceof p)return{ok:!1,reasonCode:r.reasonCode};const c=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(c)?{ok:!1,reasonCode:c}:{ok:!1,reasonCode:"story-write-set-extension-failed"}}finally{i?.ok&&await G(i.path,i.owner).catch(()=>{})}}export{V as extendStoryWriteSet};
@@ -1,284 +1 @@
1
- /**
2
- * P158.06 -- optional pre-command deterministic graph retrieval enrichment.
3
- *
4
- * The client collects a tiny, public, redacted context envelope for commands
5
- * resolved by the shared command context policy shadow. It never constructs
6
- * workflow prompts or decides orchestration; the server validates and decides
7
- * whether to consume this auxiliary metadata.
8
- */
9
- import { createHash } from 'node:crypto';
10
- import { existsSync, readFileSync, statSync } from 'node:fs';
11
- import { join } from 'node:path';
12
- import { DEFAULT_GRAPH_RETRIEVAL_BUDGETS, createGraphRetrievalMetadata, normalizeGraphRetrievalPath, resolveClientCommandContextPolicy, } from './shared-graph-retrieval-contract.js';
13
- import { admitInvocation, } from '../../../shared/dist/invocation/index.js';
14
- const CONTRACT_VERSION = 'client-pre-command-v1';
15
- const DEFAULT_GENERATED_AT = '1970-01-01T00:00:00.000Z';
16
- const ARCHIVE_PATH_SEGMENTS = new Set(['.archive', '_archive', '_archives', 'archive', 'archives', 'archived']);
17
- const DEFAULT_FILE_READER = Object.freeze({
18
- exists: existsSync,
19
- stat: statSync,
20
- readText: (path) => readFileSync(path, 'utf8'),
21
- });
22
- export function admitGraphInvocation(args) {
23
- return admitInvocation(args);
24
- }
25
- function resolveAdmission(args) {
26
- const admission = admitGraphInvocation(args);
27
- if (admission.outcome !== 'resolved')
28
- return null;
29
- const policy = resolveClientCommandContextPolicy(admission.selection.commandId);
30
- return policy ? { policy, selection: admission.selection } : null;
31
- }
32
- function stableHash(input) {
33
- return createHash('sha256').update(input).digest('hex');
34
- }
35
- function isUnsafeGraphRetrievalPath(relativePath) {
36
- const normalized = normalizeGraphRetrievalPath(relativePath);
37
- const containsArchiveSegment = normalized
38
- .split('/')
39
- .some((segment) => ARCHIVE_PATH_SEGMENTS.has(segment.toLowerCase()));
40
- return normalized.length === 0 ||
41
- normalized.startsWith('/') ||
42
- normalized.startsWith('..') ||
43
- normalized.includes('/../') ||
44
- containsArchiveSegment ||
45
- /(^|\/)\.env(?:$|[./-])/i.test(normalized) ||
46
- /(^|\/)(?:credentials?|secrets?|tokens?|private-prompts?|raw-logs?)(?:\.|\/|$)/i.test(normalized) ||
47
- /\.(?:sqlite|db|pem|key|p12|pfx|crt|cer|der|bin)$/i.test(normalized);
48
- }
49
- function sourceFor(projectRoot, relativePath, fileReader) {
50
- const normalized = normalizeGraphRetrievalPath(relativePath);
51
- if (isUnsafeGraphRetrievalPath(normalized)) {
52
- return null;
53
- }
54
- const absolute = join(projectRoot, normalized);
55
- if (!fileReader.exists(absolute))
56
- return null;
57
- const stat = fileReader.stat(absolute);
58
- if (!stat.isFile() || stat.size > 96 * 1024)
59
- return null;
60
- const content = fileReader.readText(absolute);
61
- return {
62
- kind: 'repo-path',
63
- path: normalized,
64
- contentHash: stableHash(content).slice(0, 16),
65
- mtimeMs: Math.floor(stat.mtimeMs),
66
- };
67
- }
68
- function redactPublicText(input) {
69
- let text = input;
70
- const before = text;
71
- text = text.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[REDACTED_EMAIL]');
72
- text = text.replace(/\b(api[-_ ]?key|license[-_ ]?key|token|password|secret)\b\s*[:=]\s*[^\s`'"\])}]+/gi, '$1=[REDACTED_SECRET]');
73
- text = text.replace(/\b(?:sk|pk|ghp|github_pat|pat)_[A-Za-z0-9_\-]{16,}\b/g, '[REDACTED_TOKEN]');
74
- text = text.replace(/\b[A-Za-z0-9+/]{32,}={0,2}\b/g, '[REDACTED_TOKEN]');
75
- text = text.replace(/<!--\s*(?:server|private|proprietary)[\s\S]*?-->/gi, '[REDACTED_PRIVATE_PROMPT]');
76
- text = text.replace(/\b(?:private|proprietary|protected)\s+(?:prompt|workflow|step\s*body|orchestration)\b[^.!?\n]*/gi, '[REDACTED_PRIVATE_PROMPT]');
77
- return { text, redacted: text !== before };
78
- }
79
- function compactSummary(content, maxChars = DEFAULT_GRAPH_RETRIEVAL_BUDGETS.maxSnippetChars) {
80
- const lines = content
81
- .split(/\r?\n/)
82
- .map((line) => line.trim())
83
- .filter((line) => line.length > 0 && !line.startsWith('---') && !line.startsWith('<!--'))
84
- .slice(0, 8)
85
- .join(' ');
86
- const redacted = redactPublicText(lines);
87
- return {
88
- summary: redacted.text.slice(0, maxChars),
89
- redacted: redacted.redacted,
90
- };
91
- }
92
- function readItem(projectRoot, params, fileReader) {
93
- const source = sourceFor(projectRoot, params.path, fileReader);
94
- if (!source)
95
- return null;
96
- const content = fileReader.readText(join(projectRoot, source.path));
97
- const summary = compactSummary(content, params.maxSnippetChars);
98
- return {
99
- nodeType: params.nodeType,
100
- stableId: params.stableId,
101
- source,
102
- confidence: summary.redacted ? Math.min(params.confidence, 0.72) : params.confidence,
103
- reasonCode: params.reasonCode,
104
- budgetCost: params.budgetCost,
105
- summary: summary.summary,
106
- warnings: summary.redacted ? ['redacted_sensitive_content'] : undefined,
107
- score: params.score,
108
- };
109
- }
110
- function generatedCommandItem(policy) {
111
- const summary = `Public command ${policy.commandId}; graphRetrieval profile ${policy.retrievalProfile}; context is auxiliary, redacted, budgeted and non-authoritative.`;
112
- return {
113
- nodeType: 'Command',
114
- stableId: `command:${policy.commandId}`,
115
- source: {
116
- kind: 'command',
117
- path: policy.commandId,
118
- contentHash: stableHash(summary).slice(0, 16),
119
- },
120
- confidence: 0.88,
121
- reasonCode: 'command_surface_match',
122
- budgetCost: 1,
123
- summary: summary.slice(0, policy.retrievalBudget.maxSnippetChars),
124
- score: 90,
125
- };
126
- }
127
- function targetTokens(selection) {
128
- const typedPath = selection.uiUxReview?.architectureDir;
129
- return typedPath ? [...selection.positionals, typedPath] : selection.positionals;
130
- }
131
- function extractStoryPath(tokens) {
132
- const token = tokens.find((value) => /^@?docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/u.test(value));
133
- return token?.replace(/^@/u, '') ?? null;
134
- }
135
- function extractEpicPath(tokens) {
136
- const token = tokens.find((value) => /^@?docs\/epics\/[A-Za-z0-9._-]+\.md$/u.test(value));
137
- return token?.replace(/^@/u, '') ?? null;
138
- }
139
- function extractEpicId(tokens) {
140
- const storyPath = extractStoryPath(tokens);
141
- const storyId = storyPath?.split('/').pop()?.replace(/\.story\.md$/, '');
142
- const fromStory = storyId?.match(/^(P\d+)\./i)?.[1];
143
- if (fromStory)
144
- return fromStory.toUpperCase();
145
- const direct = tokens
146
- .map((value) => value.match(/^@?(?:docs\/epics\/epic-)?(P\d+)(?:\.md)?$/iu)?.[1])
147
- .find((value) => Boolean(value));
148
- return direct ? direct.toUpperCase() : null;
149
- }
150
- function extractMarkdownPaths(tokens) {
151
- return tokens
152
- .map((value) => value.match(/^@?((?:docs|core)\/[A-Za-z0-9_./-]+\.md)$/u)?.[1])
153
- .filter((value) => Boolean(value))
154
- .map((value) => normalizeGraphRetrievalPath(value))
155
- .filter((path) => !isUnsafeGraphRetrievalPath(path));
156
- }
157
- function candidateKindForPath(path) {
158
- if (path.startsWith('docs/stories/'))
159
- return { nodeType: 'Story', reasonCode: 'story_scope_match' };
160
- if (path.startsWith('docs/epics/'))
161
- return { nodeType: 'Epic', reasonCode: 'epic_scope_match' };
162
- if (path.includes('security') || path.includes('policy') || path.includes('standard'))
163
- return { nodeType: 'Guardrail', reasonCode: 'guardrail_match' };
164
- return { nodeType: 'Doc', reasonCode: 'architecture_reference' };
165
- }
166
- function addSpec(specs, spec) {
167
- const normalized = normalizeGraphRetrievalPath(spec.path);
168
- if (isUnsafeGraphRetrievalPath(normalized))
169
- return;
170
- const duplicate = specs.some((existing) => existing.nodeType === spec.nodeType && normalizeGraphRetrievalPath(existing.path) === normalized);
171
- if (!duplicate)
172
- specs.push({ ...spec, path: normalized });
173
- }
174
- function addTargetSpecs(specs, tokens, maxSnippetChars) {
175
- const storyPath = extractStoryPath(tokens);
176
- if (storyPath) {
177
- const storyId = storyPath.split('/').pop()?.replace(/\.story\.md$/, '') ?? storyPath;
178
- addSpec(specs, { path: storyPath, nodeType: 'Story', stableId: storyId, reasonCode: 'story_scope_match', confidence: 0.96, budgetCost: 3, score: 96, maxSnippetChars });
179
- }
180
- const epicPath = extractEpicPath(tokens);
181
- const epicId = extractEpicId(tokens);
182
- if (epicPath) {
183
- const stableId = epicPath.split('/').pop()?.replace(/\.md$/, '') ?? epicPath;
184
- addSpec(specs, { path: epicPath, nodeType: 'Epic', stableId, reasonCode: 'epic_scope_match', confidence: 0.92, budgetCost: 3, score: 92, maxSnippetChars });
185
- }
186
- else if (epicId) {
187
- addSpec(specs, { path: `docs/epics/epic-${epicId}.md`, nodeType: 'Epic', stableId: epicId, reasonCode: 'epic_scope_match', confidence: 0.9, budgetCost: 3, score: 90, maxSnippetChars });
188
- }
189
- for (const path of extractMarkdownPaths(tokens)) {
190
- const stableId = path.split('/').pop()?.replace(/\.md$/, '').replace(/\.story$/, '') ?? path;
191
- const kind = candidateKindForPath(path);
192
- addSpec(specs, { path, stableId, ...kind, confidence: 0.84, budgetCost: 3, score: 82, maxSnippetChars });
193
- }
194
- }
195
- function collectCandidateItems(policy, selection, projectRoot, fileReader) {
196
- const maxSnippetChars = policy.retrievalBudget.maxSnippetChars;
197
- const specs = [];
198
- addSpec(specs, { path: 'NEOCORTEX.md', nodeType: 'CanonicalMemory', stableId: 'canonical-memory', reasonCode: 'canonical_memory_seed', confidence: 0.92, budgetCost: 4, score: 100, maxSnippetChars });
199
- addSpec(specs, { path: 'AGENTS.md', nodeType: 'PlatformMemory', stableId: 'platform-memory:agents', reasonCode: 'platform_memory_reference', confidence: 0.7, budgetCost: 2, score: 66, maxSnippetChars });
200
- addSpec(specs, { path: 'package.json', nodeType: 'Package', stableId: 'root-package', reasonCode: 'package_surface_match', confidence: 0.78, budgetCost: 2, score: 72, maxSnippetChars });
201
- if (policy.retrievalProfile !== 'utility' || policy.commandId === 'ui-ux-review') {
202
- addSpec(specs, { path: 'docs/arquitetura-software/deterministic-graph-retrieval.md', nodeType: 'Doc', stableId: 'deterministic-graph-retrieval', reasonCode: 'architecture_reference', confidence: 0.9, budgetCost: 4, score: 84, maxSnippetChars });
203
- }
204
- addTargetSpecs(specs, targetTokens(selection), maxSnippetChars);
205
- if (['story-execution', 'diagnostic', 'research', 'review', 'qa', 'recovery', 'planning'].includes(policy.retrievalProfile) || policy.commandId === 'tech-debt') {
206
- addSpec(specs, { path: '.neocortex/tech-debt-registry.json', nodeType: 'Debt', stableId: 'tech-debt-registry', reasonCode: 'debt_area_match', confidence: 0.74, budgetCost: 3, score: 76, maxSnippetChars });
207
- }
208
- if (['story-execution', 'diagnostic', 'research', 'review', 'qa', 'recovery', 'planning', 'architecture'].includes(policy.retrievalProfile)) {
209
- addSpec(specs, { path: 'core/standards/spec-driven-development.md', nodeType: 'Guardrail', stableId: 'spec-driven-development', reasonCode: 'guardrail_match', confidence: 0.82, budgetCost: 3, score: 78, maxSnippetChars });
210
- }
211
- if (policy.retrievalProfile === 'security') {
212
- addSpec(specs, { path: 'docs/architecture/solyd-security-system-contract.md', nodeType: 'Guardrail', stableId: 'solyd-security-system-contract', reasonCode: 'guardrail_match', confidence: 0.86, budgetCost: 3, score: 84, maxSnippetChars });
213
- }
214
- if (policy.retrievalProfile === 'continuity') {
215
- addSpec(specs, { path: 'core/standards/enterprise-continuity-plane.md', nodeType: 'Guardrail', stableId: 'enterprise-continuity-plane', reasonCode: 'guardrail_match', confidence: 0.86, budgetCost: 3, score: 84, maxSnippetChars });
216
- addSpec(specs, { path: 'docs/runbooks/enterprise-continuity-runner.md', nodeType: 'Doc', stableId: 'enterprise-continuity-runner', reasonCode: 'architecture_reference', confidence: 0.78, budgetCost: 3, score: 72, maxSnippetChars });
217
- }
218
- if (['utility', 'continuity', 'recovery'].includes(policy.retrievalProfile)) {
219
- addSpec(specs, { path: '.neocortex/state.json', nodeType: 'State', stableId: 'project-state', reasonCode: 'state_status_match', confidence: 0.68, budgetCost: 3, score: 70, maxSnippetChars });
220
- }
221
- return [generatedCommandItem(policy), ...specs
222
- .map((spec) => readItem(projectRoot, spec, fileReader))
223
- .filter((item) => item !== null)];
224
- }
225
- function enforceSerializedPayloadLimit(metadata) {
226
- let items = [...metadata.items];
227
- let next = metadata;
228
- const maxPayloadBytes = Math.min(metadata.budget.maxPayloadBytes, DEFAULT_GRAPH_RETRIEVAL_BUDGETS.maxPayloadBytes);
229
- while (Buffer.byteLength(JSON.stringify(next), 'utf8') > maxPayloadBytes && items.length > 0) {
230
- const removed = items.pop();
231
- const base = createGraphRetrievalMetadata({
232
- retrievalId: metadata.retrievalId,
233
- query: metadata.query,
234
- items,
235
- generatedAt: metadata.generatedAt,
236
- warnings: metadata.warnings,
237
- budgets: metadata.budget,
238
- });
239
- next = {
240
- ...base,
241
- skipped: removed
242
- ? [...base.skipped, { stableId: removed.stableId, source: removed.source, reasonCode: 'budget_exceeded' }]
243
- : base.skipped,
244
- contractVersion: CONTRACT_VERSION,
245
- command: metadata.command,
246
- };
247
- }
248
- return next;
249
- }
250
- export async function runGraphRetrievalHook(ctx) {
251
- const resolved = resolveAdmission(ctx.args);
252
- if (!resolved) {
253
- return { applied: false, reason: 'command_not_allowlisted' };
254
- }
255
- const { policy, selection } = resolved;
256
- const command = policy.commandId;
257
- try {
258
- const items = collectCandidateItems(policy, selection, ctx.projectRoot, ctx.fileReader ?? DEFAULT_FILE_READER);
259
- if (items.length === 0)
260
- return { applied: false, reason: 'no_items', command, profile: policy.retrievalProfile };
261
- // Query and target projection consume only values emitted by the exact
262
- // admission authority. Raw quoting/option syntax is never reparsed here.
263
- const query = redactPublicText(selection.positionals.join(' ').slice(0, 240)).text;
264
- const retrievalId = stableHash(`${CONTRACT_VERSION}:${command}:${query}:${items.map((item) => `${item.source.path}:${item.source.contentHash ?? ''}`).sort().join('|')}`).slice(0, 24);
265
- const base = createGraphRetrievalMetadata({
266
- retrievalId,
267
- query,
268
- items,
269
- generatedAt: ctx.nowIso ?? DEFAULT_GENERATED_AT,
270
- budgets: policy.retrievalBudget,
271
- });
272
- const metadata = enforceSerializedPayloadLimit({
273
- ...base,
274
- contractVersion: CONTRACT_VERSION,
275
- command,
276
- });
277
- return { applied: true, reason: 'applied', command, profile: policy.retrievalProfile, metadata };
278
- }
279
- catch (err) {
280
- const msg = err instanceof Error ? err.message : String(err);
281
- ctx.logger?.warn?.(`[neocortex] graph retrieval hook failed: ${msg}. Proceeding without enrichment.`);
282
- return { applied: false, reason: 'hook_error', command, profile: policy.retrievalProfile, warning: msg };
283
- }
284
- }
1
+ import{createHash as v}from"node:crypto";import{existsSync as T,readFileSync as I,statSync as E}from"node:fs";import{join as h}from"node:path";import{DEFAULT_GRAPH_RETRIEVAL_BUDGETS as y,createGraphRetrievalMetadata as g,normalizeGraphRetrievalPath as i,resolveClientCommandContextPolicy as P}from"./shared-graph-retrieval-contract.js";import{admitInvocation as A}from"../../../shared/dist/invocation/index.js";const u="client-pre-command-v1",x="1970-01-01T00:00:00.000Z",R=new Set([".archive","_archive","_archives","archive","archives","archived"]),S=Object.freeze({exists:T,stat:E,readText:e=>I(e,"utf8")});function k(e){return A(e)}function $(e){const t=k(e);if(t.outcome!=="resolved")return null;const o=P(t.selection.commandId);return o?{policy:o,selection:t.selection}:null}function p(e){return v("sha256").update(e).digest("hex")}function m(e){const t=i(e),o=t.split("/").some(s=>R.has(s.toLowerCase()));return t.length===0||t.startsWith("/")||t.startsWith("..")||t.includes("/../")||o||/(^|\/)\.env(?:$|[./-])/i.test(t)||/(^|\/)(?:credentials?|secrets?|tokens?|private-prompts?|raw-logs?)(?:\.|\/|$)/i.test(t)||/\.(?:sqlite|db|pem|key|p12|pfx|crt|cer|der|bin)$/i.test(t)}function D(e,t,o){const s=i(t);if(m(s))return null;const r=h(e,s);if(!o.exists(r))return null;const n=o.stat(r);if(!n.isFile()||n.size>96*1024)return null;const a=o.readText(r);return{kind:"repo-path",path:s,contentHash:p(a).slice(0,16),mtimeMs:Math.floor(n.mtimeMs)}}function b(e){let t=e;const o=t;return t=t.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"[REDACTED_EMAIL]"),t=t.replace(/\b(api[-_ ]?key|license[-_ ]?key|token|password|secret)\b\s*[:=]\s*[^\s`'"\])}]+/gi,"$1=[REDACTED_SECRET]"),t=t.replace(/\b(?:sk|pk|ghp|github_pat|pat)_[A-Za-z0-9_\-]{16,}\b/g,"[REDACTED_TOKEN]"),t=t.replace(/\b[A-Za-z0-9+/]{32,}={0,2}\b/g,"[REDACTED_TOKEN]"),t=t.replace(/<!--\s*(?:server|private|proprietary)[\s\S]*?-->/gi,"[REDACTED_PRIVATE_PROMPT]"),t=t.replace(/\b(?:private|proprietary|protected)\s+(?:prompt|workflow|step\s*body|orchestration)\b[^.!?\n]*/gi,"[REDACTED_PRIVATE_PROMPT]"),{text:t,redacted:t!==o}}function w(e,t=y.maxSnippetChars){const o=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("---")&&!r.startsWith("<!--")).slice(0,8).join(" "),s=b(o);return{summary:s.text.slice(0,t),redacted:s.redacted}}function G(e,t,o){const s=D(e,t.path,o);if(!s)return null;const r=o.readText(h(e,s.path)),n=w(r,t.maxSnippetChars);return{nodeType:t.nodeType,stableId:t.stableId,source:s,confidence:n.redacted?Math.min(t.confidence,.72):t.confidence,reasonCode:t.reasonCode,budgetCost:t.budgetCost,summary:n.summary,warnings:n.redacted?["redacted_sensitive_content"]:void 0,score:t.score}}function M(e){const t=`Public command ${e.commandId}; graphRetrieval profile ${e.retrievalProfile}; context is auxiliary, redacted, budgeted and non-authoritative.`;return{nodeType:"Command",stableId:`command:${e.commandId}`,source:{kind:"command",path:e.commandId,contentHash:p(t).slice(0,16)},confidence:.88,reasonCode:"command_surface_match",budgetCost:1,summary:t.slice(0,e.retrievalBudget.maxSnippetChars),score:90}}function z(e){const t=e.uiUxReview?.architectureDir;return t?[...e.positionals,t]:e.positionals}function _(e){return e.find(o=>/^@?docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/u.test(o))?.replace(/^@/u,"")??null}function B(e){return e.find(o=>/^@?docs\/epics\/[A-Za-z0-9._-]+\.md$/u.test(o))?.replace(/^@/u,"")??null}function O(e){const s=_(e)?.split("/").pop()?.replace(/\.story\.md$/,"")?.match(/^(P\d+)\./i)?.[1];if(s)return s.toUpperCase();const r=e.map(n=>n.match(/^@?(?:docs\/epics\/epic-)?(P\d+)(?:\.md)?$/iu)?.[1]).find(n=>!!n);return r?r.toUpperCase():null}function j(e){return e.map(t=>t.match(/^@?((?:docs|core)\/[A-Za-z0-9_./-]+\.md)$/u)?.[1]).filter(t=>!!t).map(t=>i(t)).filter(t=>!m(t))}function H(e){return e.startsWith("docs/stories/")?{nodeType:"Story",reasonCode:"story_scope_match"}:e.startsWith("docs/epics/")?{nodeType:"Epic",reasonCode:"epic_scope_match"}:e.includes("security")||e.includes("policy")||e.includes("standard")?{nodeType:"Guardrail",reasonCode:"guardrail_match"}:{nodeType:"Doc",reasonCode:"architecture_reference"}}function c(e,t){const o=i(t.path);if(m(o))return;e.some(r=>r.nodeType===t.nodeType&&i(r.path)===o)||e.push({...t,path:o})}function L(e,t,o){const s=_(t);if(s){const a=s.split("/").pop()?.replace(/\.story\.md$/,"")??s;c(e,{path:s,nodeType:"Story",stableId:a,reasonCode:"story_scope_match",confidence:.96,budgetCost:3,score:96,maxSnippetChars:o})}const r=B(t),n=O(t);if(r){const a=r.split("/").pop()?.replace(/\.md$/,"")??r;c(e,{path:r,nodeType:"Epic",stableId:a,reasonCode:"epic_scope_match",confidence:.92,budgetCost:3,score:92,maxSnippetChars:o})}else n&&c(e,{path:`docs/epics/epic-${n}.md`,nodeType:"Epic",stableId:n,reasonCode:"epic_scope_match",confidence:.9,budgetCost:3,score:90,maxSnippetChars:o});for(const a of j(t)){const d=a.split("/").pop()?.replace(/\.md$/,"").replace(/\.story$/,"")??a,l=H(a);c(e,{path:a,stableId:d,...l,confidence:.84,budgetCost:3,score:82,maxSnippetChars:o})}}function N(e,t,o,s){const r=e.retrievalBudget.maxSnippetChars,n=[];return c(n,{path:"NEOCORTEX.md",nodeType:"CanonicalMemory",stableId:"canonical-memory",reasonCode:"canonical_memory_seed",confidence:.92,budgetCost:4,score:100,maxSnippetChars:r}),c(n,{path:"AGENTS.md",nodeType:"PlatformMemory",stableId:"platform-memory:agents",reasonCode:"platform_memory_reference",confidence:.7,budgetCost:2,score:66,maxSnippetChars:r}),c(n,{path:"package.json",nodeType:"Package",stableId:"root-package",reasonCode:"package_surface_match",confidence:.78,budgetCost:2,score:72,maxSnippetChars:r}),(e.retrievalProfile!=="utility"||e.commandId==="ui-ux-review")&&c(n,{path:"docs/arquitetura-software/deterministic-graph-retrieval.md",nodeType:"Doc",stableId:"deterministic-graph-retrieval",reasonCode:"architecture_reference",confidence:.9,budgetCost:4,score:84,maxSnippetChars:r}),L(n,z(t),r),(["story-execution","diagnostic","research","review","qa","recovery","planning"].includes(e.retrievalProfile)||e.commandId==="tech-debt")&&c(n,{path:".neocortex/tech-debt-registry.json",nodeType:"Debt",stableId:"tech-debt-registry",reasonCode:"debt_area_match",confidence:.74,budgetCost:3,score:76,maxSnippetChars:r}),["story-execution","diagnostic","research","review","qa","recovery","planning","architecture"].includes(e.retrievalProfile)&&c(n,{path:"core/standards/spec-driven-development.md",nodeType:"Guardrail",stableId:"spec-driven-development",reasonCode:"guardrail_match",confidence:.82,budgetCost:3,score:78,maxSnippetChars:r}),e.retrievalProfile==="security"&&c(n,{path:"docs/architecture/solyd-security-system-contract.md",nodeType:"Guardrail",stableId:"solyd-security-system-contract",reasonCode:"guardrail_match",confidence:.86,budgetCost:3,score:84,maxSnippetChars:r}),e.retrievalProfile==="continuity"&&(c(n,{path:"core/standards/enterprise-continuity-plane.md",nodeType:"Guardrail",stableId:"enterprise-continuity-plane",reasonCode:"guardrail_match",confidence:.86,budgetCost:3,score:84,maxSnippetChars:r}),c(n,{path:"docs/runbooks/enterprise-continuity-runner.md",nodeType:"Doc",stableId:"enterprise-continuity-runner",reasonCode:"architecture_reference",confidence:.78,budgetCost:3,score:72,maxSnippetChars:r})),["utility","continuity","recovery"].includes(e.retrievalProfile)&&c(n,{path:".neocortex/state.json",nodeType:"State",stableId:"project-state",reasonCode:"state_status_match",confidence:.68,budgetCost:3,score:70,maxSnippetChars:r}),[M(e),...n.map(a=>G(o,a,s)).filter(a=>a!==null)]}function Z(e){let t=[...e.items],o=e;const s=Math.min(e.budget.maxPayloadBytes,y.maxPayloadBytes);for(;Buffer.byteLength(JSON.stringify(o),"utf8")>s&&t.length>0;){const r=t.pop(),n=g({retrievalId:e.retrievalId,query:e.query,items:t,generatedAt:e.generatedAt,warnings:e.warnings,budgets:e.budget});o={...n,skipped:r?[...n.skipped,{stableId:r.stableId,source:r.source,reasonCode:"budget_exceeded"}]:n.skipped,contractVersion:u,command:e.command}}return o}async function K(e){const t=$(e.args);if(!t)return{applied:!1,reason:"command_not_allowlisted"};const{policy:o,selection:s}=t,r=o.commandId;try{const n=N(o,s,e.projectRoot,e.fileReader??S);if(n.length===0)return{applied:!1,reason:"no_items",command:r,profile:o.retrievalProfile};const a=b(s.positionals.join(" ").slice(0,240)).text,d=p(`${u}:${r}:${a}:${n.map(f=>`${f.source.path}:${f.source.contentHash??""}`).sort().join("|")}`).slice(0,24),l=g({retrievalId:d,query:a,items:n,generatedAt:e.nowIso??x,budgets:o.retrievalBudget}),C=Z({...l,contractVersion:u,command:r});return{applied:!0,reason:"applied",command:r,profile:o.retrievalProfile,metadata:C}}catch(n){const a=n instanceof Error?n.message:String(n);return e.logger?.warn?.(`[neocortex] graph retrieval hook failed: ${a}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",command:r,profile:o.retrievalProfile,warning:a}}}export{k as admitGraphInvocation,K as runGraphRetrievalHook};