@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,1117 +1,41 @@
1
- /**
2
- * Project memory writer for platform-specific always-loaded files.
3
- *
4
- * The writer owns only the NEOCORTEX-MEMORY block. Everything outside that
5
- * block is preserved byte-for-byte so users can keep local instructions.
6
- */
7
- import { execFileSync } from 'node:child_process';
8
- import { randomUUID } from 'node:crypto';
9
- import { constants as fsConstants, existsSync, lstatSync, mkdirSync, copyFileSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from 'node:fs';
10
- import { platform } from 'node:os';
11
- import { basename, dirname, join, relative, resolve } from 'node:path';
12
- import { CANONICAL_PROJECT_MEMORY_SOURCE, getProjectMemoryTarget, renderArchitectureReferenceTable, } from './shared-project-memory-types.js';
13
- import { assertProjectMemoryPaths, invalidProjectMemoryPath, isValidScopedRelativePath } from './project-memory-path-scope.js';
14
- export const LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON = 'legacy-agent-path-wrapper-tracked';
15
- function hasCanonicalUpdateInput(options) {
16
- return (options.memoryNotes?.length ?? 0) > 0 ||
17
- (options.architectureReferences?.length ?? 0) > 0 ||
18
- options.bootstrapArchitecture !== undefined;
19
- }
20
- const REFRESH_UPDATE_START = '<!-- NEOCORTEX-REFRESH-UPDATES-START -->';
21
- const REFRESH_UPDATE_END = '<!-- NEOCORTEX-REFRESH-UPDATES-END -->';
22
- function occurrenceCount(content, value) {
23
- return content.split(value).length - 1;
24
- }
25
- function canonicalRefreshRows(options) {
26
- assertSafeProjectMemoryInput(options.memoryNotes ?? [], options.architectureReferences ?? [], options.bootstrapArchitecture);
27
- const noteRows = classifyProjectMemoryUpdates(options.memoryNotes ?? [])
28
- .map((entry) => `- [${entry.reasonCode}] ${entry.summary} (layer: ${entry.layer})`);
29
- const referenceRows = (options.architectureReferences ?? []).map((reference) => `- [architecture-reference] \`${reference.path}\`: ${reference.title}; ${reference.purpose}; use: ${reference.suggestedUsage}`);
30
- const bootstrap = options.bootstrapArchitecture;
31
- const bootstrapRows = bootstrap === undefined ? [] : [
32
- ...(bootstrap.universalLaws ?? []).map((value) => `- [bootstrap-law] ${value}`),
33
- ...(bootstrap.businessContext ?? []).map((value) => `- [bootstrap-business] ${value}`),
34
- ...(bootstrap.activeContext ?? []).map((value) => `- [bootstrap-context] ${value}`),
35
- ...(bootstrap.repositoryMap ?? []).map((value) => `- [bootstrap-repository] ${value}`),
36
- ...(bootstrap.environmentPractices ?? []).map((value) => `- [bootstrap-environment] ${value}`),
37
- ...(bootstrap.platformMemoryContract ?? []).map((value) => `- [bootstrap-platform] ${value}`),
38
- ...(bootstrap.maintenanceRules ?? []).map((value) => `- [bootstrap-maintenance] ${value}`),
39
- ...(bootstrap.heuristics ?? []).map((value) => `- [bootstrap-heuristic] ${value}`),
40
- ];
41
- return uniqueLines([...noteRows, ...referenceRows, ...bootstrapRows]);
42
- }
43
- function assertWithinBudgetWithoutTruncation(target, content) {
44
- if (content.split('\n').length > target.budget.maxLines ||
45
- Buffer.byteLength(content, 'utf8') > target.budget.maxBytes) {
46
- throw new Error('Canonical project memory update exceeds its context budget; refusing to truncate existing content.');
47
- }
48
- }
49
- function mergeCanonicalRefreshUpdate(target, existingContent, options) {
50
- const rows = canonicalRefreshRows(options);
51
- if (rows.length === 0)
52
- return existingContent;
53
- const eol = existingContent.includes('\r\n') ? '\r\n' : '\n';
54
- const outerStart = markerStart(target);
55
- const outerEnd = markerEnd(target);
56
- const outerStartCount = occurrenceCount(existingContent, outerStart);
57
- const outerEndCount = occurrenceCount(existingContent, outerEnd);
58
- if (outerStartCount !== 1 || outerEndCount !== 1 || existingContent.indexOf(outerEnd) < existingContent.indexOf(outerStart)) {
59
- throw new Error('Canonical project memory has ambiguous managed-block markers; refusing refresh.');
60
- }
61
- const innerStartCount = occurrenceCount(existingContent, REFRESH_UPDATE_START);
62
- const innerEndCount = occurrenceCount(existingContent, REFRESH_UPDATE_END);
63
- if (innerStartCount !== innerEndCount || innerStartCount > 1) {
64
- throw new Error('Canonical project memory has ambiguous refresh-update markers; refusing refresh.');
65
- }
66
- let nextContent;
67
- if (innerStartCount === 0) {
68
- const outerEndIndex = existingContent.indexOf(outerEnd);
69
- const prefix = existingContent.slice(0, outerEndIndex);
70
- const block = [
71
- REFRESH_UPDATE_START,
72
- '## Durable Refresh Updates',
73
- ...rows,
74
- REFRESH_UPDATE_END,
75
- '',
76
- ].join(eol);
77
- nextContent = `${prefix}${prefix.endsWith(eol) ? '' : eol}${block}${existingContent.slice(outerEndIndex)}`;
78
- }
79
- else {
80
- const innerStartIndex = existingContent.indexOf(REFRESH_UPDATE_START);
81
- const innerEndIndex = existingContent.indexOf(REFRESH_UPDATE_END);
82
- const outerStartIndex = existingContent.indexOf(outerStart);
83
- const outerEndIndex = existingContent.indexOf(outerEnd);
84
- if (innerStartIndex < outerStartIndex || innerEndIndex > outerEndIndex || innerEndIndex < innerStartIndex) {
85
- throw new Error('Canonical refresh-update block is outside the managed block; refusing refresh.');
86
- }
87
- const currentBlock = existingContent.slice(innerStartIndex, innerEndIndex);
88
- const existingRows = new Set(currentBlock.split(/\r?\n/).map((line) => line.trim().toLowerCase()));
89
- const missingRows = rows.filter((row) => !existingRows.has(row.trim().toLowerCase()));
90
- if (missingRows.length === 0)
91
- return existingContent;
92
- const prefix = existingContent.slice(0, innerEndIndex);
93
- nextContent = `${prefix}${prefix.endsWith(eol) ? '' : eol}${missingRows.join(eol)}${eol}${existingContent.slice(innerEndIndex)}`;
94
- }
95
- assertWithinBudgetWithoutTruncation(target, nextContent);
96
- return nextContent;
97
- }
98
- export function createNodeProjectMemoryFs(backupDirectory) {
99
- return {
100
- readFile(path) {
101
- try {
102
- return readFileSync(path, 'utf8');
103
- }
104
- catch {
105
- return undefined;
106
- }
107
- },
108
- writeFileAtomic(path, content) {
109
- mkdirSync(dirname(path), { recursive: true });
110
- const nonce = randomUUID();
111
- const tempPath = `${path}.tmp-${nonce}`;
112
- const backupPath = existsSync(path) ? memoryBackupPath(path, nonce, backupDirectory) : undefined;
113
- try {
114
- writeFileSync(tempPath, content, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
115
- if (backupPath !== undefined)
116
- copyFileSync(path, backupPath, fsConstants.COPYFILE_EXCL);
117
- renameSync(tempPath, path);
118
- return { backupPath };
119
- }
120
- catch (error) {
121
- rmSync(tempPath, { force: true });
122
- if (backupPath !== undefined && existsSync(backupPath)) {
123
- try {
124
- copyFileSync(backupPath, path);
125
- }
126
- catch { /* best-effort rollback */ }
127
- }
128
- throw error;
129
- }
130
- },
131
- join(...parts) {
132
- return join(...parts);
133
- },
134
- };
135
- }
136
- function markerStart(target) {
137
- return `<!-- ${target.ownedBlockName}-START -->`;
138
- }
139
- function markerEnd(target) {
140
- return `<!-- ${target.ownedBlockName}-END -->`;
141
- }
142
- function uniqueLines(values) {
143
- const seen = new Set();
144
- const result = [];
145
- for (const value of values) {
146
- const normalized = value.trim().replace(/\s+/g, ' ');
147
- if (normalized.length === 0 || seen.has(normalized.toLowerCase()))
148
- continue;
149
- seen.add(normalized.toLowerCase());
150
- result.push(normalized);
151
- }
152
- return result;
153
- }
154
- function uniqueArchitectureReferences(references) {
155
- const seen = new Set();
156
- const result = [];
157
- for (const reference of references) {
158
- if (seen.has(reference.path))
159
- continue;
160
- seen.add(reference.path);
161
- result.push(reference);
162
- }
163
- return result;
164
- }
165
- function templateTitle(target) {
166
- switch (target.templateKind) {
167
- case 'neocortex-md':
168
- return '# NEOCORTEX.md Project Memory';
169
- case 'claude-md':
170
- return '# CLAUDE.md Project Memory';
171
- case 'agents-md':
172
- return '# AGENTS.md Project Instructions';
173
- case 'gemini-md':
174
- return '# GEMINI.md Project Memory';
175
- case 'copilot-instructions':
176
- return '# GitHub Copilot Repository Instructions';
177
- case 'cursor-rule':
178
- return '---\ndescription: Neocortex project memory\nalwaysApply: true\n---\n\n# Cursor Project Memory';
179
- }
180
- }
181
- const DEFAULT_UNIVERSAL_LAWS = [
182
- 'Keep always-loaded memory compact: laws, active context, and references only.',
183
- 'Preserve human-authored instructions outside this owned block.',
184
- 'Prefer repository SSoT docs over duplicating architecture details here.',
185
- ];
186
- const DEFAULT_ARCHITECTURE_HEURISTICS = [
187
- 'Consult `docs/architecture/` before changes that affect architecture, contracts, data, security, performance, UX, or infrastructure.',
188
- 'Reference architecture documents by repository path, such as `docs/architecture/architecture.md`, before changing related implementation.',
189
- 'Summarize decisions and trade-offs in NEOCORTEX.md; do not paste complete architecture documents into memory.',
190
- 'Update memory for durable cross-layer changes across skills/agents, frontend, backend, API, DB, schemas, envs, DevOps, cyber security, testing/QA, observability, product, docs, and platform contracts.',
191
- 'Prioritize compact summaries of durable decisions, public contracts, operational risks, debts, command behavior, and repository paths; skip transient logs, raw payloads, secrets, private prompts, long documents, and duplicated canonical sources.',
192
- 'Keep platform memory files symlink-backed or include-backed to NEOCORTEX.md when supported.',
193
- ];
194
- export const PROJECT_MEMORY_LAYER_CATEGORIES = [
195
- 'skills-agents',
196
- 'frontend',
197
- 'backend',
198
- 'api',
199
- 'db',
200
- 'schemas',
201
- 'envs',
202
- 'devops',
203
- 'cyber-security',
204
- 'testing-qa',
205
- 'observability',
206
- 'product-business',
207
- 'docs-architecture',
208
- 'platform-memory',
209
- 'command-behavior',
210
- 'generic',
211
- ];
212
- const PROJECT_MEMORY_NOTE_BUDGET_BYTES = 360;
213
- const CHANGE_KIND_SECTIONS = {
214
- feature: 'Features',
215
- rule: 'Rules/Policies',
216
- flag: 'Flags',
217
- route: 'Routes',
218
- api: 'APIs/Contracts',
219
- 'db-schema': 'DB/Schema',
220
- architecture: 'Architecture',
221
- debt: 'Debts',
222
- decision: 'Decisions',
223
- generic: 'General Updates',
224
- };
225
- const IP_BOUNDARY_PATTERN = /\b(private|proprietary|server[- ]only|system)\s+prompt\b|\b(api[-_ ]?key|license[-_ ]?key|password|authorization|bearer|token|secret)\s*[:=]|\b(ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[baprs]-[A-Za-z0-9-]+)\b|\b(customer|cliente)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s*[:=]|\braw\s+payload\b/i;
226
- function classifyKind(value) {
227
- const text = value.toLowerCase();
228
- if (/\b(project memory|canonical memory|memory heuristic|neocortex\.md|\*update-memory)\b/.test(text))
229
- return 'decision';
230
- if (/\b(feature|capability|funcionalidade|release)\b/.test(text))
231
- return 'feature';
232
- if (/\b(rule|policy|guardrail|regra|lei|must|never)\b/.test(text))
233
- return 'rule';
234
- if (/\b(flag|feature[- ]?flag|toggle|env var|environment variable)\b/.test(text))
235
- return 'flag';
236
- if (/\b(api|contract|schema contract|graphql|rest|rpc|webhook)\b/.test(text))
237
- return 'api';
238
- if (/\b(db|database|schema|migration|table|column|prisma|sql)\b/.test(text))
239
- return 'db-schema';
240
- if (/\b(decision|decisão|decisao|accepted|rejected|trade[- ]?off)\b/.test(text))
241
- return 'decision';
242
- if (/\b(route|endpoint route|url path|pathname)\b|\/(api|admin|portal|v\d+)\//.test(text))
243
- return 'route';
244
- if (/\b(architecture|arquitetura|adr|topology|infra|boundary)\b/.test(text))
245
- return 'architecture';
246
- if (/\b(debt|follow[- ]?up|todo|tech[- ]?debt|dívida|divida)\b/.test(text))
247
- return 'debt';
248
- return 'generic';
249
- }
250
- function classifyLayer(value) {
251
- const text = value.toLowerCase();
252
- if (/\b(neocortex\.md|project memory|canonical memory|memory wrapper|symlink|owned block|memory heuristic)\b/.test(text))
253
- return 'platform-memory';
254
- if (/\b(command|cli|\*update-memory|\*create-epic|\*arch-plan|workflow behavior)\b/.test(text))
255
- return 'command-behavior';
256
- if (/\b(skill|agent|subagent|orchestrator|opencode|codex|claude|gemini|cursor)\b/.test(text))
257
- return 'skills-agents';
258
- if (/\b(frontend|ui|ux|react|component|design[- ]?system|css|accessibility|a11y)\b/.test(text))
259
- return 'frontend';
260
- if (/\b(backend|server|service|worker|job|queue)\b/.test(text))
261
- return 'backend';
262
- if (/\b(api|endpoint|rest|graphql|rpc|webhook|contract)\b/.test(text))
263
- return 'api';
264
- if (/\b(db|database|table|column|migration|sql|prisma)\b/.test(text))
265
- return 'db';
266
- if (/\b(schema|schemas|zod|json schema|protobuf|openapi)\b/.test(text))
267
- return 'schemas';
268
- if (/\b(env|environment|\.env\.example|config|configuration|feature[- ]?flag)\b/.test(text))
269
- return 'envs';
270
- if (/\b(devops|deploy|deployment|ci|cd|docker|container|kubernetes|infra|terraform|rollback)\b/.test(text))
271
- return 'devops';
272
- if (/\b(security|cyber|auth|authorization|permission|compliance|vulnerability|secret|token redaction)\b/.test(text))
273
- return 'cyber-security';
274
- if (/\b(test|testing|qa|e2e|unit|integration|snapshot|property[- ]?based|flaky)\b/.test(text))
275
- return 'testing-qa';
276
- if (/\b(observability|metric|metrics|log|logging|trace|tracing|alert|monitoring|slo)\b/.test(text))
277
- return 'observability';
278
- if (/\b(product|business|user journey|onboarding|pricing|tenant|customer-facing)\b/.test(text))
279
- return 'product-business';
280
- if (/\b(docs|documentation|architecture|arquitetura|adr|runbook|decision record)\b/.test(text))
281
- return 'docs-architecture';
282
- return 'generic';
283
- }
284
- function compactMemoryNote(value) {
285
- const normalized = value.trim().replace(/\s+/g, ' ');
286
- if (Buffer.byteLength(normalized, 'utf8') <= PROJECT_MEMORY_NOTE_BUDGET_BYTES)
287
- return normalized;
288
- const pathReference = normalized.match(/(?:^|\s)([\w.-]+(?:\/[\w.@-]+)+(?:\.[A-Za-z0-9]+)?)/)?.[1];
289
- const summary = normalized.slice(0, 220).replace(/\s+\S*$/, '').trim();
290
- return pathReference
291
- ? `${summary}… See ${pathReference} for details.`
292
- : `${summary}… Details omitted from always-loaded memory; keep source content in repository docs.`;
293
- }
294
- export function classifyProjectMemoryUpdate(value) {
295
- assertSafeMemoryText(value);
296
- const kind = classifyKind(value);
297
- const layer = classifyLayer(value);
298
- return {
299
- kind,
300
- layer,
301
- sectionTitle: CHANGE_KIND_SECTIONS[kind],
302
- summary: compactMemoryNote(value),
303
- reasonCode: `memory_update_${kind.replace('-', '_')}`,
304
- };
305
- }
306
- function classifyProjectMemoryUpdates(values) {
307
- const seen = new Set();
308
- const result = [];
309
- for (const value of values) {
310
- const classified = classifyProjectMemoryUpdate(value);
311
- const key = `${classified.kind}:${classified.summary.toLowerCase()}`;
312
- if (seen.has(key))
313
- continue;
314
- seen.add(key);
315
- result.push(classified);
316
- }
317
- return result;
318
- }
319
- function assertSafeMemoryText(value) {
320
- if (IP_BOUNDARY_PATTERN.test(value)) {
321
- throw new Error('Project memory input violates IP boundary guardrails.');
322
- }
323
- }
324
- export function createSafeProjectMemoryDiff(before, after) {
325
- const beforeLines = (before ?? '').split('\n');
326
- const afterLines = after.split('\n');
327
- const rows = [];
328
- const max = Math.max(beforeLines.length, afterLines.length);
329
- for (let index = 0; index < max; index++) {
330
- const oldLine = beforeLines[index];
331
- const newLine = afterLines[index];
332
- if (oldLine === newLine)
333
- continue;
334
- if (oldLine !== undefined)
335
- rows.push(`- ${oldLine}`);
336
- if (newLine !== undefined)
337
- rows.push(`+ ${newLine}`);
338
- if (rows.length >= 80) {
339
- rows.push('… diff truncated; inspect repository diff for full context.');
340
- break;
341
- }
342
- }
343
- const diff = rows.join('\n');
344
- assertSafeMemoryText(diff);
345
- return diff;
346
- }
347
- function assertSafeArchitectureReference(reference) {
348
- assertSafeMemoryText(reference.path);
349
- assertSafeMemoryText(reference.title);
350
- assertSafeMemoryText(reference.purpose);
351
- assertSafeMemoryText(reference.suggestedUsage);
352
- }
353
- function assertSafeProjectMemoryInput(memoryNotes, architectureReferences, bootstrapArchitecture) {
354
- memoryNotes.forEach(assertSafeMemoryText);
355
- architectureReferences.forEach(assertSafeArchitectureReference);
356
- bootstrapArchitecture?.universalLaws?.forEach(assertSafeMemoryText);
357
- bootstrapArchitecture?.businessContext?.forEach(assertSafeMemoryText);
358
- bootstrapArchitecture?.activeContext?.forEach(assertSafeMemoryText);
359
- bootstrapArchitecture?.repositoryMap?.forEach(assertSafeMemoryText);
360
- bootstrapArchitecture?.environmentPractices?.forEach(assertSafeMemoryText);
361
- bootstrapArchitecture?.platformMemoryContract?.forEach(assertSafeMemoryText);
362
- bootstrapArchitecture?.maintenanceRules?.forEach(assertSafeMemoryText);
363
- bootstrapArchitecture?.heuristics?.forEach(assertSafeMemoryText);
364
- bootstrapArchitecture?.importantReferences?.forEach(assertSafeArchitectureReference);
365
- bootstrapArchitecture?.architectureReferences?.forEach(assertSafeArchitectureReference);
366
- }
367
- function buildTemplate(target) {
368
- return [
369
- templateTitle(target),
370
- '',
371
- 'This file contains compact, always-loaded project memory. Keep detailed architecture in referenced docs.',
372
- '',
373
- ].join('\n');
374
- }
375
- function buildOwnedBlock(target, memoryNotes, architectureReferences, bootstrapArchitecture) {
376
- assertSafeProjectMemoryInput(memoryNotes, architectureReferences, bootstrapArchitecture);
377
- const laws = uniqueLines([
378
- ...DEFAULT_UNIVERSAL_LAWS,
379
- ...(bootstrapArchitecture?.universalLaws ?? []),
380
- ]);
381
- const notes = uniqueLines([
382
- ...(bootstrapArchitecture?.activeContext ?? []),
383
- ...memoryNotes.map(compactMemoryNote),
384
- ]);
385
- const classifiedUpdates = classifyProjectMemoryUpdates(memoryNotes);
386
- const businessContext = uniqueLines(bootstrapArchitecture?.businessContext ?? [
387
- 'Product/business context was not explicitly documented during bootstrap; treat conclusions as repository-inferred until a human updates this section.',
388
- ]);
389
- const repositoryMap = uniqueLines(bootstrapArchitecture?.repositoryMap ?? [
390
- 'Source, tests, package/build files, docs, CI, and runtime manifests are the permitted bootstrap sources for repository orientation.',
391
- ]);
392
- const environmentPractices = uniqueLines(bootstrapArchitecture?.environmentPractices ?? [
393
- 'Use `.env.example` for configuration shape only; do not read real environment files or credential-bearing files into always-loaded memory.',
394
- ]);
395
- const platformMemoryContract = uniqueLines(bootstrapArchitecture?.platformMemoryContract ?? [
396
- 'Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.',
397
- 'Platform wrapper/frontmatter must be preserved via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md.',
398
- ]);
399
- const maintenanceRules = uniqueLines(bootstrapArchitecture?.maintenanceRules ?? [
400
- 'Keep NEOCORTEX.md deterministic, compact, objective, and direct; store only summaries, indexes, and links to detailed docs.',
401
- 'Do not copy protected prompt bodies, proprietary wrappers, server-side internals, customer data, license keys, or long document bodies into always-loaded memory.',
402
- ]);
403
- const references = uniqueArchitectureReferences([
404
- ...(bootstrapArchitecture?.importantReferences ?? []),
405
- ...(bootstrapArchitecture?.architectureReferences ?? []),
406
- ...architectureReferences,
407
- ]);
408
- const heuristics = uniqueLines([
409
- ...DEFAULT_ARCHITECTURE_HEURISTICS,
410
- ...(bootstrapArchitecture?.heuristics ?? []),
411
- ]);
412
- const lawRows = laws.map((law) => `- ${law}`);
413
- const noteRows = notes.length > 0
414
- ? notes.map((note) => `- ${note}`)
415
- : ['- No active project notes recorded.'];
416
- const referenceSection = references.length > 0
417
- ? renderArchitectureReferenceTable(references)
418
- : 'No architecture references discovered.';
419
- const feedbackRows = classifiedUpdates.length > 0
420
- ? Object.entries(CHANGE_KIND_SECTIONS)
421
- .flatMap(([kind, sectionTitle]) => {
422
- const updates = classifiedUpdates.filter((entry) => entry.kind === kind);
423
- return updates.length > 0
424
- ? [`### ${sectionTitle}`, ...updates.map((entry) => `- [${entry.reasonCode}] ${entry.summary} (layer: ${entry.layer})`)]
425
- : [];
426
- })
427
- : ['- No durable change feedback recorded.'];
428
- return [
429
- markerStart(target),
430
- '## Universal Project Laws',
431
- ...lawRows,
432
- '',
433
- '## Business/Product Context',
434
- ...businessContext.map((line) => `- ${line}`),
435
- '',
436
- '## Active Context',
437
- ...noteRows,
438
- '',
439
- '## Durable Change Feedback',
440
- ...feedbackRows,
441
- '',
442
- '## Architecture References',
443
- referenceSection,
444
- '',
445
- '## Repository Map',
446
- ...repositoryMap.map((line) => `- ${line}`),
447
- '',
448
- '## Environment/Container/Production/Security/Dev Practices',
449
- ...environmentPractices.map((line) => `- ${line}`),
450
- '',
451
- '## Platform Memory Contract',
452
- ...platformMemoryContract.map((line) => `- ${line}`),
453
- `- NEOCORTEX.md is the canonical project memory source for every platform target; run \`${target.bidirectionalReference.feedbackTrigger}\` when durable context discovered in a platform wrapper should be fed back into canonical memory.`,
454
- '',
455
- '## Maintenance Rules',
456
- ...maintenanceRules.map((line) => `- ${line}`),
457
- '',
458
- '## Architecture Heuristics',
459
- ...heuristics.map((heuristic) => `- ${heuristic}`),
460
- markerEnd(target),
461
- ].join('\n');
462
- }
463
- const BOOTSTRAP_ARCHITECTURE_ROOTS = ['docs/architecture', 'docs/arquitetura-software'];
464
- const BOOTSTRAP_FALLBACK_DOCS = ['README.md', 'readme.md', 'architecture.md', 'docs/architecture.md'];
465
- const BOOTSTRAP_PACKAGE_FILES = ['package.json', 'pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'tsconfig.json', 'vite.config.ts', 'turbo.json'];
466
- const BOOTSTRAP_RUNTIME_FILES = ['Dockerfile', 'docker-compose.yml', 'compose.yml', '.env.example', 'fly.toml'];
467
- const BOOTSTRAP_PLATFORM_FILES = ['AGENTS.md', 'CLAUDE.md', 'GEMINI.md', '.opencode/AGENTS.md', '.cursor/rules/neocortex.mdc'];
468
- function readOptional(projectRoot, relativePath, maxBytes = 24_000) {
469
- const fullPath = join(projectRoot, relativePath);
470
- try {
471
- if (!existsSync(fullPath) || lstatSync(fullPath).isDirectory())
472
- return undefined;
473
- const content = readFileSync(fullPath, 'utf8');
474
- return content.length <= maxBytes ? content : content.slice(0, maxBytes);
475
- }
476
- catch {
477
- return undefined;
478
- }
479
- }
480
- function memoryBackupPath(path, nonce, backupDirectory) {
481
- if (!backupDirectory)
482
- return `${path}.bak-${nonce}`;
483
- const directory = resolve(backupDirectory), info = lstatSync(directory);
484
- if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== process.getuid?.()
485
- || (info.mode & 0o077) !== 0 || realpathSync(directory) !== directory)
486
- throw new Error('project-memory-backup-directory-unsafe');
487
- return join(directory, `${basename(path)}.bak-${nonce}`);
488
- }
489
- function writeFileWithBackup(path, content, backupDirectory) {
490
- mkdirSync(dirname(path), { recursive: true });
491
- const nonce = randomUUID();
492
- const tempPath = `${path}.tmp-${nonce}`;
493
- const backupPath = existsSync(path) ? memoryBackupPath(path, nonce, backupDirectory) : undefined;
494
- try {
495
- writeFileSync(tempPath, content, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
496
- if (backupPath !== undefined)
497
- copyFileSync(path, backupPath, fsConstants.COPYFILE_EXCL);
498
- renameSync(tempPath, path);
499
- return backupPath;
500
- }
501
- catch (error) {
502
- rmSync(tempPath, { force: true });
503
- if (backupPath !== undefined && existsSync(backupPath)) {
504
- try {
505
- copyFileSync(backupPath, path);
506
- }
507
- catch { /* best-effort rollback */ }
508
- }
509
- throw error;
510
- }
511
- }
512
- function reasonCodesForNotes(memoryNotes) {
513
- return Array.from(new Set(classifyProjectMemoryUpdates(memoryNotes).map((entry) => entry.reasonCode)));
514
- }
515
- function safeExists(projectRoot, relativePath) {
516
- try {
517
- return existsSync(join(projectRoot, relativePath));
518
- }
519
- catch {
520
- return false;
521
- }
522
- }
523
- function listSourceChildren(projectRoot, relativePath) {
524
- try {
525
- return readdirSync(join(projectRoot, relativePath), { withFileTypes: true })
526
- .filter((entry) => !entry.name.startsWith('.') && !entry.name.toLowerCase().includes('secret'))
527
- .sort((a, b) => a.name.localeCompare(b.name))
528
- .slice(0, 8)
529
- .map((entry) => `${relativePath}/${entry.name}${entry.isDirectory() ? '/' : ''}`);
530
- }
531
- catch {
532
- return [];
533
- }
534
- }
535
- function collectMarkdownDocs(projectRoot, relativeDir, limit = 16) {
536
- try {
537
- const entries = readdirSync(join(projectRoot, relativeDir), { withFileTypes: true })
538
- .filter((entry) => !entry.name.startsWith('.') && !entry.name.startsWith('_'))
539
- .sort((a, b) => a.name.localeCompare(b.name));
540
- const files = [];
541
- for (const entry of entries) {
542
- const relativeEntry = `${relativeDir}/${entry.name}`;
543
- if (entry.isDirectory()) {
544
- files.push(...collectMarkdownDocs(projectRoot, relativeEntry, limit - files.length));
545
- }
546
- else if (/\.(md|markdown)$/i.test(entry.name)) {
547
- files.push(relativeEntry);
548
- }
549
- if (files.length >= limit)
550
- break;
551
- }
552
- return files;
553
- }
554
- catch {
555
- return [];
556
- }
557
- }
558
- function extractBootstrapTitle(path, content) {
559
- const heading = content.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim();
560
- if (heading)
561
- return heading.replace(/[`*_#]/g, '');
562
- return path.split('/').pop()?.replace(/\.(md|markdown)$/i, '').replace(/[-_]+/g, ' ') ?? path;
563
- }
564
- function referencePurpose(path, content) {
565
- const stale = /\b(stale|deprecated|outdated|incerto|uncertain)\b/i.test(`${path}\n${content.slice(0, 2_000)}`);
566
- const firstParagraph = content
567
- .replace(/^---[\s\S]*?---\s*/, '')
568
- .split(/\n{2,}/)
569
- .map((part) => part.replace(/^#+\s+.+$/gm, '').replace(/[`*_>#]/g, '').replace(/\s+/g, ' ').trim())
570
- .find((part) => part.length > 0 && !part.startsWith('|'));
571
- const prefix = stale ? '[stale/uncertain evidence] ' : '';
572
- return `${prefix}${(firstParagraph ?? 'Architecture reference for this project.').slice(0, 180)}`;
573
- }
574
- function bootstrapSuggestedUsage(path) {
575
- const lower = path.toLowerCase();
576
- if (/deploy|infra|docker|production|runbook/.test(lower))
577
- return 'Use before changing deployment, runtime, containers, or production operations.';
578
- if (/security|auth|compliance/.test(lower))
579
- return 'Use before changing auth, compliance, or security-sensitive behavior.';
580
- if (/api|contract|state|schema/.test(lower))
581
- return 'Use before changing contracts, APIs, schemas, or persisted state.';
582
- return 'Use before implementation in this area; verify freshness when marked stale or uncertain.';
583
- }
584
- export function bootstrapArchitectureMemory(projectRoot) {
585
- const packageFiles = BOOTSTRAP_PACKAGE_FILES.filter((path) => safeExists(projectRoot, path));
586
- const runtimeFiles = BOOTSTRAP_RUNTIME_FILES.filter((path) => safeExists(projectRoot, path));
587
- const platformFiles = BOOTSTRAP_PLATFORM_FILES.filter((path) => safeExists(projectRoot, path));
588
- const sourceRoots = ['packages', 'src', 'apps', 'tests', '__tests__']
589
- .filter((path) => safeExists(projectRoot, path));
590
- const docs = [
591
- ...BOOTSTRAP_ARCHITECTURE_ROOTS.flatMap((root) => collectMarkdownDocs(projectRoot, root)),
592
- ...BOOTSTRAP_FALLBACK_DOCS.filter((path) => safeExists(projectRoot, path)),
593
- ];
594
- const references = docs.slice(0, 24).flatMap((path) => {
595
- const content = readOptional(projectRoot, path, 48_000);
596
- if (!content)
597
- return [];
598
- return [{
599
- path,
600
- title: extractBootstrapTitle(path, content),
601
- purpose: referencePurpose(path, content),
602
- suggestedUsage: bootstrapSuggestedUsage(path),
603
- source: BOOTSTRAP_ARCHITECTURE_ROOTS.some((root) => path.startsWith(`${root}/`)) ? 'architecture-root' : 'fallback-file',
604
- }];
605
- });
606
- const packageJson = readOptional(projectRoot, 'package.json');
607
- const packageName = packageJson?.match(/"name"\s*:\s*"([^"]+)"/)?.[1];
608
- const scripts = [...(packageJson?.matchAll(/"(test|build|lint|typecheck|dev)"\s*:/g) ?? [])].map((match) => match[1]);
609
- return {
610
- universalLaws: [
611
- 'Bootstrap canonical memory before creating or repairing platform memory wrappers when NEOCORTEX.md is absent.',
612
- 'Use only permitted repository sources for bootstrap: package/build files, architecture docs, README/deploy docs, .env.example, runtime manifests, CI, source/test layout, and platform memory wrappers.',
613
- ],
614
- businessContext: [
615
- packageName ? `Repository package name: ${packageName}.` : 'Repository product name was not declared in package metadata.',
616
- 'Business/product conclusions are bootstrap-inferred and must be refined from canonical docs or human input.',
617
- ],
618
- activeContext: [
619
- `Bootstrap scanned ${packageFiles.length} package/build files, ${references.length} architecture/readme docs, ${runtimeFiles.length} runtime/config templates, and ${platformFiles.length} platform memory wrappers.`,
620
- scripts.length > 0 ? `Detected quality scripts: ${scripts.sort().join(', ')}.` : 'No standard quality scripts were detected in package metadata.',
621
- ],
622
- repositoryMap: [
623
- packageFiles.length > 0 ? `Package/build files: ${packageFiles.join(', ')}.` : 'No package/build files detected in permitted bootstrap set.',
624
- sourceRoots.length > 0 ? `Source/test roots: ${sourceRoots.flatMap((root) => listSourceChildren(projectRoot, root)).slice(0, 16).join(', ')}.` : 'Source/test roots were not detected in standard locations.',
625
- platformFiles.length > 0 ? `Platform memory/wrappers: ${platformFiles.join(', ')}.` : 'No platform memory wrappers detected before bootstrap.',
626
- ],
627
- environmentPractices: [
628
- runtimeFiles.length > 0 ? `Runtime/config templates: ${runtimeFiles.join(', ')}.` : 'No Docker/compose/.env.example/runtime manifest detected in permitted bootstrap set.',
629
- 'Read `.env.example` only for configuration shape; never ingest real .env files, credentials, customer data, or license keys into memory.',
630
- 'Run repository quality scripts before commit and keep CI/deploy evidence referenced by path or URL rather than copied verbatim.',
631
- ],
632
- platformMemoryContract: [
633
- 'Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.',
634
- 'Preserve wrappers/frontmatter via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md.',
635
- ],
636
- maintenanceRules: [
637
- 'Generated memory must be deterministic, objective, direct, compact, and inside the target always-loaded context budget.',
638
- 'Cite long architecture docs by path with usage guidance; mark stale or uncertain docs when repository evidence indicates that status.',
639
- 'Do not copy protected prompt bodies, proprietary wrappers, server internals, secrets, customer data, license keys, or complete long documents.',
640
- ],
641
- architectureReferences: references,
642
- heuristics: [
643
- 'Before processing a story, consult the cited Architecture References whose path or suggested usage intersects the change.',
644
- 'When a referenced doc is marked stale/uncertain, validate against current package/runtime/source evidence before relying on it.',
645
- ],
646
- };
647
- }
648
- function replaceOwnedBlock(existingContent, target, ownedBlock) {
649
- const start = markerStart(target);
650
- const end = markerEnd(target);
651
- const startIndex = existingContent.indexOf(start);
652
- const endIndex = existingContent.indexOf(end);
653
- if (startIndex >= 0 && endIndex >= startIndex) {
654
- const afterEnd = endIndex + end.length;
655
- return `${existingContent.slice(0, startIndex)}${ownedBlock}${existingContent.slice(afterEnd)}`;
656
- }
657
- const separator = existingContent.endsWith('\n') ? '\n' : '\n\n';
658
- return `${existingContent}${separator}${ownedBlock}\n`;
659
- }
660
- function frontmatterForWrapper(relativeFile) {
661
- if (relativeFile.endsWith('.mdc')) {
662
- return '---\ndescription: Neocortex project memory\nalwaysApply: true\n---\n\n';
663
- }
664
- if (relativeFile.endsWith('.toml')) {
665
- return '[agent]\nname = "neocortex"\ndescription = "Neocortex project memory wrapper"\n\n';
666
- }
667
- if (relativeFile.endsWith('.agent.md')) {
668
- return '---\nname: neocortex\ndescription: Neocortex project memory wrapper\n---\n\n';
669
- }
670
- return '';
671
- }
672
- function relativeCanonicalLink(projectRoot, relativeFile) {
673
- const fromDir = dirname(join(projectRoot, relativeFile));
674
- const toFile = join(projectRoot, CANONICAL_PROJECT_MEMORY_SOURCE);
675
- const target = relative(fromDir, toFile);
676
- return target.length > 0 ? target : CANONICAL_PROJECT_MEMORY_SOURCE;
677
- }
678
- export function shouldUseManagedWrapper(target, relativeFile) {
679
- if (target.targetId === 'canonical')
680
- return true;
681
- if (target.requiresWrapperPreservation || target.linkRequirement.requiresWrapperPreservation)
682
- return true;
683
- if (target.linkRequirement.wrapperAllowed)
684
- return true;
685
- if (relativeFile === 'AGENTS.md')
686
- return true;
687
- if (relativeFile.includes('/agents/') || relativeFile.includes('/skills/'))
688
- return true;
689
- if (relativeFile.endsWith('.toml') || relativeFile.endsWith('.mdc'))
690
- return true;
691
- if (relativeFile.endsWith('.agent.md') || relativeFile.endsWith('.instructions.md'))
692
- return true;
693
- return false;
694
- }
695
- function isPolicySymlinkCapable(target) {
696
- return target.linkRequirement.symlinkBacked && target.linkRequirement.semanticFileRequired;
697
- }
698
- function safeSymlinkFailureReason(reason) {
699
- if (/EPERM|EACCES|operation not permitted|permission/i.test(reason))
700
- return 'EPERM: symlink permission denied';
701
- if (/ENOSYS|ENOTSUP|EOPNOTSUPP|not supported/i.test(reason))
702
- return 'symlink filesystem unsupported';
703
- return 'symlink capability unavailable';
704
- }
705
- function detectSymlinkCapability(projectRoot, target, relativeFile, override, dryRun = false) {
706
- if (override !== undefined)
707
- return override;
708
- const targetPolicyAllowsSymlink = isPolicySymlinkCapable(target);
709
- if (!targetPolicyAllowsSymlink) {
710
- return {
711
- os: platform(),
712
- supported: false,
713
- permission: 'unknown',
714
- filesystem: 'unknown',
715
- targetPolicy: target.linkRequirement.policy,
716
- targetPolicyAllowsSymlink,
717
- requiresWrapperPreservation: shouldUseManagedWrapper(target, relativeFile),
718
- reason: `target policy ${target.linkRequirement.policy} does not allow semantic symlink orchestration`,
719
- };
720
- }
721
- if (dryRun) {
722
- return {
723
- os: platform(),
724
- supported: true,
725
- permission: 'unknown',
726
- filesystem: 'unknown',
727
- targetPolicy: target.linkRequirement.policy,
728
- targetPolicyAllowsSymlink,
729
- requiresWrapperPreservation: shouldUseManagedWrapper(target, relativeFile),
730
- reason: 'dry-run does not probe filesystem symlink support',
731
- };
732
- }
733
- const probeDir = join(projectRoot, '.neocortex', 'tmp');
734
- const nonce = randomUUID();
735
- const probeSource = join(probeDir, `symlink-capability-source-${nonce}`);
736
- const probeLink = join(probeDir, `symlink-capability-link-${nonce}`);
737
- try {
738
- mkdirSync(probeDir, { recursive: true });
739
- writeFileSync(probeSource, 'probe', { encoding: 'utf8', flag: 'wx', mode: 0o600 });
740
- symlinkSync(probeSource, probeLink);
741
- const supported = lstatSync(probeLink).isSymbolicLink() && statSync(probeLink).isFile();
742
- return {
743
- os: platform(),
744
- supported,
745
- permission: supported ? 'ok' : 'unknown',
746
- filesystem: supported ? 'supports-symlink' : 'no-symlink-support',
747
- targetPolicy: target.linkRequirement.policy,
748
- targetPolicyAllowsSymlink,
749
- requiresWrapperPreservation: shouldUseManagedWrapper(target, relativeFile),
750
- reason: supported ? undefined : 'filesystem probe did not create a resolvable symbolic link',
751
- };
752
- }
753
- catch (error) {
754
- const message = error instanceof Error ? error.message : String(error);
755
- const denied = /EPERM|EACCES|operation not permitted|permission/i.test(message);
756
- return {
757
- os: platform(),
758
- supported: false,
759
- permission: denied ? 'denied' : 'unknown',
760
- filesystem: 'no-symlink-support',
761
- targetPolicy: target.linkRequirement.policy,
762
- targetPolicyAllowsSymlink,
763
- requiresWrapperPreservation: shouldUseManagedWrapper(target, relativeFile),
764
- reason: safeSymlinkFailureReason(message),
765
- };
766
- }
767
- finally {
768
- rmSync(probeLink, { force: true });
769
- rmSync(probeSource, { force: true });
770
- }
771
- }
772
- function buildManagedWrapperContent(target, relativeFile, existingContent, projectRoot) {
773
- const canonicalLink = relativeCanonicalLink(projectRoot, relativeFile);
774
- const baseContent = existingContent ?? `${frontmatterForWrapper(relativeFile)}# ${target.platformName} Neocortex Memory Wrapper\n\n`;
775
- const ownedBlock = [
776
- markerStart(target),
777
- '## Canonical Project Memory Source',
778
- '',
779
- `This platform wrapper preserves host-specific frontmatter/instructions while resolving project memory to \`${canonicalLink}\`.`,
780
- '',
781
- `- Canonical source: \`${CANONICAL_PROJECT_MEMORY_SOURCE}\``,
782
- `- Symlink-backed/source-of-truth file: \`${canonicalLink}\``,
783
- `- Feedback loop: read \`${canonicalLink}\` for shared context and run \`${target.bidirectionalReference.feedbackTrigger}\` when durable platform findings should update \`${CANONICAL_PROJECT_MEMORY_SOURCE}\`.`,
784
- '- Human-authored content outside this managed block is preserved byte-for-byte.',
785
- markerEnd(target),
786
- ].join('\n');
787
- return replaceOwnedBlock(baseContent, target, ownedBlock);
788
- }
789
- function writeCompatibilityFallback(projectRoot, relativeFile, canonicalContent, capability, fallbackReason, dryRun = false) {
790
- const filePath = join(projectRoot, relativeFile);
791
- const publicFallbackReason = safeSymlinkFailureReason(fallbackReason);
792
- const remediationDebt = [
793
- '[NEOCORTEX COMPATIBILITY REMEDIATION]',
794
- 'Materialized project memory fallback because semantic symlink orchestration failed.',
795
- 'This is not product mode; repair host permissions/filesystem support and restore the symlink to NEOCORTEX.md.',
796
- 'WARNING: materialized fallback is remediation debt, not a silent mode; run *update-memory for durable context and repair this file back to canonical NEOCORTEX.md resolution.',
797
- `Fallback reason: ${publicFallbackReason}`,
798
- '',
799
- ].join('\n');
800
- const content = `${remediationDebt}${canonicalContent}`;
801
- const existingContent = existsSync(filePath) ? readFileSync(filePath, 'utf8') : undefined;
802
- const changed = existingContent !== content;
803
- if (changed && !dryRun) {
804
- if (existsSync(filePath) && lstatSync(filePath).isSymbolicLink())
805
- unlinkSync(filePath);
806
- writeFileWithBackup(filePath, content);
807
- }
808
- return {
809
- filePath,
810
- relativeFile,
811
- changed,
812
- content,
813
- mode: 'compatibility-materialized-fallback',
814
- canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
815
- symlinkCapability: capability,
816
- fallbackReason: publicFallbackReason,
817
- remediationDebt: `Repair ${relativeFile} so it is a symlink to ${CANONICAL_PROJECT_MEMORY_SOURCE}; fallback is compatibility remediation only.`,
818
- };
819
- }
820
- function writeSemanticSymlink(projectRoot, relativeFile, target, canonicalContent, symlinkCapability, dryRun = false) {
821
- const filePath = join(projectRoot, relativeFile);
822
- const linkTarget = relativeCanonicalLink(projectRoot, relativeFile);
823
- if (!dryRun)
824
- mkdirSync(dirname(filePath), { recursive: true });
825
- const capability = detectSymlinkCapability(projectRoot, target, relativeFile, symlinkCapability, dryRun);
826
- if (!capability.supported) {
827
- return writeCompatibilityFallback(projectRoot, relativeFile, canonicalContent, capability, capability.reason ?? 'symlink capability detection reported unsupported host', dryRun);
828
- }
829
- if (dryRun) {
830
- let changed = true;
831
- try {
832
- changed = !(existsSync(filePath) && lstatSync(filePath).isSymbolicLink() && readlinkSync(filePath) === linkTarget);
833
- }
834
- catch {
835
- changed = true;
836
- }
837
- return {
838
- filePath,
839
- relativeFile,
840
- changed,
841
- content: canonicalContent,
842
- mode: 'semantic-symlink',
843
- canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
844
- symlinkCapability: capability,
845
- };
846
- }
847
- let changed = false;
848
- try {
849
- if (existsSync(filePath)) {
850
- const stat = lstatSync(filePath);
851
- if (stat.isSymbolicLink() && readlinkSync(filePath) === linkTarget) {
852
- changed = false;
853
- }
854
- else {
855
- unlinkSync(filePath);
856
- symlinkSync(linkTarget, filePath);
857
- changed = true;
858
- }
859
- }
860
- else {
861
- symlinkSync(linkTarget, filePath);
862
- changed = true;
863
- }
864
- return {
865
- filePath,
866
- relativeFile,
867
- changed,
868
- content: readFileSync(filePath, 'utf8'),
869
- mode: 'semantic-symlink',
870
- canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
871
- symlinkCapability: capability,
872
- };
873
- }
874
- catch (error) {
875
- const reason = error instanceof Error ? error.message : String(error);
876
- const publicReason = safeSymlinkFailureReason(reason);
877
- return writeCompatibilityFallback(projectRoot, relativeFile, canonicalContent, {
878
- ...capability,
879
- supported: false,
880
- permission: /EPERM|EACCES|operation not permitted|permission/i.test(reason) ? 'denied' : capability.permission,
881
- filesystem: 'no-symlink-support',
882
- reason: publicReason,
883
- }, publicReason, dryRun);
884
- }
885
- }
886
- function enforceBudget(target, content, memoryNotes, architectureReferences, bootstrapArchitecture) {
887
- const fits = (value) => value.split('\n').length <= target.budget.maxLines &&
888
- Buffer.byteLength(value, 'utf8') <= target.budget.maxBytes;
889
- if (fits(content))
890
- return content;
891
- const compactBlock = buildOwnedBlock(target, memoryNotes.slice(0, 8), architectureReferences.slice(0, 12), bootstrapArchitecture);
892
- const compactContent = replaceOwnedBlock(content.includes(markerStart(target)) ? content : buildTemplate(target), target, compactBlock);
893
- return fits(compactContent) ? compactContent : compactContent.slice(0, target.budget.maxBytes);
894
- }
895
- export function buildProjectMemoryContent(target, existingContent, memoryNotes = [], architectureReferences = [], bootstrapArchitecture) {
896
- const baseContent = existingContent ?? buildTemplate(target);
897
- const ownedBlock = buildOwnedBlock(target, memoryNotes, architectureReferences, bootstrapArchitecture);
898
- const content = replaceOwnedBlock(baseContent, target, ownedBlock);
899
- return enforceBudget(target, content, memoryNotes, architectureReferences, bootstrapArchitecture);
900
- }
901
- export function writeProjectMemory(options) {
902
- const target = getProjectMemoryTarget(options.targetId);
903
- const fs = options.fs ?? createNodeProjectMemoryFs(options.backupDirectory);
904
- const filePath = fs.join(options.projectRoot, target.primaryFile);
905
- if (options.fs === undefined && target.targetId === 'canonical') {
906
- assertProjectMemoryPaths(options.projectRoot, [CANONICAL_PROJECT_MEMORY_SOURCE]);
907
- }
908
- if (target.targetId !== 'canonical' && options.fs === undefined) {
909
- const result = writeProjectMemoryTargetFiles(options).files.find((file) => file.relativeFile === target.primaryFile);
910
- if (result === undefined)
911
- throw new Error(`Primary project memory file was not written for ${target.targetId}.`);
912
- return { filePath: result.filePath, changed: result.changed, content: result.content };
913
- }
914
- const existingContent = fs.readFile(filePath);
915
- const bootstrapArchitecture = options.bootstrapArchitecture ?? (options.fs === undefined && target.targetId === 'canonical' && existingContent === undefined
916
- ? bootstrapArchitectureMemory(options.projectRoot)
917
- : undefined);
918
- const content = target.targetId === 'canonical' && existingContent !== undefined
919
- ? (hasCanonicalUpdateInput(options) ? mergeCanonicalRefreshUpdate(target, existingContent, options) : existingContent)
920
- : buildProjectMemoryContent(target, existingContent, options.memoryNotes, options.architectureReferences, bootstrapArchitecture);
921
- if (existingContent === content) {
922
- return { filePath, changed: false, content };
923
- }
924
- const writeResult = options.dryRun ? undefined : fs.writeFileAtomic(filePath, content);
925
- return {
926
- filePath,
927
- changed: true,
928
- content,
929
- safeDiff: createSafeProjectMemoryDiff(existingContent, content),
930
- backupPath: writeResult?.backupPath,
931
- reasonCodes: reasonCodesForNotes(options.memoryNotes ?? []),
932
- };
933
- }
934
- export function writeCanonicalProjectMemory(options) {
935
- return writeProjectMemory({ ...options, targetId: 'canonical' });
936
- }
937
- // Earlier releases wrote memory wrappers into agent discovery paths, where a
938
- // frontmatter-less `neocortex.md` shadows the real subagent (Claude Code) or
939
- // collides with the installed native subagent (Gemini CLI/Antigravity).
940
- const LEGACY_AGENT_PATH_WRAPPERS = {
941
- 'claude-code': ['.claude/agents/neocortex.md'],
942
- 'gemini-cli': ['.gemini/agents/neocortex.md'],
943
- antigravity: ['.gemini/agents/neocortex.md'],
944
- };
945
- const LEGACY_WRAPPER_HEADER = /^# [^\n]* Neocortex Memory Wrapper\s*$/;
946
- /**
947
- * True only when Git positively reports the path as tracked in the index.
948
- * Git unavailable, not a repository, or any error is treated as untracked.
949
- * Ambient GIT_* variables are stripped so hooks cannot redirect the lookup.
950
- */
951
- function isGitTrackedPath(projectRoot, relativeFile) {
952
- try {
953
- execFileSync('git', [
954
- '-c', 'core.fsmonitor=false',
955
- 'ls-files', '--error-unmatch', '--', relativeFile,
956
- ], {
957
- cwd: projectRoot,
958
- stdio: ['ignore', 'ignore', 'ignore'],
959
- env: {
960
- ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_'))),
961
- GIT_TERMINAL_PROMPT: '0',
962
- GIT_OPTIONAL_LOCKS: '0',
963
- },
964
- timeout: 10_000,
965
- windowsHide: true,
966
- });
967
- return true;
968
- }
969
- catch {
970
- return false;
971
- }
972
- }
973
- function retireLegacyAgentPathWrappers(projectRoot, target, dryRun, backupDirectory) {
974
- const results = [];
975
- const retiredStatus = dryRun ? 'would-retire' : 'retired';
976
- const trackedBlocked = (relativeFile) => ({
977
- relativeFile,
978
- status: 'tracked-blocked',
979
- reasonCode: LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON,
980
- remediation: `git rm ${relativeFile}`,
981
- });
982
- for (const relativeFile of LEGACY_AGENT_PATH_WRAPPERS[target.targetId] ?? []) {
983
- assertProjectMemoryPaths(projectRoot, [relativeFile]);
984
- const filePath = join(projectRoot, relativeFile);
985
- let stats;
986
- try {
987
- stats = lstatSync(filePath);
988
- }
989
- catch {
990
- continue;
991
- }
992
- if (stats.isSymbolicLink()) {
993
- let pointsToCanonical = false;
994
- try {
995
- pointsToCanonical = realpathSync(filePath) === realpathSync(join(projectRoot, CANONICAL_PROJECT_MEMORY_SOURCE));
996
- }
997
- catch {
998
- pointsToCanonical = false;
999
- }
1000
- if (pointsToCanonical) {
1001
- // A tracked wrapper is repository content: never delete it behind Git's back.
1002
- if (isGitTrackedPath(projectRoot, relativeFile)) {
1003
- results.push(trackedBlocked(relativeFile));
1004
- continue;
1005
- }
1006
- if (!dryRun)
1007
- unlinkSync(filePath);
1008
- results.push({ relativeFile, status: retiredStatus });
1009
- }
1010
- continue;
1011
- }
1012
- if (!stats.isFile())
1013
- continue;
1014
- const content = readFileSync(filePath, 'utf8');
1015
- const start = content.indexOf(markerStart(target));
1016
- const end = content.indexOf(markerEnd(target));
1017
- if (start < 0 || end < start)
1018
- continue;
1019
- if (isGitTrackedPath(projectRoot, relativeFile)) {
1020
- results.push(trackedBlocked(relativeFile));
1021
- continue;
1022
- }
1023
- const remainder = content.slice(0, start) + content.slice(end + markerEnd(target).length);
1024
- const trimmed = remainder.trim();
1025
- if (trimmed.length === 0 || LEGACY_WRAPPER_HEADER.test(trimmed)) {
1026
- if (!dryRun)
1027
- rmSync(filePath, { force: true });
1028
- }
1029
- else {
1030
- // Real agent content with an appended wrapper block: keep the agent.
1031
- if (!dryRun)
1032
- writeFileWithBackup(filePath, `${remainder.replace(/\s+$/, '')}\n`, backupDirectory);
1033
- }
1034
- results.push({ relativeFile, status: retiredStatus });
1035
- }
1036
- return results;
1037
- }
1038
- export function writeProjectMemoryTargetFiles(options) {
1039
- if (options.fs !== undefined) {
1040
- throw new Error('writeProjectMemoryTargetFiles requires the node filesystem to manage symlinks safely.');
1041
- }
1042
- const target = getProjectMemoryTarget(options.targetId);
1043
- const canonicalTarget = getProjectMemoryTarget('canonical');
1044
- if (target.secondaryFiles.some((file) => file === null || (file.scope !== 'project' && file.scope !== 'user') || !isValidScopedRelativePath(file.path))) {
1045
- invalidProjectMemoryPath('invalid');
1046
- }
1047
- const relativeFiles = Array.from(new Set([
1048
- target.primaryFile,
1049
- ...(target.targetId === 'canonical' ? [] : target.secondaryFiles.filter((file) => file.scope === 'project').map((file) => file.path)),
1050
- ]));
1051
- assertProjectMemoryPaths(options.projectRoot, [CANONICAL_PROJECT_MEMORY_SOURCE, ...relativeFiles, '.neocortex/tmp']);
1052
- const canonicalFilePath = join(options.projectRoot, CANONICAL_PROJECT_MEMORY_SOURCE);
1053
- const existingCanonicalContent = existsSync(canonicalFilePath) ? readFileSync(canonicalFilePath, 'utf8') : undefined;
1054
- const bootstrapArchitecture = options.bootstrapArchitecture ?? (existingCanonicalContent === undefined ? bootstrapArchitectureMemory(options.projectRoot) : undefined);
1055
- const canonicalContent = existingCanonicalContent !== undefined
1056
- ? (hasCanonicalUpdateInput(options) ? mergeCanonicalRefreshUpdate(canonicalTarget, existingCanonicalContent, options) : existingCanonicalContent)
1057
- : buildProjectMemoryContent(canonicalTarget, existingCanonicalContent, options.memoryNotes, options.architectureReferences, bootstrapArchitecture);
1058
- const canonicalChanged = !existsSync(canonicalFilePath) || readFileSync(canonicalFilePath, 'utf8') !== canonicalContent;
1059
- let canonicalBackupPath;
1060
- if (canonicalChanged && !options.dryRun) {
1061
- canonicalBackupPath = writeFileWithBackup(canonicalFilePath, canonicalContent, options.backupDirectory);
1062
- }
1063
- if (target.targetId === 'canonical') {
1064
- return {
1065
- targetId: target.targetId,
1066
- canonicalFilePath,
1067
- changed: canonicalChanged,
1068
- files: [{
1069
- filePath: canonicalFilePath,
1070
- relativeFile: CANONICAL_PROJECT_MEMORY_SOURCE,
1071
- changed: canonicalChanged,
1072
- content: canonicalContent,
1073
- mode: 'canonical',
1074
- canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
1075
- safeDiff: createSafeProjectMemoryDiff(existingCanonicalContent, canonicalContent),
1076
- backupPath: canonicalBackupPath,
1077
- reasonCodes: reasonCodesForNotes(options.memoryNotes ?? []),
1078
- }],
1079
- };
1080
- }
1081
- const files = relativeFiles.map((relativeFile) => {
1082
- assertProjectMemoryPaths(options.projectRoot, [relativeFile, '.neocortex/tmp']);
1083
- if (!shouldUseManagedWrapper(target, relativeFile)) {
1084
- return writeSemanticSymlink(options.projectRoot, relativeFile, target, canonicalContent, options.symlinkCapability, options.dryRun);
1085
- }
1086
- const filePath = join(options.projectRoot, relativeFile);
1087
- const existingContent = existsSync(filePath) ? readFileSync(filePath, 'utf8') : undefined;
1088
- const content = buildManagedWrapperContent(target, relativeFile, existingContent, options.projectRoot);
1089
- const changed = existingContent !== content;
1090
- if (changed && !options.dryRun) {
1091
- writeFileWithBackup(filePath, content, options.backupDirectory);
1092
- }
1093
- return {
1094
- filePath,
1095
- relativeFile,
1096
- changed,
1097
- content,
1098
- mode: 'managed-wrapper',
1099
- canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
1100
- symlinkCapability: detectSymlinkCapability(options.projectRoot, target, relativeFile, options.symlinkCapability, options.dryRun),
1101
- reasonCodes: reasonCodesForNotes(options.memoryNotes ?? []),
1102
- };
1103
- });
1104
- const legacyAgentPathWrappers = retireLegacyAgentPathWrappers(options.projectRoot, target, options.dryRun, options.backupDirectory);
1105
- // A tracked-blocked wrapper is reported, never acted on, so it does not mark the target changed.
1106
- const retiredFiles = legacyAgentPathWrappers
1107
- .filter((entry) => entry.status !== 'tracked-blocked')
1108
- .map((entry) => entry.relativeFile);
1109
- return {
1110
- targetId: target.targetId,
1111
- canonicalFilePath,
1112
- files,
1113
- changed: canonicalChanged || files.some((file) => file.changed) || retiredFiles.length > 0,
1114
- ...(retiredFiles.length > 0 ? { retiredFiles } : {}),
1115
- ...(legacyAgentPathWrappers.length > 0 ? { legacyAgentPathWrappers } : {}),
1116
- };
1117
- }
1
+ import{execFileSync as Re}from"node:child_process";import{randomUUID as B}from"node:crypto";import{constants as ee,existsSync as k,lstatSync as C,mkdirSync as I,copyFileSync as M,readdirSync as te,readFileSync as R,readlinkSync as re,realpathSync as q,renameSync as ne,rmSync as v,statSync as Pe,symlinkSync as F,unlinkSync as G,writeFileSync as X}from"node:fs";import{platform as j}from"node:os";import{basename as Ce,dirname as L,join as y,relative as Se,resolve as $e}from"node:path";import{CANONICAL_PROJECT_MEMORY_SOURCE as h,getProjectMemoryTarget as H,renderArchitectureReferenceTable as Te}from"./shared-project-memory-types.js";import{assertProjectMemoryPaths as D,invalidProjectMemoryPath as Oe,isValidScopedRelativePath as xe}from"./project-memory-path-scope.js";const ve="legacy-agent-path-wrapper-tracked";function oe(e){return(e.memoryNotes?.length??0)>0||(e.architectureReferences?.length??0)>0||e.bootstrapArchitecture!==void 0}const z="<!-- NEOCORTEX-REFRESH-UPDATES-START -->",Y="<!-- NEOCORTEX-REFRESH-UPDATES-END -->";function U(e,t){return e.split(t).length-1}function Ae(e){ue(e.memoryNotes??[],e.architectureReferences??[],e.bootstrapArchitecture);const t=K(e.memoryNotes??[]).map(r=>`- [${r.reasonCode}] ${r.summary} (layer: ${r.layer})`),n=(e.architectureReferences??[]).map(r=>`- [architecture-reference] \`${r.path}\`: ${r.title}; ${r.purpose}; use: ${r.suggestedUsage}`),s=e.bootstrapArchitecture,o=s===void 0?[]:[...(s.universalLaws??[]).map(r=>`- [bootstrap-law] ${r}`),...(s.businessContext??[]).map(r=>`- [bootstrap-business] ${r}`),...(s.activeContext??[]).map(r=>`- [bootstrap-context] ${r}`),...(s.repositoryMap??[]).map(r=>`- [bootstrap-repository] ${r}`),...(s.environmentPractices??[]).map(r=>`- [bootstrap-environment] ${r}`),...(s.platformMemoryContract??[]).map(r=>`- [bootstrap-platform] ${r}`),...(s.maintenanceRules??[]).map(r=>`- [bootstrap-maintenance] ${r}`),...(s.heuristics??[]).map(r=>`- [bootstrap-heuristic] ${r}`)];return w([...t,...n,...o])}function Ne(e,t){if(t.split(`
2
+ `).length>e.budget.maxLines||Buffer.byteLength(t,"utf8")>e.budget.maxBytes)throw new Error("Canonical project memory update exceeds its context budget; refusing to truncate existing content.")}function se(e,t,n){const s=Ae(n);if(s.length===0)return t;const o=t.includes(`\r
3
+ `)?`\r
4
+ `:`
5
+ `,r=T(e),a=O(e),c=U(t,r),u=U(t,a);if(c!==1||u!==1||t.indexOf(a)<t.indexOf(r))throw new Error("Canonical project memory has ambiguous managed-block markers; refusing refresh.");const l=U(t,z),i=U(t,Y);if(l!==i||l>1)throw new Error("Canonical project memory has ambiguous refresh-update markers; refusing refresh.");let m;if(l===0){const f=t.indexOf(a),d=t.slice(0,f),g=[z,"## Durable Refresh Updates",...s,Y,""].join(o);m=`${d}${d.endsWith(o)?"":o}${g}${t.slice(f)}`}else{const f=t.indexOf(z),d=t.indexOf(Y),g=t.indexOf(r),E=t.indexOf(a);if(f<g||d>E||d<f)throw new Error("Canonical refresh-update block is outside the managed block; refusing refresh.");const P=t.slice(f,d),S=new Set(P.split(/\r?\n/).map($=>$.trim().toLowerCase())),p=s.filter($=>!S.has($.trim().toLowerCase()));if(p.length===0)return t;const _=t.slice(0,d);m=`${_}${_.endsWith(o)?"":o}${p.join(o)}${o}${t.slice(d)}`}return Ne(e,m),m}function _e(e){return{readFile(t){try{return R(t,"utf8")}catch{return}},writeFileAtomic(t,n){I(L(t),{recursive:!0});const s=B(),o=`${t}.tmp-${s}`,r=k(t)?pe(t,s,e):void 0;try{return X(o,n,{encoding:"utf8",flag:"wx",mode:384}),r!==void 0&&M(t,r,ee.COPYFILE_EXCL),ne(o,t),{backupPath:r}}catch(a){if(v(o,{force:!0}),r!==void 0&&k(r))try{M(r,t)}catch{}throw a}},join(...t){return y(...t)}}}function T(e){return`<!-- ${e.ownedBlockName}-START -->`}function O(e){return`<!-- ${e.ownedBlockName}-END -->`}function w(e){const t=new Set,n=[];for(const s of e){const o=s.trim().replace(/\s+/g," ");o.length===0||t.has(o.toLowerCase())||(t.add(o.toLowerCase()),n.push(o))}return n}function Ie(e){const t=new Set,n=[];for(const s of e)t.has(s.path)||(t.add(s.path),n.push(s));return n}function Me(e){switch(e.templateKind){case"neocortex-md":return"# NEOCORTEX.md Project Memory";case"claude-md":return"# CLAUDE.md Project Memory";case"agents-md":return"# AGENTS.md Project Instructions";case"gemini-md":return"# GEMINI.md Project Memory";case"copilot-instructions":return"# GitHub Copilot Repository Instructions";case"cursor-rule":return`---
6
+ description: Neocortex project memory
7
+ alwaysApply: true
8
+ ---
9
+
10
+ # Cursor Project Memory`}}const je=["Keep always-loaded memory compact: laws, active context, and references only.","Preserve human-authored instructions outside this owned block.","Prefer repository SSoT docs over duplicating architecture details here."],Le=["Consult `docs/architecture/` before changes that affect architecture, contracts, data, security, performance, UX, or infrastructure.","Reference architecture documents by repository path, such as `docs/architecture/architecture.md`, before changing related implementation.","Summarize decisions and trade-offs in NEOCORTEX.md; do not paste complete architecture documents into memory.","Update memory for durable cross-layer changes across skills/agents, frontend, backend, API, DB, schemas, envs, DevOps, cyber security, testing/QA, observability, product, docs, and platform contracts.","Prioritize compact summaries of durable decisions, public contracts, operational risks, debts, command behavior, and repository paths; skip transient logs, raw payloads, secrets, private prompts, long documents, and duplicated canonical sources.","Keep platform memory files symlink-backed or include-backed to NEOCORTEX.md when supported."],pt=["skills-agents","frontend","backend","api","db","schemas","envs","devops","cyber-security","testing-qa","observability","product-business","docs-architecture","platform-memory","command-behavior","generic"],De=360,ae={feature:"Features",rule:"Rules/Policies",flag:"Flags",route:"Routes",api:"APIs/Contracts","db-schema":"DB/Schema",architecture:"Architecture",debt:"Debts",decision:"Decisions",generic:"General Updates"},Ue=/\b(private|proprietary|server[- ]only|system)\s+prompt\b|\b(api[-_ ]?key|license[-_ ]?key|password|authorization|bearer|token|secret)\s*[:=]|\b(ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[baprs]-[A-Za-z0-9-]+)\b|\b(customer|cliente)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s+(payload|record|email|phone)\b|\b(customer|cliente)\s+(data|dados)\s*[:=]|\braw\s+payload\b/i;function We(e){const t=e.toLowerCase();return/\b(project memory|canonical memory|memory heuristic|neocortex\.md|\*update-memory)\b/.test(t)?"decision":/\b(feature|capability|funcionalidade|release)\b/.test(t)?"feature":/\b(rule|policy|guardrail|regra|lei|must|never)\b/.test(t)?"rule":/\b(flag|feature[- ]?flag|toggle|env var|environment variable)\b/.test(t)?"flag":/\b(api|contract|schema contract|graphql|rest|rpc|webhook)\b/.test(t)?"api":/\b(db|database|schema|migration|table|column|prisma|sql)\b/.test(t)?"db-schema":/\b(decision|decisão|decisao|accepted|rejected|trade[- ]?off)\b/.test(t)?"decision":/\b(route|endpoint route|url path|pathname)\b|\/(api|admin|portal|v\d+)\//.test(t)?"route":/\b(architecture|arquitetura|adr|topology|infra|boundary)\b/.test(t)?"architecture":/\b(debt|follow[- ]?up|todo|tech[- ]?debt|dívida|divida)\b/.test(t)?"debt":"generic"}function Be(e){const t=e.toLowerCase();return/\b(neocortex\.md|project memory|canonical memory|memory wrapper|symlink|owned block|memory heuristic)\b/.test(t)?"platform-memory":/\b(command|cli|\*update-memory|\*create-epic|\*arch-plan|workflow behavior)\b/.test(t)?"command-behavior":/\b(skill|agent|subagent|orchestrator|opencode|codex|claude|gemini|cursor)\b/.test(t)?"skills-agents":/\b(frontend|ui|ux|react|component|design[- ]?system|css|accessibility|a11y)\b/.test(t)?"frontend":/\b(backend|server|service|worker|job|queue)\b/.test(t)?"backend":/\b(api|endpoint|rest|graphql|rpc|webhook|contract)\b/.test(t)?"api":/\b(db|database|table|column|migration|sql|prisma)\b/.test(t)?"db":/\b(schema|schemas|zod|json schema|protobuf|openapi)\b/.test(t)?"schemas":/\b(env|environment|\.env\.example|config|configuration|feature[- ]?flag)\b/.test(t)?"envs":/\b(devops|deploy|deployment|ci|cd|docker|container|kubernetes|infra|terraform|rollback)\b/.test(t)?"devops":/\b(security|cyber|auth|authorization|permission|compliance|vulnerability|secret|token redaction)\b/.test(t)?"cyber-security":/\b(test|testing|qa|e2e|unit|integration|snapshot|property[- ]?based|flaky)\b/.test(t)?"testing-qa":/\b(observability|metric|metrics|log|logging|trace|tracing|alert|monitoring|slo)\b/.test(t)?"observability":/\b(product|business|user journey|onboarding|pricing|tenant|customer-facing)\b/.test(t)?"product-business":/\b(docs|documentation|architecture|arquitetura|adr|runbook|decision record)\b/.test(t)?"docs-architecture":"generic"}function ie(e){const t=e.trim().replace(/\s+/g," ");if(Buffer.byteLength(t,"utf8")<=De)return t;const n=t.match(/(?:^|\s)([\w.-]+(?:\/[\w.@-]+)+(?:\.[A-Za-z0-9]+)?)/)?.[1],s=t.slice(0,220).replace(/\s+\S*$/,"").trim();return n?`${s}\u2026 See ${n} for details.`:`${s}\u2026 Details omitted from always-loaded memory; keep source content in repository docs.`}function qe(e){b(e);const t=We(e),n=Be(e);return{kind:t,layer:n,sectionTitle:ae[t],summary:ie(e),reasonCode:`memory_update_${t.replace("-","_")}`}}function K(e){const t=new Set,n=[];for(const s of e){const o=qe(s),r=`${o.kind}:${o.summary.toLowerCase()}`;t.has(r)||(t.add(r),n.push(o))}return n}function b(e){if(Ue.test(e))throw new Error("Project memory input violates IP boundary guardrails.")}function ce(e,t){const n=(e??"").split(`
11
+ `),s=t.split(`
12
+ `),o=[],r=Math.max(n.length,s.length);for(let c=0;c<r;c++){const u=n[c],l=s[c];if(u!==l&&(u!==void 0&&o.push(`- ${u}`),l!==void 0&&o.push(`+ ${l}`),o.length>=80)){o.push("\u2026 diff truncated; inspect repository diff for full context.");break}}const a=o.join(`
13
+ `);return b(a),a}function J(e){b(e.path),b(e.title),b(e.purpose),b(e.suggestedUsage)}function ue(e,t,n){e.forEach(b),t.forEach(J),n?.universalLaws?.forEach(b),n?.businessContext?.forEach(b),n?.activeContext?.forEach(b),n?.repositoryMap?.forEach(b),n?.environmentPractices?.forEach(b),n?.platformMemoryContract?.forEach(b),n?.maintenanceRules?.forEach(b),n?.heuristics?.forEach(b),n?.importantReferences?.forEach(J),n?.architectureReferences?.forEach(J)}function de(e){return[Me(e),"","This file contains compact, always-loaded project memory. Keep detailed architecture in referenced docs.",""].join(`
14
+ `)}function le(e,t,n,s){ue(t,n,s);const o=w([...je,...s?.universalLaws??[]]),r=w([...s?.activeContext??[],...t.map(ie)]),a=K(t),c=w(s?.businessContext??["Product/business context was not explicitly documented during bootstrap; treat conclusions as repository-inferred until a human updates this section."]),u=w(s?.repositoryMap??["Source, tests, package/build files, docs, CI, and runtime manifests are the permitted bootstrap sources for repository orientation."]),l=w(s?.environmentPractices??["Use `.env.example` for configuration shape only; do not read real environment files or credential-bearing files into always-loaded memory."]),i=w(s?.platformMemoryContract??["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Platform wrapper/frontmatter must be preserved via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."]),m=w(s?.maintenanceRules??["Keep NEOCORTEX.md deterministic, compact, objective, and direct; store only summaries, indexes, and links to detailed docs.","Do not copy protected prompt bodies, proprietary wrappers, server-side internals, customer data, license keys, or long document bodies into always-loaded memory."]),f=Ie([...s?.importantReferences??[],...s?.architectureReferences??[],...n]),d=w([...Le,...s?.heuristics??[]]),g=o.map(p=>`- ${p}`),E=r.length>0?r.map(p=>`- ${p}`):["- No active project notes recorded."],P=f.length>0?Te(f):"No architecture references discovered.",S=a.length>0?Object.entries(ae).flatMap(([p,_])=>{const $=a.filter(x=>x.kind===p);return $.length>0?[`### ${_}`,...$.map(x=>`- [${x.reasonCode}] ${x.summary} (layer: ${x.layer})`)]:[]}):["- No durable change feedback recorded."];return[T(e),"## Universal Project Laws",...g,"","## Business/Product Context",...c.map(p=>`- ${p}`),"","## Active Context",...E,"","## Durable Change Feedback",...S,"","## Architecture References",P,"","## Repository Map",...u.map(p=>`- ${p}`),"","## Environment/Container/Production/Security/Dev Practices",...l.map(p=>`- ${p}`),"","## Platform Memory Contract",...i.map(p=>`- ${p}`),`- NEOCORTEX.md is the canonical project memory source for every platform target; run \`${e.bidirectionalReference.feedbackTrigger}\` when durable context discovered in a platform wrapper should be fed back into canonical memory.`,"","## Maintenance Rules",...m.map(p=>`- ${p}`),"","## Architecture Heuristics",...d.map(p=>`- ${p}`),O(e)].join(`
15
+ `)}const me=["docs/architecture","docs/arquitetura-software"],Fe=["README.md","readme.md","architecture.md","docs/architecture.md"],Ge=["package.json","pnpm-lock.yaml","package-lock.json","yarn.lock","tsconfig.json","vite.config.ts","turbo.json"],Xe=["Dockerfile","docker-compose.yml","compose.yml",".env.example","fly.toml"],He=["AGENTS.md","CLAUDE.md","GEMINI.md",".opencode/AGENTS.md",".cursor/rules/neocortex.mdc"];function fe(e,t,n=24e3){const s=y(e,t);try{if(!k(s)||C(s).isDirectory())return;const o=R(s,"utf8");return o.length<=n?o:o.slice(0,n)}catch{return}}function pe(e,t,n){if(!n)return`${e}.bak-${t}`;const s=$e(n),o=C(s);if(!o.isDirectory()||o.isSymbolicLink()||o.uid!==process.getuid?.()||(o.mode&63)!==0||q(s)!==s)throw new Error("project-memory-backup-directory-unsafe");return y(s,`${Ce(e)}.bak-${t}`)}function W(e,t,n){I(L(e),{recursive:!0});const s=B(),o=`${e}.tmp-${s}`,r=k(e)?pe(e,s,n):void 0;try{return X(o,t,{encoding:"utf8",flag:"wx",mode:384}),r!==void 0&&M(e,r,ee.COPYFILE_EXCL),ne(o,e),r}catch(a){if(v(o,{force:!0}),r!==void 0&&k(r))try{M(r,e)}catch{}throw a}}function Z(e){return Array.from(new Set(K(e).map(t=>t.reasonCode)))}function A(e,t){try{return k(y(e,t))}catch{return!1}}function ze(e,t){try{return te(y(e,t),{withFileTypes:!0}).filter(n=>!n.name.startsWith(".")&&!n.name.toLowerCase().includes("secret")).sort((n,s)=>n.name.localeCompare(s.name)).slice(0,8).map(n=>`${t}/${n.name}${n.isDirectory()?"/":""}`)}catch{return[]}}function ye(e,t,n=16){try{const s=te(y(e,t),{withFileTypes:!0}).filter(r=>!r.name.startsWith(".")&&!r.name.startsWith("_")).sort((r,a)=>r.name.localeCompare(a.name)),o=[];for(const r of s){const a=`${t}/${r.name}`;if(r.isDirectory()?o.push(...ye(e,a,n-o.length)):/\.(md|markdown)$/i.test(r.name)&&o.push(a),o.length>=n)break}return o}catch{return[]}}function Ye(e,t){const n=t.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim();return n?n.replace(/[`*_#]/g,""):e.split("/").pop()?.replace(/\.(md|markdown)$/i,"").replace(/[-_]+/g," ")??e}function Ke(e,t){const n=/\b(stale|deprecated|outdated|incerto|uncertain)\b/i.test(`${e}
16
+ ${t.slice(0,2e3)}`),s=t.replace(/^---[\s\S]*?---\s*/,"").split(/\n{2,}/).map(r=>r.replace(/^#+\s+.+$/gm,"").replace(/[`*_>#]/g,"").replace(/\s+/g," ").trim()).find(r=>r.length>0&&!r.startsWith("|"));return`${n?"[stale/uncertain evidence] ":""}${(s??"Architecture reference for this project.").slice(0,180)}`}function Je(e){const t=e.toLowerCase();return/deploy|infra|docker|production|runbook/.test(t)?"Use before changing deployment, runtime, containers, or production operations.":/security|auth|compliance/.test(t)?"Use before changing auth, compliance, or security-sensitive behavior.":/api|contract|state|schema/.test(t)?"Use before changing contracts, APIs, schemas, or persisted state.":"Use before implementation in this area; verify freshness when marked stale or uncertain."}function he(e){const t=Ge.filter(i=>A(e,i)),n=Xe.filter(i=>A(e,i)),s=He.filter(i=>A(e,i)),o=["packages","src","apps","tests","__tests__"].filter(i=>A(e,i)),a=[...me.flatMap(i=>ye(e,i)),...Fe.filter(i=>A(e,i))].slice(0,24).flatMap(i=>{const m=fe(e,i,48e3);return m?[{path:i,title:Ye(i,m),purpose:Ke(i,m),suggestedUsage:Je(i),source:me.some(f=>i.startsWith(`${f}/`))?"architecture-root":"fallback-file"}]:[]}),c=fe(e,"package.json"),u=c?.match(/"name"\s*:\s*"([^"]+)"/)?.[1],l=[...c?.matchAll(/"(test|build|lint|typecheck|dev)"\s*:/g)??[]].map(i=>i[1]);return{universalLaws:["Bootstrap canonical memory before creating or repairing platform memory wrappers when NEOCORTEX.md is absent.","Use only permitted repository sources for bootstrap: package/build files, architecture docs, README/deploy docs, .env.example, runtime manifests, CI, source/test layout, and platform memory wrappers."],businessContext:[u?`Repository package name: ${u}.`:"Repository product name was not declared in package metadata.","Business/product conclusions are bootstrap-inferred and must be refined from canonical docs or human input."],activeContext:[`Bootstrap scanned ${t.length} package/build files, ${a.length} architecture/readme docs, ${n.length} runtime/config templates, and ${s.length} platform memory wrappers.`,l.length>0?`Detected quality scripts: ${l.sort().join(", ")}.`:"No standard quality scripts were detected in package metadata."],repositoryMap:[t.length>0?`Package/build files: ${t.join(", ")}.`:"No package/build files detected in permitted bootstrap set.",o.length>0?`Source/test roots: ${o.flatMap(i=>ze(e,i)).slice(0,16).join(", ")}.`:"Source/test roots were not detected in standard locations.",s.length>0?`Platform memory/wrappers: ${s.join(", ")}.`:"No platform memory wrappers detected before bootstrap."],environmentPractices:[n.length>0?`Runtime/config templates: ${n.join(", ")}.`:"No Docker/compose/.env.example/runtime manifest detected in permitted bootstrap set.","Read `.env.example` only for configuration shape; never ingest real .env files, credentials, customer data, or license keys into memory.","Run repository quality scripts before commit and keep CI/deploy evidence referenced by path or URL rather than copied verbatim."],platformMemoryContract:["Semantic platform memory file must resolve to NEOCORTEX.md through a symlink; do not replace it with an unrelated wrapper or copied frontmatter.","Preserve wrappers/frontmatter via split/include/managed block while the semantic memory payload remains symlink-backed by NEOCORTEX.md."],maintenanceRules:["Generated memory must be deterministic, objective, direct, compact, and inside the target always-loaded context budget.","Cite long architecture docs by path with usage guidance; mark stale or uncertain docs when repository evidence indicates that status.","Do not copy protected prompt bodies, proprietary wrappers, server internals, secrets, customer data, license keys, or complete long documents."],architectureReferences:a,heuristics:["Before processing a story, consult the cited Architecture References whose path or suggested usage intersects the change.","When a referenced doc is marked stale/uncertain, validate against current package/runtime/source evidence before relying on it."]}}function V(e,t,n){const s=T(t),o=O(t),r=e.indexOf(s),a=e.indexOf(o);if(r>=0&&a>=r){const u=a+o.length;return`${e.slice(0,r)}${n}${e.slice(u)}`}const c=e.endsWith(`
17
+ `)?`
18
+ `:`
19
+
20
+ `;return`${e}${c}${n}
21
+ `}function Ze(e){return e.endsWith(".mdc")?`---
22
+ description: Neocortex project memory
23
+ alwaysApply: true
24
+ ---
25
+
26
+ `:e.endsWith(".toml")?`[agent]
27
+ name = "neocortex"
28
+ description = "Neocortex project memory wrapper"
29
+
30
+ `:e.endsWith(".agent.md")?`---
31
+ name: neocortex
32
+ description: Neocortex project memory wrapper
33
+ ---
34
+
35
+ `:""}function be(e,t){const n=L(y(e,t)),s=y(e,h),o=Se(n,s);return o.length>0?o:h}function N(e,t){return!!(e.targetId==="canonical"||e.requiresWrapperPreservation||e.linkRequirement.requiresWrapperPreservation||e.linkRequirement.wrapperAllowed||t==="AGENTS.md"||t.includes("/agents/")||t.includes("/skills/")||t.endsWith(".toml")||t.endsWith(".mdc")||t.endsWith(".agent.md")||t.endsWith(".instructions.md"))}function Ve(e){return e.linkRequirement.symlinkBacked&&e.linkRequirement.semanticFileRequired}function Q(e){return/EPERM|EACCES|operation not permitted|permission/i.test(e)?"EPERM: symlink permission denied":/ENOSYS|ENOTSUP|EOPNOTSUPP|not supported/i.test(e)?"symlink filesystem unsupported":"symlink capability unavailable"}function ge(e,t,n,s,o=!1){if(s!==void 0)return s;const r=Ve(t);if(!r)return{os:j(),supported:!1,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:N(t,n),reason:`target policy ${t.linkRequirement.policy} does not allow semantic symlink orchestration`};if(o)return{os:j(),supported:!0,permission:"unknown",filesystem:"unknown",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:N(t,n),reason:"dry-run does not probe filesystem symlink support"};const a=y(e,".neocortex","tmp"),c=B(),u=y(a,`symlink-capability-source-${c}`),l=y(a,`symlink-capability-link-${c}`);try{I(a,{recursive:!0}),X(u,"probe",{encoding:"utf8",flag:"wx",mode:384}),F(u,l);const i=C(l).isSymbolicLink()&&Pe(l).isFile();return{os:j(),supported:i,permission:i?"ok":"unknown",filesystem:i?"supports-symlink":"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:N(t,n),reason:i?void 0:"filesystem probe did not create a resolvable symbolic link"}}catch(i){const m=i instanceof Error?i.message:String(i),f=/EPERM|EACCES|operation not permitted|permission/i.test(m);return{os:j(),supported:!1,permission:f?"denied":"unknown",filesystem:"no-symlink-support",targetPolicy:t.linkRequirement.policy,targetPolicyAllowsSymlink:r,requiresWrapperPreservation:N(t,n),reason:Q(m)}}finally{v(l,{force:!0}),v(u,{force:!0})}}function Qe(e,t,n,s){const o=be(s,t),r=n??`${Ze(t)}# ${e.platformName} Neocortex Memory Wrapper
36
+
37
+ `,a=[T(e),"## Canonical Project Memory Source","",`This platform wrapper preserves host-specific frontmatter/instructions while resolving project memory to \`${o}\`.`,"",`- Canonical source: \`${h}\``,`- Symlink-backed/source-of-truth file: \`${o}\``,`- Feedback loop: read \`${o}\` for shared context and run \`${e.bidirectionalReference.feedbackTrigger}\` when durable platform findings should update \`${h}\`.`,"- Human-authored content outside this managed block is preserved byte-for-byte.",O(e)].join(`
38
+ `);return V(r,e,a)}function ke(e,t,n,s,o,r=!1){const a=y(e,t),c=Q(o),l=`${["[NEOCORTEX COMPATIBILITY REMEDIATION]","Materialized project memory fallback because semantic symlink orchestration failed.","This is not product mode; repair host permissions/filesystem support and restore the symlink to NEOCORTEX.md.","WARNING: materialized fallback is remediation debt, not a silent mode; run *update-memory for durable context and repair this file back to canonical NEOCORTEX.md resolution.",`Fallback reason: ${c}`,""].join(`
39
+ `)}${n}`,m=(k(a)?R(a,"utf8"):void 0)!==l;return m&&!r&&(k(a)&&C(a).isSymbolicLink()&&G(a),W(a,l)),{filePath:a,relativeFile:t,changed:m,content:l,mode:"compatibility-materialized-fallback",canonicalSource:h,symlinkCapability:s,fallbackReason:c,remediationDebt:`Repair ${t} so it is a symlink to ${h}; fallback is compatibility remediation only.`}}function et(e,t,n,s,o,r=!1){const a=y(e,t),c=be(e,t);r||I(L(a),{recursive:!0});const u=ge(e,n,t,o,r);if(!u.supported)return ke(e,t,s,u,u.reason??"symlink capability detection reported unsupported host",r);if(r){let i=!0;try{i=!(k(a)&&C(a).isSymbolicLink()&&re(a)===c)}catch{i=!0}return{filePath:a,relativeFile:t,changed:i,content:s,mode:"semantic-symlink",canonicalSource:h,symlinkCapability:u}}let l=!1;try{return k(a)?C(a).isSymbolicLink()&&re(a)===c?l=!1:(G(a),F(c,a),l=!0):(F(c,a),l=!0),{filePath:a,relativeFile:t,changed:l,content:R(a,"utf8"),mode:"semantic-symlink",canonicalSource:h,symlinkCapability:u}}catch(i){const m=i instanceof Error?i.message:String(i),f=Q(m);return ke(e,t,s,{...u,supported:!1,permission:/EPERM|EACCES|operation not permitted|permission/i.test(m)?"denied":u.permission,filesystem:"no-symlink-support",reason:f},f,r)}}function tt(e,t,n,s,o){const r=u=>u.split(`
40
+ `).length<=e.budget.maxLines&&Buffer.byteLength(u,"utf8")<=e.budget.maxBytes;if(r(t))return t;const a=le(e,n.slice(0,8),s.slice(0,12),o),c=V(t.includes(T(e))?t:de(e),e,a);return r(c)?c:c.slice(0,e.budget.maxBytes)}function Ee(e,t,n=[],s=[],o){const r=t??de(e),a=le(e,n,s,o),c=V(r,e,a);return tt(e,c,n,s,o)}function rt(e){const t=H(e.targetId),n=e.fs??_e(e.backupDirectory),s=n.join(e.projectRoot,t.primaryFile);if(e.fs===void 0&&t.targetId==="canonical"&&D(e.projectRoot,[h]),t.targetId!=="canonical"&&e.fs===void 0){const u=at(e).files.find(l=>l.relativeFile===t.primaryFile);if(u===void 0)throw new Error(`Primary project memory file was not written for ${t.targetId}.`);return{filePath:u.filePath,changed:u.changed,content:u.content}}const o=n.readFile(s),r=e.bootstrapArchitecture??(e.fs===void 0&&t.targetId==="canonical"&&o===void 0?he(e.projectRoot):void 0),a=t.targetId==="canonical"&&o!==void 0?oe(e)?se(t,o,e):o:Ee(t,o,e.memoryNotes,e.architectureReferences,r);if(o===a)return{filePath:s,changed:!1,content:a};const c=e.dryRun?void 0:n.writeFileAtomic(s,a);return{filePath:s,changed:!0,content:a,safeDiff:ce(o,a),backupPath:c?.backupPath,reasonCodes:Z(e.memoryNotes??[])}}function yt(e){return rt({...e,targetId:"canonical"})}const nt={"claude-code":[".claude/agents/neocortex.md"],"gemini-cli":[".gemini/agents/neocortex.md"],antigravity:[".gemini/agents/neocortex.md"]},ot=/^# [^\n]* Neocortex Memory Wrapper\s*$/;function we(e,t){try{return Re("git",["-c","core.fsmonitor=false","ls-files","--error-unmatch","--",t],{cwd:e,stdio:["ignore","ignore","ignore"],env:{...Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_"))),GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"},timeout:1e4,windowsHide:!0}),!0}catch{return!1}}function st(e,t,n,s){const o=[],r=n?"would-retire":"retired",a=c=>({relativeFile:c,status:"tracked-blocked",reasonCode:ve,remediation:`git rm ${c}`});for(const c of nt[t.targetId]??[]){D(e,[c]);const u=y(e,c);let l;try{l=C(u)}catch{continue}if(l.isSymbolicLink()){let E=!1;try{E=q(u)===q(y(e,h))}catch{E=!1}if(E){if(we(e,c)){o.push(a(c));continue}n||G(u),o.push({relativeFile:c,status:r})}continue}if(!l.isFile())continue;const i=R(u,"utf8"),m=i.indexOf(T(t)),f=i.indexOf(O(t));if(m<0||f<m)continue;if(we(e,c)){o.push(a(c));continue}const d=i.slice(0,m)+i.slice(f+O(t).length),g=d.trim();g.length===0||ot.test(g)?n||v(u,{force:!0}):n||W(u,`${d.replace(/\s+$/,"")}
41
+ `,s),o.push({relativeFile:c,status:r})}return o}function at(e){if(e.fs!==void 0)throw new Error("writeProjectMemoryTargetFiles requires the node filesystem to manage symlinks safely.");const t=H(e.targetId),n=H("canonical");t.secondaryFiles.some(d=>d===null||d.scope!=="project"&&d.scope!=="user"||!xe(d.path))&&Oe("invalid");const s=Array.from(new Set([t.primaryFile,...t.targetId==="canonical"?[]:t.secondaryFiles.filter(d=>d.scope==="project").map(d=>d.path)]));D(e.projectRoot,[h,...s,".neocortex/tmp"]);const o=y(e.projectRoot,h),r=k(o)?R(o,"utf8"):void 0,a=e.bootstrapArchitecture??(r===void 0?he(e.projectRoot):void 0),c=r!==void 0?oe(e)?se(n,r,e):r:Ee(n,r,e.memoryNotes,e.architectureReferences,a),u=!k(o)||R(o,"utf8")!==c;let l;if(u&&!e.dryRun&&(l=W(o,c,e.backupDirectory)),t.targetId==="canonical")return{targetId:t.targetId,canonicalFilePath:o,changed:u,files:[{filePath:o,relativeFile:h,changed:u,content:c,mode:"canonical",canonicalSource:h,safeDiff:ce(r,c),backupPath:l,reasonCodes:Z(e.memoryNotes??[])}]};const i=s.map(d=>{if(D(e.projectRoot,[d,".neocortex/tmp"]),!N(t,d))return et(e.projectRoot,d,t,c,e.symlinkCapability,e.dryRun);const g=y(e.projectRoot,d),E=k(g)?R(g,"utf8"):void 0,P=Qe(t,d,E,e.projectRoot),S=E!==P;return S&&!e.dryRun&&W(g,P,e.backupDirectory),{filePath:g,relativeFile:d,changed:S,content:P,mode:"managed-wrapper",canonicalSource:h,symlinkCapability:ge(e.projectRoot,t,d,e.symlinkCapability,e.dryRun),reasonCodes:Z(e.memoryNotes??[])}}),m=st(e.projectRoot,t,e.dryRun,e.backupDirectory),f=m.filter(d=>d.status!=="tracked-blocked").map(d=>d.relativeFile);return{targetId:t.targetId,canonicalFilePath:o,files:i,changed:u||i.some(d=>d.changed)||f.length>0,...f.length>0?{retiredFiles:f}:{},...m.length>0?{legacyAgentPathWrappers:m}:{}}}export{ve as LEGACY_AGENT_PATH_WRAPPER_TRACKED_REASON,pt as PROJECT_MEMORY_LAYER_CATEGORIES,he as bootstrapArchitectureMemory,Ee as buildProjectMemoryContent,qe as classifyProjectMemoryUpdate,_e as createNodeProjectMemoryFs,ce as createSafeProjectMemoryDiff,N as shouldUseManagedWrapper,yt as writeCanonicalProjectMemory,rt as writeProjectMemory,at as writeProjectMemoryTargetFiles};