@north-light/crouter 0.3.227 → 0.3.228

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 (286) hide show
  1. package/dist/api/client.d.ts +5 -5
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/dto/broker-ops.d.ts +8 -0
  4. package/dist/api/dto/memory.d.ts +8 -7
  5. package/dist/api/dto/memory.js +2 -2
  6. package/dist/builtin-memory/05-kinds/design/00-base.md +3 -4
  7. package/dist/builtin-memory/05-kinds/design/01-orchestrator.md +4 -3
  8. package/dist/builtin-memory/05-kinds/design/design-contract.md +3 -6
  9. package/dist/builtin-memory/05-kinds/plan/00-base.md +3 -4
  10. package/dist/builtin-memory/05-kinds/plan/01-orchestrator.md +4 -5
  11. package/dist/builtin-memory/05-kinds/plan/plan-contract.md +5 -13
  12. package/dist/builtin-memory/design/guide.md +38 -16
  13. package/dist/builtin-memory/design/roadmap.md +4 -4
  14. package/dist/builtin-memory/insights/init.md +5 -5
  15. package/dist/builtin-memory/internal/INDEX.md +1 -1
  16. package/dist/builtin-memory/internal/examples/INDEX.md +1 -1
  17. package/dist/builtin-memory/internal/memory-loading.md +6 -6
  18. package/dist/builtin-memory/internal/plugins.md +1 -1
  19. package/dist/builtin-memory/plan/guide.md +53 -0
  20. package/dist/builtin-memory/plan/roadmap.md +10 -8
  21. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +50 -37
  22. package/dist/clients/attach/__tests__/pane-tag-successor.test.js +56 -0
  23. package/dist/clients/attach/__tests__/profile-files.test.js +21 -0
  24. package/dist/clients/attach/chrome/inbox-strip.js +11 -7
  25. package/dist/clients/attach/session/pane-tag.d.ts +28 -2
  26. package/dist/clients/attach/session/pane-tag.js +48 -22
  27. package/dist/clients/attach/session/profile-files.d.ts +6 -0
  28. package/dist/clients/attach/session/profile-files.js +44 -11
  29. package/dist/clients/attach/slash/dispatch.js +4 -7
  30. package/dist/clients/attach/viewer.js +588 -596
  31. package/dist/commands/__tests__/surface-reload-target.test.js +21 -0
  32. package/dist/commands/api-client.d.ts +3 -7
  33. package/dist/commands/api-client.js +7 -12
  34. package/dist/commands/memory/__tests__/command-selector-and-mutation-guards.test.js +292 -0
  35. package/dist/commands/memory/__tests__/repository-root-lint.test.js +146 -0
  36. package/dist/commands/memory/delete.js +51 -24
  37. package/dist/commands/memory/edit.js +50 -10
  38. package/dist/commands/memory/find.js +105 -56
  39. package/dist/commands/memory/history.js +51 -31
  40. package/dist/commands/memory/lint.d.ts +0 -9
  41. package/dist/commands/memory/lint.js +78 -322
  42. package/dist/commands/memory/list.d.ts +12 -4
  43. package/dist/commands/memory/list.js +64 -25
  44. package/dist/commands/memory/move.js +103 -73
  45. package/dist/commands/memory/origin.js +35 -5
  46. package/dist/commands/memory/read.d.ts +4 -0
  47. package/dist/commands/memory/read.js +132 -80
  48. package/dist/commands/memory/shared.d.ts +115 -25
  49. package/dist/commands/memory/shared.js +331 -74
  50. package/dist/commands/memory/write.js +72 -21
  51. package/dist/commands/memory.js +2 -2
  52. package/dist/commands/node/lifecycle.js +2 -2
  53. package/dist/commands/pkg/market-manage.js +25 -24
  54. package/dist/commands/pkg/plugin-manage.d.ts +22 -6
  55. package/dist/commands/pkg/plugin-manage.js +118 -25
  56. package/dist/commands/pkg/shared.d.ts +8 -0
  57. package/dist/commands/pkg/shared.js +23 -20
  58. package/dist/commands/surface-reload.d.ts +5 -0
  59. package/dist/commands/surface-reload.js +9 -1
  60. package/dist/commands/sys/__tests__/migrate.test.js +1140 -22
  61. package/dist/commands/sys/__tests__/sync-project-guidance.test.js +218 -0
  62. package/dist/commands/sys/migrate.js +126 -140
  63. package/dist/commands/sys/panels/profiles-panel.d.ts +66 -0
  64. package/dist/commands/sys/panels/profiles-panel.js +599 -0
  65. package/dist/commands/sys/settings-shell.d.ts +4 -2
  66. package/dist/commands/sys/settings-shell.js +35 -4
  67. package/dist/commands/sys/settings.js +21 -5
  68. package/dist/commands/sys/sync-deps.d.ts +2 -0
  69. package/dist/commands/sys/sync-deps.js +26 -15
  70. package/dist/commands/sys/sync-project-guidance.js +228 -145
  71. package/dist/commands/sys/sync-skills.js +28 -17
  72. package/dist/commands/sys/update.js +11 -3
  73. package/dist/core/__tests__/canvas-inbox-watcher-hold.test.js +15 -2
  74. package/dist/core/__tests__/config-change-delta.test.js +106 -0
  75. package/dist/core/__tests__/context-intro.test.js +13 -9
  76. package/dist/core/__tests__/daemon-boot.test.js +22 -16
  77. package/dist/core/__tests__/fixtures/memory-slash-live-probe.js +5 -1
  78. package/dist/core/__tests__/human-deliver.test.js +19 -0
  79. package/dist/core/__tests__/inline-memory-refs.test.js +50 -46
  80. package/dist/core/__tests__/{serial → integration}/broker-fork-seam.test.js +1 -1
  81. package/dist/core/__tests__/{serial → integration}/broker-sdk-wiring.test.js +1 -1
  82. package/dist/core/__tests__/{serial → integration}/broker-snapshot-history.test.js +1 -1
  83. package/dist/core/__tests__/{serial → integration}/command-plugins.test.js +94 -3
  84. package/dist/core/__tests__/{serial → integration}/deferred-no-wake.test.js +1 -1
  85. package/dist/core/__tests__/{serial → integration}/flagship-lifecycle.test.js +13 -27
  86. package/dist/core/__tests__/{serial → integration}/host-teardown-process-group.test.js +1 -1
  87. package/dist/core/__tests__/{serial → integration}/human-deliver-e2e.test.js +1 -1
  88. package/dist/core/__tests__/{live-mutation-verbs.test.js → integration/live-mutation-verbs.test.js} +22 -33
  89. package/dist/core/__tests__/{serial → integration}/live-mutation.test.js +21 -41
  90. package/dist/core/__tests__/integration/refresh-stall-recycle.test.d.ts +1 -0
  91. package/dist/core/__tests__/{serial → integration}/refresh-stall-recycle.test.js +1 -1
  92. package/dist/core/__tests__/integration/revive.test.d.ts +1 -0
  93. package/dist/core/__tests__/{serial → integration}/revive.test.js +38 -19
  94. package/dist/core/__tests__/integration/spawn-root.test.d.ts +1 -0
  95. package/dist/core/__tests__/{serial → integration}/spawn-root.test.js +104 -1
  96. package/dist/core/__tests__/integration/subscription-delivery.test.d.ts +1 -0
  97. package/dist/core/__tests__/{serial → integration}/subscription-delivery.test.js +1 -1
  98. package/dist/core/__tests__/integration/tmux-surface.test.d.ts +1 -0
  99. package/dist/core/__tests__/{serial → integration}/tmux-surface.test.js +1 -1
  100. package/dist/core/__tests__/integration/worktree-land.test.d.ts +1 -0
  101. package/dist/core/__tests__/integration/worktree-land.test.js +400 -0
  102. package/dist/core/__tests__/integration/worktree-reap.test.d.ts +1 -0
  103. package/dist/core/__tests__/{serial/worktree.test.js → integration/worktree-reap.test.js} +6 -338
  104. package/dist/core/__tests__/kickoff.test.js +16 -5
  105. package/dist/core/__tests__/memory-resolver-precedence.test.js +122 -91
  106. package/dist/core/__tests__/nested-store-discovery.test.js +5 -3
  107. package/dist/core/__tests__/on-read-crouter-home-fence.test.js +2 -1
  108. package/dist/core/__tests__/on-read-dedup-resume.test.js +39 -27
  109. package/dist/core/__tests__/on-read-nested-store.test.js +19 -13
  110. package/dist/core/__tests__/profile-project-memory-delivery.test.js +138 -44
  111. package/dist/core/__tests__/repository-association.test.d.ts +1 -0
  112. package/dist/core/__tests__/repository-association.test.js +153 -0
  113. package/dist/core/__tests__/repository-root-identity.test.d.ts +1 -0
  114. package/dist/core/__tests__/repository-root-identity.test.js +219 -0
  115. package/dist/core/__tests__/seam/memory-slash-node-relative-inventory.test.js +27 -11
  116. package/dist/core/__tests__/warm-claim-preference-snapshot.test.d.ts +1 -0
  117. package/dist/core/__tests__/warm-claim-preference-snapshot.test.js +40 -0
  118. package/dist/core/canvas/canvas.d.ts +3 -0
  119. package/dist/core/canvas/canvas.js +30 -10
  120. package/dist/core/canvas/db.js +28 -1
  121. package/dist/core/canvas/paths.d.ts +4 -6
  122. package/dist/core/canvas/paths.js +8 -6
  123. package/dist/core/canvas/render-source.js +2 -2
  124. package/dist/core/canvas/types.d.ts +9 -13
  125. package/dist/core/exclusive-lock.d.ts +2 -0
  126. package/dist/core/exclusive-lock.js +21 -0
  127. package/dist/core/git.d.ts +0 -1
  128. package/dist/core/git.js +0 -3
  129. package/dist/core/human/__tests__/integration/inbox-core.test.d.ts +1 -0
  130. package/dist/core/human/feedback-companion.js +3 -0
  131. package/dist/core/human/scan.js +8 -1
  132. package/dist/core/keybindings/catalog.d.ts +2 -2
  133. package/dist/core/keybindings/catalog.js +2 -1
  134. package/dist/core/memory/doc-link-grammar.js +2 -2
  135. package/dist/core/memory/history.d.ts +24 -0
  136. package/dist/core/memory/history.js +66 -1
  137. package/dist/core/memory/identity.d.ts +65 -0
  138. package/dist/core/memory/identity.js +185 -0
  139. package/dist/core/memory/inline-ref-guidance.d.ts +1 -1
  140. package/dist/core/memory/inline-ref-guidance.js +1 -1
  141. package/dist/core/memory/inline-ref-inventory.d.ts +3 -10
  142. package/dist/core/memory/inline-ref-inventory.js +30 -62
  143. package/dist/core/memory/lint.d.ts +129 -0
  144. package/dist/core/memory/lint.js +517 -0
  145. package/dist/core/memory/project-namespace.d.ts +31 -0
  146. package/dist/core/memory/project-namespace.js +85 -0
  147. package/dist/core/memory/repository-association.d.ts +31 -0
  148. package/dist/core/memory/repository-association.js +129 -0
  149. package/dist/core/memory/tree.d.ts +39 -0
  150. package/dist/core/memory/tree.js +93 -0
  151. package/dist/core/memory-resolver.d.ts +193 -90
  152. package/dist/core/memory-resolver.js +461 -375
  153. package/dist/core/nested-stores.js +6 -13
  154. package/dist/core/profiles/select.d.ts +4 -1
  155. package/dist/core/profiles/select.js +108 -48
  156. package/dist/core/review/__tests__/capture-origin.test.js +2 -2
  157. package/dist/core/review/__tests__/stage-identity.test.js +2 -2
  158. package/dist/core/review/companion.js +11 -2
  159. package/dist/core/runtime/bearings.d.ts +2 -2
  160. package/dist/core/runtime/bearings.js +3 -3
  161. package/dist/core/runtime/broker/daemon-ops.d.ts +2 -2
  162. package/dist/core/runtime/broker/rebind.js +5 -0
  163. package/dist/core/runtime/broker-extension-render.d.ts +7 -3
  164. package/dist/core/runtime/broker-extension-render.js +10 -5
  165. package/dist/core/runtime/broker-persona-guidance.d.ts +19 -5
  166. package/dist/core/runtime/broker-persona-guidance.js +122 -27
  167. package/dist/core/runtime/deliver-live.d.ts +16 -4
  168. package/dist/core/runtime/deliver-live.js +29 -15
  169. package/dist/core/runtime/kickoff.d.ts +3 -3
  170. package/dist/core/runtime/kickoff.js +8 -16
  171. package/dist/core/runtime/lifecycle.js +2 -3
  172. package/dist/core/runtime/nodes.d.ts +3 -4
  173. package/dist/core/runtime/nodes.js +3 -4
  174. package/dist/core/runtime/persona.d.ts +8 -12
  175. package/dist/core/runtime/persona.js +24 -96
  176. package/dist/core/runtime/promote.d.ts +2 -2
  177. package/dist/core/runtime/promote.js +8 -21
  178. package/dist/core/runtime/revive.js +20 -17
  179. package/dist/core/runtime/spawn.js +18 -7
  180. package/dist/core/runtime/tmux-bindings.js +2 -3
  181. package/dist/core/runtime/warm-pool.js +3 -4
  182. package/dist/core/scope.js +2 -0
  183. package/dist/core/self-update.d.ts +0 -2
  184. package/dist/core/self-update.js +2 -35
  185. package/dist/core/substrate/__tests__/surface-match-memory-read.test.d.ts +1 -0
  186. package/dist/core/substrate/__tests__/surface-match-memory-read.test.js +28 -0
  187. package/dist/core/substrate/index.d.ts +2 -2
  188. package/dist/core/substrate/index.js +1 -1
  189. package/dist/core/substrate/injected-store.d.ts +43 -27
  190. package/dist/core/substrate/injected-store.js +208 -104
  191. package/dist/core/substrate/listings.d.ts +19 -12
  192. package/dist/core/substrate/listings.js +75 -52
  193. package/dist/core/substrate/on-read-node.d.ts +4 -7
  194. package/dist/core/substrate/on-read-node.js +6 -8
  195. package/dist/core/substrate/on-read.d.ts +22 -25
  196. package/dist/core/substrate/on-read.js +103 -147
  197. package/dist/core/substrate/render-node.d.ts +4 -7
  198. package/dist/core/substrate/render-node.js +5 -7
  199. package/dist/core/substrate/render.d.ts +21 -3
  200. package/dist/core/substrate/render.js +291 -223
  201. package/dist/core/substrate/schema.d.ts +1 -13
  202. package/dist/core/substrate/schema.js +5 -40
  203. package/dist/core/substrate/session-cache.d.ts +14 -4
  204. package/dist/core/substrate/session-cache.js +40 -22
  205. package/dist/core/substrate/surface-match.d.ts +9 -7
  206. package/dist/core/substrate/surface-match.js +26 -25
  207. package/dist/daemon/__tests__/helpers/source-daemon.d.ts +30 -0
  208. package/dist/daemon/__tests__/helpers/source-daemon.js +174 -0
  209. package/dist/daemon/__tests__/integration/migration-startup.test.d.ts +1 -0
  210. package/dist/daemon/__tests__/integration/migration-startup.test.js +97 -0
  211. package/dist/daemon/api/__tests__/bridge-heartbeat.test.js +21 -5
  212. package/dist/daemon/api/handlers/broker-ops.js +21 -16
  213. package/dist/daemon/api/handlers/memory.js +2 -0
  214. package/dist/daemon/crtrd.js +2 -0
  215. package/dist/daemon/human/finish.js +8 -1
  216. package/dist/daemon/manage.d.ts +0 -1
  217. package/dist/daemon/manage.js +7 -16
  218. package/dist/daemon/startup-policy.d.ts +1 -0
  219. package/dist/daemon/startup-policy.js +1 -0
  220. package/dist/migrations/001-surfaces-frontmatter.js +21 -109
  221. package/dist/migrations/002-profile-project-memory.js +1 -0
  222. package/dist/migrations/003-repository-root-memory-identity/front-door.d.ts +26 -0
  223. package/dist/migrations/003-repository-root-memory-identity/front-door.js +231 -0
  224. package/dist/migrations/003-repository-root-memory-identity/index.d.ts +2 -0
  225. package/dist/migrations/003-repository-root-memory-identity/index.js +513 -0
  226. package/dist/migrations/003-repository-root-memory-identity/references.d.ts +95 -0
  227. package/dist/migrations/003-repository-root-memory-identity/references.js +469 -0
  228. package/dist/migrations/003-repository-root-memory-identity/repository-facts.d.ts +39 -0
  229. package/dist/migrations/003-repository-root-memory-identity/repository-facts.js +349 -0
  230. package/dist/migrations/__tests__/activation-concurrency.test.d.ts +1 -0
  231. package/dist/migrations/__tests__/activation-concurrency.test.js +145 -0
  232. package/dist/migrations/__tests__/activation.test.d.ts +1 -0
  233. package/dist/migrations/__tests__/activation.test.js +149 -0
  234. package/dist/migrations/__tests__/deletion-and-root-declaration.test.d.ts +1 -0
  235. package/dist/migrations/__tests__/deletion-and-root-declaration.test.js +149 -0
  236. package/dist/migrations/activation.d.ts +16 -0
  237. package/dist/migrations/activation.js +78 -0
  238. package/dist/migrations/convergent.d.ts +14 -3
  239. package/dist/migrations/convergent.js +21 -10
  240. package/dist/migrations/corpus.d.ts +78 -0
  241. package/dist/migrations/corpus.js +497 -0
  242. package/dist/migrations/frontmatter-splice.d.ts +15 -0
  243. package/dist/migrations/frontmatter-splice.js +176 -0
  244. package/dist/migrations/registry.d.ts +6 -1
  245. package/dist/migrations/registry.js +7 -2
  246. package/dist/migrations/runner.d.ts +41 -0
  247. package/dist/migrations/runner.js +81 -0
  248. package/dist/migrations/types.d.ts +148 -9
  249. package/dist/migrations/types.js +9 -2
  250. package/dist/pi-extensions/__tests__/canvas-context-intro.test.js +225 -17
  251. package/dist/pi-extensions/__tests__/canvas-goal-capture-envelope.test.js +11 -3
  252. package/dist/pi-extensions/canvas-context-intro.d.ts +3 -5
  253. package/dist/pi-extensions/canvas-context-intro.js +50 -46
  254. package/dist/pi-extensions/canvas-doc-substrate.d.ts +1 -8
  255. package/dist/pi-extensions/canvas-doc-substrate.js +55 -122
  256. package/dist/pi-extensions/canvas-stophook.js +6 -13
  257. package/dist/shared/generated-context.d.ts +0 -3
  258. package/dist/shared/generated-context.js +0 -57
  259. package/dist/shared/tool-groups.js +2 -3
  260. package/package.json +5 -4
  261. package/runtime.lock.json +2 -2
  262. /package/dist/api/__tests__/{serial → integration}/client.test.d.ts +0 -0
  263. /package/dist/api/__tests__/{serial → integration}/client.test.js +0 -0
  264. /package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/__tests__/{serial → integration}/provider-rotation.test.ts +0 -0
  265. /package/dist/clients/{inbox/__tests__/serial/inbox-controller.test.d.ts → attach/__tests__/pane-tag-successor.test.d.ts} +0 -0
  266. /package/dist/clients/{inbox/__tests__/serial/mount-panel.test.d.ts → attach/__tests__/profile-files.test.d.ts} +0 -0
  267. /package/dist/{core/__tests__/live-mutation-verbs.test.d.ts → clients/inbox/__tests__/integration/inbox-controller.test.d.ts} +0 -0
  268. /package/dist/clients/inbox/__tests__/{serial → integration}/inbox-controller.test.js +0 -0
  269. /package/dist/{core/__tests__/serial/broker-fork-seam.test.d.ts → clients/inbox/__tests__/integration/mount-panel.test.d.ts} +0 -0
  270. /package/dist/clients/inbox/__tests__/{serial → integration}/mount-panel.test.js +0 -0
  271. /package/dist/{core/__tests__/serial/broker-sdk-wiring.test.d.ts → commands/__tests__/surface-reload-target.test.d.ts} +0 -0
  272. /package/dist/{core/__tests__/serial/broker-snapshot-history.test.d.ts → commands/memory/__tests__/command-selector-and-mutation-guards.test.d.ts} +0 -0
  273. /package/dist/{core/__tests__/serial/command-plugins.test.d.ts → commands/memory/__tests__/repository-root-lint.test.d.ts} +0 -0
  274. /package/dist/{core/__tests__/serial/deferred-no-wake.test.d.ts → commands/sys/__tests__/sync-project-guidance.test.d.ts} +0 -0
  275. /package/dist/core/__tests__/{serial/flagship-lifecycle.test.d.ts → config-change-delta.test.d.ts} +0 -0
  276. /package/dist/core/__tests__/{serial/host-teardown-process-group.test.d.ts → integration/broker-fork-seam.test.d.ts} +0 -0
  277. /package/dist/core/__tests__/{serial/human-deliver-e2e.test.d.ts → integration/broker-sdk-wiring.test.d.ts} +0 -0
  278. /package/dist/core/__tests__/{serial/live-mutation.test.d.ts → integration/broker-snapshot-history.test.d.ts} +0 -0
  279. /package/dist/core/__tests__/{serial/refresh-stall-recycle.test.d.ts → integration/command-plugins.test.d.ts} +0 -0
  280. /package/dist/core/__tests__/{serial/revive.test.d.ts → integration/deferred-no-wake.test.d.ts} +0 -0
  281. /package/dist/core/__tests__/{serial/spawn-root.test.d.ts → integration/flagship-lifecycle.test.d.ts} +0 -0
  282. /package/dist/core/__tests__/{serial/subscription-delivery.test.d.ts → integration/host-teardown-process-group.test.d.ts} +0 -0
  283. /package/dist/core/__tests__/{serial/tmux-surface.test.d.ts → integration/human-deliver-e2e.test.d.ts} +0 -0
  284. /package/dist/core/__tests__/{serial/worktree.test.d.ts → integration/live-mutation-verbs.test.d.ts} +0 -0
  285. /package/dist/core/{human/__tests__/serial/inbox-core.test.d.ts → __tests__/integration/live-mutation.test.d.ts} +0 -0
  286. /package/dist/core/human/__tests__/{serial → integration}/inbox-core.test.js +0 -0
@@ -0,0 +1,517 @@
1
+ // lint.ts — the ONE memory validation engine. It checks a PHYSICAL store (every
2
+ // markdown file it holds, whether or not the runtime will mount it) or a whole
3
+ // TARGET VIEW (every store a cwd/profile/node sees, plus the cross-store
4
+ // diagnostics only a view can produce), and returns structured findings. The
5
+ // `memory lint` leaf, migration verification, the plugin candidate gate, and
6
+ // the build's builtin-corpus gate all consume this module rather than
7
+ // reimplementing a rule: a rule asserted in one caller holds only there.
8
+ //
9
+ // Severity is the contract: `error` fails an authoring/mount gate, `warning` is
10
+ // a non-fatal authoring smell, `notice` is inspection data (duplicate stores are
11
+ // legitimate, so equal-canonical candidates across stores are reported, never
12
+ // failed).
13
+ import { basename, join, matchesGlob, relative, sep } from 'node:path';
14
+ import { pathExists, readText, realpathOrSelf, walkFiles } from '../fs-utils.js';
15
+ import { parseFrontmatterGeneric } from '../frontmatter.js';
16
+ import { descendantStoreRoots } from '../nested-stores.js';
17
+ import { projectScopeRoots } from '../scope.js';
18
+ import { associateRepository } from './repository-association.js';
19
+ import { loadProfileManifest } from '../profiles/manifest.js';
20
+ import { loadMemoryTargetView, loadStoreMemoryDocs, openProjectMemoryStore, } from '../memory-resolver.js';
21
+ import { buildMemoryTree } from './tree.js';
22
+ import { canonicalSegments, collapseTrailingIndex, INDEX_SEGMENT, localNameFromPath, normalizeDocName, validateExplicitLocalName, } from './identity.js';
23
+ import { lintSubstrateFrontmatter, parsedSubstrateSurfaces } from '../substrate/frontmatter-validation.js';
24
+ import { memoryExtensionValidationCatalog, validateMemoryExtensionValues } from './extensions.js';
25
+ import { docLinkNames } from './doc-link-grammar.js';
26
+ /** The rules that decide whether a corpus is COMPATIBLE with exact canonical
27
+ * identity — what a plugin candidate gate, the builtin build gate, and
28
+ * migration verification refuse a corpus on, independent of authoring-quality
29
+ * rules such as length or routing lines. */
30
+ export const MEMORY_LINT_IDENTITY_RULES = new Set([
31
+ 'store-namespace',
32
+ 'namespace-placement',
33
+ 'owner-path-collision',
34
+ 'root-name',
35
+ 'root-index-unaddressable',
36
+ 'local-name',
37
+ 'canonical-collision',
38
+ 'dangling-link',
39
+ 'memory-read-route',
40
+ ]);
41
+ function makeResult(findings, checked, documents, storesLinted) {
42
+ const errors = findings.filter((f) => f.severity === 'error');
43
+ return {
44
+ ok: errors.length === 0,
45
+ checked,
46
+ documents,
47
+ storesLinted,
48
+ findings,
49
+ errors,
50
+ warnings: findings.filter((f) => f.severity === 'warning'),
51
+ notices: findings.filter((f) => f.severity === 'notice'),
52
+ };
53
+ }
54
+ // ---------------------------------------------------------------------------
55
+ // Body-length caps, measured in WORDS (frontmatter excluded). Words, not lines:
56
+ // house style writes each paragraph as ONE logical line and lets the editor
57
+ // soft-wrap, so a line count measures wrapping style rather than context cost.
58
+ //
59
+ // A `boot` entry at `content` inlines the whole body into every agent's system
60
+ // prompt; a `content` entry on any other event surfaces the whole body whenever
61
+ // the entry fires — both cap at 1000 words. A `boot` entry at `preview` routes a
62
+ // deliberate reader into the whole body, so its cap is the longest doc worth
63
+ // reading end to end. `name` entries and surface-less docs never cap: such a doc
64
+ // is only reached deliberately, so its length is the reader's choice. The
65
+ // strictest applicable cap wins.
66
+ //
67
+ // Persona layers — canonical names under `kinds/`, the docs the prompt render
68
+ // composes into an agent's persona — are structurally exempt: an agent reads its
69
+ // whole persona by construction. Suppression elsewhere is deliberate and
70
+ // per-doc: `lint-ignore: length`, surfaced ONLY by the finding itself.
71
+ // ---------------------------------------------------------------------------
72
+ const BOOT_CONTENT_MAX_WORDS = 1000;
73
+ const EVENT_CONTENT_MAX_WORDS = 1000;
74
+ const BOOT_PREVIEW_MAX_WORDS = 3000;
75
+ /** A routing line costs more than it saves for a short rule or fact. */
76
+ const PREVIEW_TO_CONTENT_MAX_WORDS = 30;
77
+ const LENGTH_REMEDY = 'Keep the load-bearing core here and split the depth into [[linked]] reference docs carrying no surfaces at all (the listing and the link are how they are found, so they cost nothing until followed). Split by subject: each leaf covers a different subject a task might need on its own; never split off “further evidence”, examples, or references — a references leaf is never followed, so supporting material stays next to the point it supports or gets cut. Keep it whole — `lint-ignore: length` in the frontmatter — only when every reader who surfaces this doc genuinely benefits from reading 100% of it, or it is one indivisible body of knowledge; then splitting just adds hops.';
78
+ function ignoresRule(fm, rule) {
79
+ const v = fm['lint-ignore'];
80
+ return v === rule || (Array.isArray(v) && v.includes(rule));
81
+ }
82
+ function countBodyWords(body) {
83
+ const trimmed = body.trim();
84
+ return trimmed === '' ? 0 : trimmed.split(/\s+/).length;
85
+ }
86
+ /** The length rule. Caps come from the parsed entries — an invalid entry already
87
+ * fails the schema check, so it simply matches no cap here. `docName` is the
88
+ * doc's canonical identity; persona layers under `kinds/` are never capped. */
89
+ export function lintBodyLength(fm, body, docName) {
90
+ if (ignoresRule(fm, 'length'))
91
+ return null;
92
+ if (docName === 'kinds' || docName.startsWith('kinds/'))
93
+ return null;
94
+ const entries = parsedSubstrateSurfaces(fm);
95
+ const words = countBodyWords(body);
96
+ if (entries.some((e) => e.on === 'boot' && e.at === 'content') && words > BOOT_CONTENT_MAX_WORDS) {
97
+ return `body is ${words} words but a boot entry at \`content\` inlines every word into every agent's system prompt — capped at ${BOOT_CONTENT_MAX_WORDS} words (boot preview gets ${BOOT_PREVIEW_MAX_WORDS}; name entries are never capped). ${LENGTH_REMEDY}`;
98
+ }
99
+ const contentEvents = [...new Set(entries.filter((e) => e.on !== 'boot' && e.at === 'content').map((e) => e.on))];
100
+ if (contentEvents.length > 0 && words > EVENT_CONTENT_MAX_WORDS) {
101
+ return `body is ${words} words, over the ${EVENT_CONTENT_MAX_WORDS}-word cap for a \`content\` entry on ${contentEvents.join('/')} (the whole body delivers every time the entry fires; name entries are never capped). ${LENGTH_REMEDY}`;
102
+ }
103
+ if (entries.some((e) => e.on === 'boot' && e.at === 'preview') && words > BOOT_PREVIEW_MAX_WORDS) {
104
+ return `body is ${words} words, over the ${BOOT_PREVIEW_MAX_WORDS}-word cap for boot preview (the routing line invites every reader into the whole body, so the cap is the longest doc worth reading end-to-end; boot content is capped at ${BOOT_CONTENT_MAX_WORDS} words; name entries are never capped). ${LENGTH_REMEDY}`;
105
+ }
106
+ return null;
107
+ }
108
+ /** Warn when a body short enough to inline still pays a routing line. */
109
+ export function lintShortPreviewBody(fm, body) {
110
+ const words = countBodyWords(body);
111
+ if (words >= PREVIEW_TO_CONTENT_MAX_WORDS)
112
+ return null;
113
+ const previewEvents = [...new Set(parsedSubstrateSurfaces(fm).filter((e) => e.at === 'preview').map((e) => e.on))];
114
+ if (previewEvents.length === 0)
115
+ return null;
116
+ const noun = previewEvents.length === 1 ? 'entry delivers' : 'entries deliver';
117
+ return `body is ${words} words but the ${previewEvents.join('/')} ${noun} \`preview\`; use \`at: content\` so agents receive the whole rule without a separate memory read`;
118
+ }
119
+ // ---------------------------------------------------------------------------
120
+ // Reference resolution: what a `[[link]]` or a `memory-read` route may name.
121
+ // ---------------------------------------------------------------------------
122
+ /** Every canonical name a reference may target in a corpus: each document's
123
+ * exact identity plus every canonical directory, because reading a directory
124
+ * answers with its own document and its listing. Derived from the canonical
125
+ * tree, never from string prefixes of a name. */
126
+ export function resolvableCanonicalNames(docs) {
127
+ const names = new Set();
128
+ const walk = (node) => {
129
+ if (node.name !== '')
130
+ names.add(node.name);
131
+ for (const child of node.childDirectories)
132
+ walk(child);
133
+ for (const child of node.childDocuments)
134
+ names.add(child.name);
135
+ };
136
+ walk(buildMemoryTree(docs).root);
137
+ return names;
138
+ }
139
+ const FRONT_DOOR_REMEDY = 'the store\'s root INDEX.md is the workspace front door: give it `surfaces: [{on: workspace-open, at: content}, {on: read, match: "./**", at: content}]` (run `crtr memory write -h` first)';
140
+ const GLOB_META_RE = /[*?[\]{}]/;
141
+ function safeGlob(target, glob) {
142
+ try {
143
+ return matchesGlob(target, glob);
144
+ }
145
+ catch {
146
+ return false;
147
+ }
148
+ }
149
+ /** The exact canonical name a WILDCARD-FREE `memory-read` glob names. A `./`
150
+ * glob is relative to the carrier's routing anchor — its own canonical name
151
+ * when it is its directory's document, else the canonical directory it sits
152
+ * in. */
153
+ function literalRouteTarget(glob, routingAnchor) {
154
+ const rest = glob.startsWith('./') ? glob.slice(2) : glob;
155
+ const absolute = glob.startsWith('./') ? `${routingAnchor}/${rest}` : rest;
156
+ return canonicalSegments(normalizeDocName(absolute)).join('/');
157
+ }
158
+ function routeMatchesAny(glob, routingAnchor, names) {
159
+ if (!glob.startsWith('./')) {
160
+ for (const name of names)
161
+ if (safeGlob(name, glob))
162
+ return true;
163
+ return false;
164
+ }
165
+ const rest = glob.slice(2);
166
+ const prefix = routingAnchor === '' ? '' : `${routingAnchor}/`;
167
+ for (const name of names) {
168
+ if (!name.startsWith(prefix))
169
+ continue;
170
+ if (safeGlob(name.slice(prefix.length), rest))
171
+ return true;
172
+ }
173
+ return false;
174
+ }
175
+ /** The tail a not-found reference should be searched by, plus the `/INDEX`
176
+ * diagnostic when the reference still uses the retired directory spelling. */
177
+ function missingNameDiagnostic(name) {
178
+ const segments = canonicalSegments(name);
179
+ const collapsedIndex = segments[segments.length - 1] === INDEX_SEGMENT;
180
+ const collapsed = collapseTrailingIndex(name);
181
+ const leaf = canonicalSegments(collapsed).pop() ?? name;
182
+ const indexNote = collapsedIndex
183
+ ? ` A directory's own document answers at the directory name, so name \`${collapsed}\` instead.`
184
+ : '';
185
+ return `${indexNote} Run \`crtr memory find ${leaf}\` for the canonical name, or drop the reference.`;
186
+ }
187
+ /** Files a store holds but the substrate never loads as documents: `SKILL.md`
188
+ * is an Agent Skill bundle and `MEMORY.md` an index file. They are YAML-parsed
189
+ * so a broken one is still caught, and nothing else applies to them. */
190
+ const NON_DOCUMENT_FILES = new Set(['SKILL.md', 'MEMORY.md']);
191
+ /** Lint ONE physical store, whether or not the runtime mounts it. An undeclared
192
+ * or invalid project store still has its files checked — every store-local rule
193
+ * holds before a namespace exists — but its references are deferred, because
194
+ * the identities its links resolve against are undetermined until migration
195
+ * declares the namespace. */
196
+ export function lintMemoryStore(store, options = {}) {
197
+ const findings = [];
198
+ const base = {
199
+ scope: store.scope,
200
+ ...(store.storeRoot === '' ? {} : { storeRoot: store.storeRoot }),
201
+ };
202
+ const add = (severity, rule, path, message, extra = {}) => {
203
+ findings.push({ severity, rule, path, message, ...base, ...extra });
204
+ };
205
+ const mounted = store.mountStatus === 'ready';
206
+ if (store.mountFailure === 'collision') {
207
+ add('error', 'owner-path-collision', store.namespacePath ?? store.storeRoot, store.diagnostic ?? `project memory stores have owner directories that normalize to the same effective prefix \`${store.namespace}\` — rename one owner directory`);
208
+ }
209
+ else if (store.mountStatus === 'undeclared' || store.mountStatus === 'invalid') {
210
+ add('error', 'store-namespace', store.namespacePath ?? store.storeRoot, store.diagnostic ?? 'project memory store does not mount');
211
+ }
212
+ if (store.mountStatus === 'undeclared' || store.mountStatus === 'invalid') {
213
+ if (options.resolvable !== undefined) {
214
+ add('notice', 'reference-check-deferred', store.storeRoot, 'links and `memory-read` routes are not checked here: the canonical identities they resolve against are undetermined until this store declares its namespace');
215
+ }
216
+ }
217
+ const isProjectStore = store.scope === 'project' && store.plugin === undefined;
218
+ const frontDoorMode = options.frontDoor ?? 'ignore';
219
+ const frontDoors = [];
220
+ // Documents as the runtime loads them, keyed by absolute path: the walk below
221
+ // owns file-level checks (including the files loading drops), these own every
222
+ // identity-level one. Hidden dirs are excluded from both.
223
+ const docs = loadStoreMemoryDocs(store, true).filter((doc) => !doc.physicalRelativePath.split('/').some((segment) => segment.startsWith('.')));
224
+ const docsByPath = new Map(docs.map((doc) => [doc.path, doc]));
225
+ let checked = 0;
226
+ let documents = 0;
227
+ for (const file of walkFiles(store.storeRoot, (n) => n.endsWith('.md'), (d) => d.startsWith('.'))) {
228
+ const relPath = relative(store.storeRoot, file).split(sep).join('/');
229
+ if (relPath === '')
230
+ continue;
231
+ checked += 1;
232
+ let fm;
233
+ let body;
234
+ try {
235
+ ({ data: fm, body } = parseFrontmatterGeneric(readText(file)));
236
+ }
237
+ catch (e) {
238
+ add('error', 'yaml', file, `invalid YAML frontmatter: ${(e instanceof Error ? e.message : String(e)).split('\n')[0]}`);
239
+ continue;
240
+ }
241
+ if (NON_DOCUMENT_FILES.has(basename(file)))
242
+ continue;
243
+ documents += 1;
244
+ const isRootFile = localNameFromPath(relPath) === '';
245
+ const doc = docsByPath.get(file);
246
+ // A file the loader dropped (a root INDEX.md composing to the empty name)
247
+ // carries no canonical identity, but its frontmatter contract still holds —
248
+ // the field rules below run before the identity-dependent ones.
249
+ const named = doc === undefined ? {} : { name: doc.name };
250
+ const schemaError = lintSubstrateFrontmatter(fm);
251
+ if (schemaError !== null)
252
+ add('error', 'schema', file, schemaError, named);
253
+ if (fm !== null) {
254
+ const isRepositoryRootStore = isProjectStore && store.ownerRelativePath === '';
255
+ if (fm['namespace'] !== undefined && !(isRootFile && isRepositoryRootStore)) {
256
+ const message = isRootFile && isProjectStore && store.ownerRelativePath !== undefined && store.ownerRelativePath !== ''
257
+ ? `\`namespace:\` belongs only on the repository-root store's ${INDEX_SEGMENT}.md (${store.namespacePath ?? store.storeRoot}) — a nested store's prefix is derived from its path under ${store.repositoryRoot ?? store.ownerDir ?? store.storeRoot}`
258
+ : `\`namespace:\` belongs only on a project store's root ${INDEX_SEGMENT}.md, where it declares the whole store's prefix — drop it here (an explicit \`name:\` is store-LOCAL and never carries a namespace)`;
259
+ add('error', 'namespace-placement', file, message, named);
260
+ }
261
+ if (isRootFile && fm['name'] !== undefined) {
262
+ add('error', 'root-name', file, `a store's root ${INDEX_SEGMENT}.md carries no \`name:\` — its identity answers at \`${store.namespace}\`; drop the field`, named);
263
+ }
264
+ }
265
+ if (doc === undefined) {
266
+ // In a project store the missing/invalid declaration is already the finding.
267
+ if (isRootFile && !isProjectStore) {
268
+ add('error', 'root-index-unaddressable', file, `a root ${INDEX_SEGMENT}.md has no canonical name in a ${store.scope} store, which declares no namespace — only a project store's root document answers at its namespace, so rename this file to a named document (\`<topic>.md\`) or fold its content into the docs it introduces`);
269
+ }
270
+ continue;
271
+ }
272
+ if (fm !== null) {
273
+ if (!isRootFile && fm['name'] !== undefined) {
274
+ const raw = fm['name'];
275
+ if (typeof raw !== 'string' || raw.trim() === '') {
276
+ add('error', 'local-name', file, `invalid name: ${JSON.stringify(raw)} (expected a non-empty store-local name)`, named);
277
+ }
278
+ else {
279
+ // Validated as WRITTEN: normalizing first would silently accept an
280
+ // `NN-` ordering prefix, which is physical-path-only. The suggestion
281
+ // is the normalized spelling.
282
+ const valid = validateExplicitLocalName(raw.trim(), store.namespace);
283
+ if (!valid.ok) {
284
+ const suggested = suggestedLocalName(normalizeDocName(raw.trim()), store.namespace, relPath);
285
+ add('error', 'local-name', file, `invalid name \`${raw}\`: ${valid.reason} — ${suggested}`, named);
286
+ }
287
+ }
288
+ }
289
+ for (const issue of validateMemoryExtensionValues(fm['extensions'], memoryExtensionValidationCatalog(doc))) {
290
+ add('error', 'extension', file, `${issue.path}: ${issue.message}`, named);
291
+ }
292
+ const lengthError = lintBodyLength(fm, body, doc.name);
293
+ if (lengthError !== null)
294
+ add('error', 'length', file, lengthError, named);
295
+ const shortPreview = lintShortPreviewBody(fm, body);
296
+ if (shortPreview !== null)
297
+ add('warning', 'short-preview', file, shortPreview, named);
298
+ const entries = parsedSubstrateSurfaces(fm);
299
+ if (options.nestedStore === true && entries.some((e) => e.on === 'boot')) {
300
+ add('warning', 'nested-store-boot', file, 'nested-store docs never ride the boot catalog, so its boot surfaces entries are inert — drop them', named);
301
+ }
302
+ if (isProjectStore && entries.some((e) => e.on === 'workspace-open' && e.at === 'content')) {
303
+ const complete = entries.some((entry) => {
304
+ if (entry.on !== 'read' || entry.at !== 'content')
305
+ return false;
306
+ return entry.match?.includes('./**') === true;
307
+ });
308
+ frontDoors.push({ path: file, root: isRootFile, complete });
309
+ }
310
+ for (const entry of entries) {
311
+ if (entry.on !== 'memory-read')
312
+ continue;
313
+ lintMemoryReadEntry(entry, doc, fm, options.resolvable, mounted, add);
314
+ }
315
+ }
316
+ if (options.resolvable !== undefined && mounted) {
317
+ for (const name of docLinkNames(body)) {
318
+ if (options.resolvable.has(name))
319
+ continue;
320
+ add('error', 'dangling-link', file, `dangling doc link [[${name}]]: no memory document or directory in this target view has that exact canonical name.${missingNameDiagnostic(name)}`, named);
321
+ }
322
+ }
323
+ }
324
+ // Same-store canonical collisions. The loader already orders `foo/INDEX.md`
325
+ // ahead of `foo.md`, so the first candidate is the deterministic read winner.
326
+ const byName = new Map();
327
+ for (const doc of docs) {
328
+ const bucket = byName.get(doc.name);
329
+ if (bucket)
330
+ bucket.push(doc);
331
+ else
332
+ byName.set(doc.name, [doc]);
333
+ }
334
+ for (const [name, candidates] of byName) {
335
+ if (candidates.length < 2)
336
+ continue;
337
+ const paths = candidates.map((doc) => doc.path);
338
+ add('error', 'canonical-collision', paths[0], `${candidates.length} files in this store own canonical name \`${name}\` (${paths.join(', ')}); \`${candidates[0].physicalRelativePath}\` is the deterministic read winner. Recover the collision with \`crtr memory move ${name} --to <new-free-name>\`; move selects the first physical path in stable lexical order, and no filesystem surgery is needed.`, { name, paths });
339
+ }
340
+ if (isProjectStore) {
341
+ for (const door of frontDoors) {
342
+ if (door.root)
343
+ continue;
344
+ add('error', 'front-door', door.path, `a project store's workspace front door is its root ${INDEX_SEGMENT}.md, not this doc — a {on: workspace-open, at: content} entry here delivers a second whole document at every workspace open; fold it into the root document or lower this entry`);
345
+ }
346
+ const repositoryRoot = (store.ownerRelativePath ?? '') === '';
347
+ const hasRootDoor = frontDoors.some((door) => door.root && door.complete);
348
+ if (repositoryRoot && !hasRootDoor && frontDoorMode !== 'ignore') {
349
+ const owner = store.ownerDir ?? store.storeRoot;
350
+ const message = frontDoorMode === 'required'
351
+ ? `the selected profile manages this project but its store has no workspace front door — ${FRONT_DOOR_REMEDY}`
352
+ : `this project store has no workspace front door, so agents open the workspace blind — ${FRONT_DOOR_REMEDY}`;
353
+ add(frontDoorMode === 'required' ? 'error' : 'warning', 'front-door', owner, message);
354
+ }
355
+ }
356
+ return makeResult(findings, checked, documents, 1);
357
+ }
358
+ /** The local spelling an invalid explicit `name:` should use: dropping the field
359
+ * entirely when the physical path already derives the same identity. */
360
+ function suggestedLocalName(local, namespace, physicalRelativePath) {
361
+ let fixed = collapseTrailingIndex(local);
362
+ if (namespace !== '') {
363
+ const nsSegments = canonicalSegments(namespace);
364
+ const segments = canonicalSegments(fixed);
365
+ if (nsSegments.every((s, i) => segments[i] === s))
366
+ fixed = segments.slice(nsSegments.length).join('/');
367
+ }
368
+ if (fixed === '') {
369
+ return `remove the field: this document's identity would be the store root's, which only the root ${INDEX_SEGMENT}.md owns`;
370
+ }
371
+ return fixed === localNameFromPath(physicalRelativePath)
372
+ ? `drop the field — its physical path already derives \`${fixed}\``
373
+ : `use \`name: ${fixed}\``;
374
+ }
375
+ function lintMemoryReadEntry(entry, doc, fm, resolvable, mounted, add) {
376
+ for (const glob of entry.match ?? []) {
377
+ if ((glob === '**' || glob === '*') && !ignoresRule(fm, 'broad-memory-read')) {
378
+ add('warning', 'broad-memory-read', doc.path, `memory-read glob \`${glob}\` fires on every memory read — scope it to a name subtree`, { name: doc.name });
379
+ continue;
380
+ }
381
+ if (resolvable === undefined || !mounted)
382
+ continue;
383
+ if (!GLOB_META_RE.test(glob)) {
384
+ const target = literalRouteTarget(glob, doc.routingAnchor);
385
+ if (!resolvable.has(target)) {
386
+ add('error', 'memory-read-route', doc.path, `memory-read route \`${glob}\` names \`${target}\`, which is no document or directory in this target view, so the entry can never fire.${missingNameDiagnostic(target)}`, { name: doc.name });
387
+ }
388
+ continue;
389
+ }
390
+ if (!routeMatchesAny(glob, doc.routingAnchor, resolvable)) {
391
+ add('warning', 'memory-read-route', doc.path, `memory-read glob \`${glob}\`${glob.startsWith('./') ? ` (anchored at \`${doc.routingAnchor}\`)` : ''} matches no canonical name in this target view — a project document's name carries its store's namespace, so an unqualified subtree glob no longer matches`, { name: doc.name });
392
+ }
393
+ }
394
+ }
395
+ function ambientTarget() {
396
+ return {
397
+ cwd: process.cwd(),
398
+ profileId: process.env['CRTR_PROFILE_ID'] || null,
399
+ nodeId: process.env['CRTR_NODE_ID'] || null,
400
+ };
401
+ }
402
+ /** Lint every store a target sees, then the diagnostics only the merged view
403
+ * produces: references resolved against the view's canonical names, and equal
404
+ * canonical identities held by several stores. */
405
+ export function lintMemoryTarget(options = {}) {
406
+ const target = options.target ?? ambientTarget();
407
+ const includeDescendants = options.includeDescendants ?? true;
408
+ const view = loadMemoryTargetView(target, {
409
+ ...(options.scope === undefined ? {} : { scope: options.scope }),
410
+ includeDescendants,
411
+ quiet: true,
412
+ });
413
+ const resolvable = resolvableCanonicalNames(view.docs);
414
+ const nestedStores = new Set(includeDescendants
415
+ ? descendantStoreRoots(projectScopeRoots(target.cwd, target.profileId)).map((root) => realpathOrSelf(join(root, 'memory')))
416
+ : []);
417
+ // Profile coverage: every project the selected profile manages carries a
418
+ // workspace front door. A managed project with no store at all still owes one.
419
+ const coverage = options.scope === undefined || options.scope === 'project';
420
+ const managed = new Set();
421
+ const managedRepositories = new Set();
422
+ if (coverage && target.profileId !== null && target.profileId !== '') {
423
+ try {
424
+ const { manifest } = loadProfileManifest(target.profileId);
425
+ for (const project of manifest.projects) {
426
+ const owner = realpathOrSelf(project.path);
427
+ managed.add(owner);
428
+ const association = associateRepository(owner);
429
+ managedRepositories.add(association.ok ? association.association.repositoryRoot : owner);
430
+ }
431
+ }
432
+ catch {
433
+ // Missing/deleted/invalid selected profile: no managed-project coverage.
434
+ }
435
+ }
436
+ const cwdReal = realpathOrSelf(target.cwd);
437
+ const findings = [];
438
+ let checked = 0;
439
+ let documents = 0;
440
+ let storesLinted = 0;
441
+ const linted = new Set();
442
+ for (const store of view.stores) {
443
+ const owner = store.ownerDir === undefined ? null : realpathOrSelf(store.ownerDir);
444
+ const repositoryRoot = store.repositoryRoot ?? owner;
445
+ if (repositoryRoot !== null && repositoryRoot !== undefined)
446
+ linted.add(repositoryRoot);
447
+ const nested = store.ownerRelativePath !== undefined && store.ownerRelativePath !== '';
448
+ const frontDoor = nested || !coverage || owner === null
449
+ ? 'ignore'
450
+ : managedRepositories.has(repositoryRoot ?? owner)
451
+ ? 'required'
452
+ : managed.size === 0 && owner === cwdReal
453
+ ? 'advisory'
454
+ : 'ignore';
455
+ const result = lintMemoryStore(store, {
456
+ resolvable,
457
+ frontDoor,
458
+ nestedStore: nestedStores.has(realpathOrSelf(store.storeRoot)),
459
+ });
460
+ findings.push(...result.findings);
461
+ checked += result.checked;
462
+ documents += result.documents;
463
+ storesLinted += result.storesLinted;
464
+ }
465
+ if (coverage) {
466
+ // A managed project whose directory holds no `.crouter/` never became a
467
+ // store in the view, and still owes a front door at its repository root.
468
+ for (const owner of managed) {
469
+ const association = associateRepository(owner);
470
+ const repositoryRoot = association.ok ? association.association.repositoryRoot : owner;
471
+ if (linted.has(repositoryRoot))
472
+ continue;
473
+ const result = lintMemoryStore(openProjectMemoryStore(repositoryRoot), { resolvable, frontDoor: 'required' });
474
+ findings.push(...result.findings);
475
+ checked += result.checked;
476
+ documents += result.documents;
477
+ storesLinted += result.storesLinted;
478
+ linted.add(repositoryRoot);
479
+ }
480
+ const cwdAssociation = associateRepository(cwdReal);
481
+ const cwdRepositoryRoot = cwdAssociation.ok ? cwdAssociation.association.repositoryRoot : cwdReal;
482
+ if (managed.size === 0 && !linted.has(cwdRepositoryRoot) && pathExists(join(target.cwd, '.crouter'))) {
483
+ const result = lintMemoryStore(openProjectMemoryStore(target.cwd), { resolvable, frontDoor: 'advisory' });
484
+ findings.push(...result.findings);
485
+ checked += result.checked;
486
+ documents += result.documents;
487
+ storesLinted += result.storesLinted;
488
+ }
489
+ }
490
+ // Equal canonical identities across stores are legitimate — a linked worktree
491
+ // and its main checkout declare one namespace on purpose — so they are
492
+ // reported with the view's winner and every ordered candidate, never failed.
493
+ const tree = buildMemoryTree(view.docs);
494
+ const walk = (node) => {
495
+ const candidates = node.documentCandidates;
496
+ if (candidates.length > 1 && new Set(candidates.map((doc) => doc.root)).size > 1) {
497
+ findings.push({
498
+ severity: 'notice',
499
+ rule: 'cross-store-candidates',
500
+ path: candidates[0].path,
501
+ name: node.name,
502
+ paths: candidates.map((doc) => doc.path),
503
+ message: `canonical name \`${node.name}\` is held by ${candidates.length} stores; this target view reads ${candidates[0].path} (${candidates[0].scope}) and the later candidates stay reachable with \`crtr memory read ${node.name} --dir <project>\``,
504
+ });
505
+ }
506
+ for (const child of node.childDirectories)
507
+ walk(child);
508
+ for (const child of node.childDocuments)
509
+ walk(child);
510
+ };
511
+ walk(tree.root);
512
+ return {
513
+ ...makeResult(findings, checked, documents, storesLinted),
514
+ stores: view.stores,
515
+ profileProjects: managed.size,
516
+ };
517
+ }
@@ -0,0 +1,31 @@
1
+ export type ProjectNamespaceSource =
2
+ /** The store root's existing explicit `name`. */
3
+ 'root-name'
4
+ /** Git common-repository label plus the owner's worktree-relative path. */
5
+ | 'git-worktree'
6
+ /** H1 title of the store root's guide body. */
7
+ | 'root-guide-h1'
8
+ /** The owner directory's own basename. */
9
+ | 'owner-basename';
10
+ export type ProjectNamespaceDerivation = {
11
+ ok: true;
12
+ namespace: string;
13
+ source: ProjectNamespaceSource;
14
+ } | {
15
+ ok: false;
16
+ reason: string;
17
+ };
18
+ export interface ProjectNamespaceInput {
19
+ /** The project directory containing `.crouter/` — not the memory dir. */
20
+ ownerDir: string;
21
+ /** Frontmatter of the store's root `INDEX.md`, when it has one. */
22
+ rootFrontmatter?: Record<string, unknown> | null;
23
+ /** Body of the store's root `INDEX.md`, when it has one. */
24
+ rootBody?: string;
25
+ }
26
+ /** Derive one project store's namespace: its existing root `name` first, else
27
+ * the git repository label plus the owner's path within its worktree, else the
28
+ * root guide's H1, else the owner basename. An existing root `name` that
29
+ * cannot be a namespace fails rather than falling through — a declared
30
+ * identity is never silently replaced. */
31
+ export declare function deriveProjectNamespace(input: ProjectNamespaceInput): ProjectNamespaceDerivation;
@@ -0,0 +1,85 @@
1
+ // project-namespace.ts — the ONE-TIME derivation of a project store's
2
+ // namespace, used by migration and the guidance producers that may initialize a
3
+ // store. The runtime NEVER calls this: it reads the `namespace:` declaration on
4
+ // a store's root INDEX.md and refuses to mount a store that has none, so a
5
+ // store's identity cannot depend on cwd, git state, or discovery order after it
6
+ // has already delivered documents.
7
+ import { basename, dirname, relative, resolve, sep } from 'node:path';
8
+ import { realpathOrSelf } from '../fs-utils.js';
9
+ import { gitSync } from '../git.js';
10
+ import { collapseTrailingIndex, normalizeDocName, slugCanonicalPath, validateNamespace } from './identity.js';
11
+ /** Derive one project store's namespace: its existing root `name` first, else
12
+ * the git repository label plus the owner's path within its worktree, else the
13
+ * root guide's H1, else the owner basename. An existing root `name` that
14
+ * cannot be a namespace fails rather than falling through — a declared
15
+ * identity is never silently replaced. */
16
+ export function deriveProjectNamespace(input) {
17
+ const ownerDir = resolve(input.ownerDir);
18
+ const rootName = input.rootFrontmatter?.['name'];
19
+ if (typeof rootName === 'string' && rootName.trim() !== '') {
20
+ // Lifted verbatim (only ordering prefixes and a trailing INDEX removed) —
21
+ // an already-authored identity is an address, not a label to re-slug.
22
+ const lifted = collapseTrailingIndex(normalizeDocName(rootName.trim()));
23
+ const check = validateNamespace(lifted);
24
+ if (!check.ok)
25
+ return { ok: false, reason: `root \`name: ${rootName.trim()}\` cannot become a namespace: ${check.reason}` };
26
+ return { ok: true, namespace: lifted, source: 'root-name' };
27
+ }
28
+ const fromGit = gitNamespace(ownerDir);
29
+ if (fromGit !== null)
30
+ return validated(fromGit, 'git-worktree');
31
+ const h1 = input.rootBody === undefined ? undefined : h1Title(input.rootBody);
32
+ if (h1 !== undefined)
33
+ return validated(slugCanonicalPath(h1), 'root-guide-h1');
34
+ return validated(slugCanonicalPath(basename(ownerDir) || ownerDir), 'owner-basename');
35
+ }
36
+ function validated(namespace, source) {
37
+ const check = validateNamespace(namespace);
38
+ return check.ok ? { ok: true, namespace, source } : { ok: false, reason: `derived namespace \`${namespace}\` is invalid: ${check.reason}` };
39
+ }
40
+ /** `<repo-label>/<owner path within its worktree>`, or `null` outside a git
41
+ * working tree. The label comes from `--git-common-dir`, which resolves a
42
+ * LINKED WORKTREE to the shared repo storage, so a canvas worktree checked out
43
+ * under a node-id path shares its main checkout's namespace. */
44
+ function gitNamespace(ownerDir) {
45
+ const label = gitRepoLabel(ownerDir);
46
+ if (label === null)
47
+ return null;
48
+ const top = gitWorktreeRoot(ownerDir);
49
+ if (top === null)
50
+ return null;
51
+ // `--show-toplevel` resolves through symlinks (macOS /tmp -> /private/tmp);
52
+ // realpath both sides so a symlinked owner doesn't produce a `../..` suffix.
53
+ const rel = relative(realpathOrSelf(top), realpathOrSelf(ownerDir)).split(sep).join('/');
54
+ if (rel.startsWith('..'))
55
+ return null;
56
+ return rel === '' || rel === '.' ? slugCanonicalPath(label) : slugCanonicalPath(`${label}/${rel}`);
57
+ }
58
+ function gitRepoLabel(dir) {
59
+ const res = gitSync(['rev-parse', '--path-format=absolute', '--git-common-dir'], dir);
60
+ if (res.status !== 0)
61
+ return null;
62
+ const gitCommonDir = res.stdout.trim();
63
+ if (gitCommonDir === '')
64
+ return null;
65
+ return basename(dirname(gitCommonDir)) || null;
66
+ }
67
+ function gitWorktreeRoot(dir) {
68
+ const res = gitSync(['rev-parse', '--path-format=absolute', '--show-toplevel'], dir);
69
+ if (res.status !== 0)
70
+ return null;
71
+ const top = res.stdout.trim();
72
+ return top === '' ? null : resolve(top);
73
+ }
74
+ /** First Markdown H1 in a body, heading marker stripped. */
75
+ function h1Title(body) {
76
+ for (const raw of body.split('\n')) {
77
+ const m = raw.match(/^#\s+(.+)$/);
78
+ if (m) {
79
+ const title = m[1].replace(/\s+/g, ' ').trim();
80
+ if (title !== '')
81
+ return title;
82
+ }
83
+ }
84
+ return undefined;
85
+ }
@@ -0,0 +1,31 @@
1
+ export type RepositoryKind = 'git' | 'non-git';
2
+ export interface RepositoryAssociation {
3
+ kind: RepositoryKind;
4
+ repositoryRoot: string;
5
+ repositoryKey: string;
6
+ ownerRelativePath: string;
7
+ declarationPath: string;
8
+ }
9
+ export type RepositoryAssociationFailureCode = 'no-project-root' | 'git-lookup-failed' | 'owner-outside-root' | 'owner-path-invalid';
10
+ export type RepositoryAssociationResult = {
11
+ ok: true;
12
+ association: RepositoryAssociation;
13
+ } | {
14
+ ok: false;
15
+ code: RepositoryAssociationFailureCode;
16
+ ownerDir: string;
17
+ repositoryRoot?: string;
18
+ reason: string;
19
+ };
20
+ /** Normalize a POSIX-slash relative owner path into canonical segments. */
21
+ export declare function normalizeOwnerRelativePath(relPosix: string): {
22
+ ok: true;
23
+ path: string;
24
+ } | {
25
+ ok: false;
26
+ reason: string;
27
+ };
28
+ /** Associate one physical project-store owner with its repository identity. */
29
+ export declare function associateRepository(ownerDir: string): RepositoryAssociationResult;
30
+ /** Clear successful associations; failures are deliberately never cached. */
31
+ export declare function resetRepositoryAssociationCache(): void;