@north-light/crouter 0.3.353 → 0.3.354

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 (609) hide show
  1. package/dist/api/client.d.ts +35 -25
  2. package/dist/api/client.js +2 -2
  3. package/dist/api/dto/broker-ops.d.ts +2 -36
  4. package/dist/api/dto/canvas.d.ts +8 -13
  5. package/dist/api/dto/config.d.ts +4 -0
  6. package/dist/api/dto/delivery.d.ts +61 -0
  7. package/dist/api/dto/docs.d.ts +133 -0
  8. package/dist/api/dto/docs.js +1 -0
  9. package/dist/api/dto/health.d.ts +26 -79
  10. package/dist/api/dto/node-outcomes.d.ts +1 -3
  11. package/dist/api/dto/nodes.d.ts +5 -26
  12. package/dist/api/dto/objects.d.ts +167 -0
  13. package/dist/api/dto/objects.js +1 -0
  14. package/dist/api/dto/profiles.d.ts +14 -8
  15. package/dist/api/dto/reports.d.ts +9 -7
  16. package/dist/api/dto/reviews.d.ts +9 -3
  17. package/dist/api/dto/worktree.d.ts +1 -1
  18. package/dist/api/index.d.ts +0 -1
  19. package/dist/api/index.js +1 -1
  20. package/dist/api/routes.d.ts +14 -12
  21. package/dist/api/routes.js +1 -1
  22. package/dist/build-root.js +1 -1
  23. package/dist/builtin-memory/00-runtime-base/00-authoring.md +10 -5
  24. package/dist/builtin-memory/04-orchestration-kernel.md +7 -7
  25. package/dist/builtin-memory/05-kinds/advisor/01-orchestrator.md +1 -1
  26. package/dist/builtin-memory/05-kinds/explore/00-base.md +2 -2
  27. package/dist/builtin-memory/05-kinds/explore/01-orchestrator.md +2 -2
  28. package/dist/builtin-memory/crouter-concepts/INDEX.md +2 -2
  29. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  30. package/dist/builtin-memory/crouter-concepts/memory.md +15 -15
  31. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +1 -1
  32. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +5 -5
  33. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  34. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  35. package/dist/builtin-memory/crouter-sdk/INDEX.md +2 -2
  36. package/dist/builtin-memory/crouter-sdk/README.md +5 -6
  37. package/dist/builtin-memory/crouter-sdk/errors.md +0 -13
  38. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -1
  39. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +2 -2
  40. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -2
  41. package/dist/builtin-memory/crouter-sdk/resources.md +0 -1
  42. package/dist/builtin-memory/explore/exploration-doc.md +4 -4
  43. package/dist/builtin-memory/insights/capture.md +6 -6
  44. package/dist/builtin-memory/insights/init.md +14 -14
  45. package/dist/builtin-memory/internal/INDEX.md +4 -4
  46. package/dist/builtin-memory/internal/agent-shaping.md +20 -20
  47. package/dist/builtin-memory/internal/examples/imessage-assistant.md +2 -2
  48. package/dist/builtin-memory/internal/marketplaces.md +2 -2
  49. package/dist/builtin-memory/internal/memory-loading.md +31 -30
  50. package/dist/builtin-memory/internal/nodes-and-canvas.md +1 -1
  51. package/dist/builtin-memory/internal/plugins.md +16 -14
  52. package/dist/builtin-memory/internal/storage-tiers.md +4 -4
  53. package/dist/builtin-memory/memory-read-orientation.md +1 -1
  54. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +32 -40
  55. package/dist/clients/attach/input/controller.js +1 -1
  56. package/dist/clients/attach/input/ref-autocomplete.js +1 -1
  57. package/dist/clients/attach/input/titled-editor.js +1 -1
  58. package/dist/clients/attach/render/chat-view.js +1 -1
  59. package/dist/clients/attach/render/crtr-output.d.ts +1 -2
  60. package/dist/clients/attach/render/crtr-output.js +17 -17
  61. package/dist/clients/attach/render/group-activity.d.ts +8 -8
  62. package/dist/clients/attach/render/group-activity.js +2 -2
  63. package/dist/clients/attach/render/group-recap.js +1 -1
  64. package/dist/clients/attach/render/tool-calls.d.ts +1 -1
  65. package/dist/clients/attach/session/profile-files.js +1 -1
  66. package/dist/clients/attach/slash/dispatch.js +1 -1
  67. package/dist/clients/attach/viewer.js +806 -1553
  68. package/dist/commands/api-client.d.ts +2 -0
  69. package/dist/commands/api-client.js +3 -3
  70. package/dist/commands/canvas/edges.d.ts +2 -0
  71. package/dist/commands/canvas/edges.js +2 -0
  72. package/dist/commands/canvas/list.d.ts +4 -0
  73. package/dist/commands/canvas/list.js +3 -0
  74. package/dist/commands/canvas/read.d.ts +8 -0
  75. package/dist/commands/canvas/read.js +5 -0
  76. package/dist/commands/canvas/search.d.ts +2 -0
  77. package/dist/commands/canvas/search.js +3 -0
  78. package/dist/commands/canvas/unwatch.d.ts +2 -0
  79. package/dist/commands/canvas/unwatch.js +1 -0
  80. package/dist/commands/canvas/watch.d.ts +3 -0
  81. package/dist/commands/canvas/watch.js +1 -0
  82. package/dist/commands/canvas-analytics.js +1 -1
  83. package/dist/commands/canvas-history/grep.js +4 -4
  84. package/dist/commands/canvas-history/read.js +2 -2
  85. package/dist/commands/canvas-history/search.js +7 -7
  86. package/dist/commands/canvas-history/shared.d.ts +0 -1
  87. package/dist/commands/canvas-history/shared.js +1 -1
  88. package/dist/commands/canvas-history/stats.js +2 -2
  89. package/dist/commands/canvas-history.js +1 -1
  90. package/dist/commands/canvas.js +1 -1
  91. package/dist/commands/doc/delete.d.ts +2 -0
  92. package/dist/commands/doc/delete.js +1 -0
  93. package/dist/commands/doc/edit.d.ts +2 -0
  94. package/dist/commands/doc/edit.js +1 -0
  95. package/dist/commands/doc/history.d.ts +2 -0
  96. package/dist/commands/doc/history.js +2 -0
  97. package/dist/commands/doc/lint.d.ts +2 -0
  98. package/dist/commands/doc/lint.js +2 -0
  99. package/dist/commands/doc/list.d.ts +2 -0
  100. package/dist/commands/doc/list.js +1 -0
  101. package/dist/commands/doc/move.d.ts +2 -0
  102. package/dist/commands/doc/move.js +1 -0
  103. package/dist/commands/doc/read.d.ts +2 -0
  104. package/dist/commands/doc/read.js +1 -0
  105. package/dist/commands/doc/shared.d.ts +25 -0
  106. package/dist/commands/doc/shared.js +2 -0
  107. package/dist/commands/doc/write.d.ts +2 -0
  108. package/dist/commands/doc/write.js +1 -0
  109. package/dist/commands/{memory.d.ts → doc.d.ts} +1 -1
  110. package/dist/commands/doc.js +1 -0
  111. package/dist/commands/human/review.js +1 -1
  112. package/dist/commands/node/bash.js +2 -2
  113. package/dist/commands/node/create.js +1 -1
  114. package/dist/commands/node/inspect.js +10 -10
  115. package/dist/commands/node/lifecycle.js +2 -2
  116. package/dist/commands/node/outcome.js +1 -1
  117. package/dist/commands/node/subscription.js +1 -1
  118. package/dist/commands/node-context.js +2 -2
  119. package/dist/commands/pkg/browse/catalog.js +1 -1
  120. package/dist/commands/pkg/browse/doc-view.js +1 -1
  121. package/dist/commands/pkg/browse/model.d.ts +9 -17
  122. package/dist/commands/pkg/plugin-inspect.js +1 -1
  123. package/dist/commands/pkg/plugin-manage.d.ts +4 -8
  124. package/dist/commands/pkg/plugin-manage.js +15 -17
  125. package/dist/commands/profile/list.js +1 -1
  126. package/dist/commands/profile/new.js +1 -1
  127. package/dist/commands/profile/project.js +1 -1
  128. package/dist/commands/profile/show.js +1 -1
  129. package/dist/commands/push.js +3 -3
  130. package/dist/commands/sys/config.js +1 -1
  131. package/dist/commands/sys/context/admin/actions.d.ts +18 -43
  132. package/dist/commands/sys/context/admin/actions.js +1 -2
  133. package/dist/commands/sys/context/admin/detail-panel.d.ts +17 -25
  134. package/dist/commands/sys/context/admin/detail-panel.js +2 -1
  135. package/dist/commands/sys/context/admin/docs-panel.d.ts +7 -6
  136. package/dist/commands/sys/context/admin/docs-panel.js +1 -1
  137. package/dist/commands/sys/context/admin/list-view.d.ts +12 -12
  138. package/dist/commands/sys/context/admin/list-view.js +1 -1
  139. package/dist/commands/sys/context/admin/model.d.ts +96 -69
  140. package/dist/commands/sys/context/admin/model.js +1 -1
  141. package/dist/commands/sys/context/admin/rail-panel.d.ts +7 -5
  142. package/dist/commands/sys/context/admin/rail-panel.js +1 -1
  143. package/dist/commands/sys/context/admin/read-view.d.ts +10 -14
  144. package/dist/commands/sys/context/admin/read-view.js +1 -2
  145. package/dist/commands/sys/context/admin/shell.d.ts +26 -31
  146. package/dist/commands/sys/context/admin/shell.js +1 -1
  147. package/dist/commands/sys/context/admin.js +2 -2
  148. package/dist/commands/sys/context/doc.js +2 -3
  149. package/dist/commands/sys/context/expose.js +2 -2
  150. package/dist/commands/sys/context/prompt-review.js +4 -4
  151. package/dist/commands/sys/context/resolve.d.ts +92 -65
  152. package/dist/commands/sys/context/resolve.js +7 -9
  153. package/dist/commands/sys/context.js +1 -1
  154. package/dist/commands/sys/doctor.js +1 -1
  155. package/dist/commands/sys/migrate.js +1 -1
  156. package/dist/commands/sys/panels/profiles-panel.d.ts +3 -1
  157. package/dist/commands/sys/panels/profiles-panel.js +1 -1
  158. package/dist/commands/sys/sync-deps.d.ts +6 -11
  159. package/dist/commands/sys/sync-deps.js +7 -8
  160. package/dist/commands/sys/sync-project-guidance.js +5 -4
  161. package/dist/commands/sys/sync-shared.d.ts +41 -4
  162. package/dist/commands/sys/sync-shared.js +1 -1
  163. package/dist/commands/sys/sync-skills.js +2 -2
  164. package/dist/commands/sys/sync.js +1 -1
  165. package/dist/core/bash-job-supervisor.d.ts +2 -3
  166. package/dist/core/bash-job-supervisor.js +3 -3
  167. package/dist/core/bash-jobs.d.ts +0 -5
  168. package/dist/core/bash-jobs.js +7 -7
  169. package/dist/core/bootstrap.js +2 -2
  170. package/dist/core/canvas/canvas.d.ts +6 -50
  171. package/dist/core/canvas/canvas.js +16 -21
  172. package/dist/core/canvas/db.d.ts +4 -1
  173. package/dist/core/canvas/db.js +2 -2
  174. package/dist/core/canvas/history.d.ts +11 -39
  175. package/dist/core/canvas/history.js +9 -20
  176. package/dist/core/canvas/install-id.d.ts +2 -2
  177. package/dist/core/canvas/install-id.js +1 -1
  178. package/dist/core/canvas/memory-reads.d.ts +5 -0
  179. package/dist/core/canvas/memory-reads.js +1 -1
  180. package/dist/core/canvas/migrations.js +215 -41
  181. package/dist/core/canvas/node-agent-paths.js +1 -1
  182. package/dist/core/canvas/node-tokens.js +1 -1
  183. package/dist/core/canvas/paths.d.ts +0 -4
  184. package/dist/core/canvas/paths.js +1 -1
  185. package/dist/core/canvas/remote-canvas-source.d.ts +0 -1
  186. package/dist/core/canvas/remote-canvas-source.js +1 -1
  187. package/dist/core/canvas/render-source.d.ts +9 -6
  188. package/dist/core/canvas/render-source.js +6 -6
  189. package/dist/core/canvas/sessions.js +2 -2
  190. package/dist/core/canvas/source.d.ts +6 -0
  191. package/dist/core/canvas/tree.d.ts +29 -0
  192. package/dist/core/canvas/tree.js +12 -0
  193. package/dist/core/canvas/types.d.ts +0 -20
  194. package/dist/core/command-plugins/bundle.js +1 -1
  195. package/dist/core/config.d.ts +1 -1
  196. package/dist/core/conversation-store/listener.js +4 -2
  197. package/dist/core/feed/feed.d.ts +9 -7
  198. package/dist/core/feed/feed.js +3 -7
  199. package/dist/core/feed/inbox.d.ts +3 -5
  200. package/dist/core/feed/inbox.js +1 -10
  201. package/dist/core/feed/messages.d.ts +33 -6
  202. package/dist/core/feed/messages.js +10 -7
  203. package/dist/core/feed/reports.d.ts +10 -0
  204. package/dist/core/feed/reports.js +2 -0
  205. package/dist/core/grants/remove.js +1 -1
  206. package/dist/core/graph/access.d.ts +24 -0
  207. package/dist/core/graph/access.js +8 -0
  208. package/dist/core/graph/bodies.d.ts +6 -0
  209. package/dist/core/graph/bodies.js +1 -0
  210. package/dist/core/graph/deletion.d.ts +9 -0
  211. package/dist/core/graph/deletion.js +5 -0
  212. package/dist/core/graph/diff.d.ts +4 -0
  213. package/dist/core/graph/diff.js +4 -0
  214. package/dist/core/graph/documents.d.ts +160 -0
  215. package/dist/core/graph/documents.js +7 -0
  216. package/dist/core/graph/edges.d.ts +24 -0
  217. package/dist/core/graph/edges.js +1 -0
  218. package/dist/core/graph/events.d.ts +26 -0
  219. package/dist/core/graph/events.js +6 -0
  220. package/dist/core/graph/exposures.d.ts +53 -0
  221. package/dist/core/graph/exposures.js +4 -0
  222. package/dist/core/graph/jobs.d.ts +31 -0
  223. package/dist/core/graph/jobs.js +2 -0
  224. package/dist/core/graph/names.d.ts +28 -0
  225. package/dist/core/graph/names.js +3 -0
  226. package/dist/core/graph/objects.d.ts +55 -0
  227. package/dist/core/graph/objects.js +9 -0
  228. package/dist/core/graph/package-docs.d.ts +31 -0
  229. package/dist/core/graph/package-docs.js +5 -0
  230. package/dist/core/graph/package-files.d.ts +20 -0
  231. package/dist/core/graph/package-files.js +2 -0
  232. package/dist/core/graph/reader.d.ts +21 -0
  233. package/dist/core/graph/reader.js +3 -0
  234. package/dist/core/graph/repo-sync/exchange.d.ts +34 -0
  235. package/dist/core/graph/repo-sync/exchange.js +2 -0
  236. package/dist/core/graph/repo-sync/identity.d.ts +30 -0
  237. package/dist/core/graph/repo-sync/identity.js +1 -0
  238. package/dist/core/graph/repo-sync/index.d.ts +4 -0
  239. package/dist/core/graph/repo-sync/index.js +1 -0
  240. package/dist/core/graph/repo-sync/mirror.d.ts +30 -0
  241. package/dist/core/graph/repo-sync/mirror.js +6 -0
  242. package/dist/core/graph/repo-sync/ref-format.d.ts +76 -0
  243. package/dist/core/graph/repo-sync/ref-format.js +2 -0
  244. package/dist/core/graph/repo-sync/repos.d.ts +17 -0
  245. package/dist/core/graph/repo-sync/repos.js +3 -0
  246. package/dist/core/graph/repo-sync/sync.d.ts +42 -0
  247. package/dist/core/graph/repo-sync/sync.js +2 -0
  248. package/dist/core/graph/rules.d.ts +26 -0
  249. package/dist/core/graph/rules.js +3 -0
  250. package/dist/core/graph/spaces/app.d.ts +3 -0
  251. package/dist/core/graph/spaces/app.js +1 -0
  252. package/dist/core/graph/spaces/index.d.ts +19 -0
  253. package/dist/core/graph/spaces/index.js +1 -0
  254. package/dist/core/graph/spaces/person.d.ts +5 -0
  255. package/dist/core/graph/spaces/person.js +2 -0
  256. package/dist/core/graph/spaces/repo.d.ts +4 -0
  257. package/dist/core/graph/spaces/repo.js +1 -0
  258. package/dist/core/graph/types.d.ts +75 -0
  259. package/dist/core/graph/types.js +1 -0
  260. package/dist/core/graph/watches.d.ts +62 -0
  261. package/dist/core/graph/watches.js +18 -0
  262. package/dist/core/human/feedback-companion.js +1 -1
  263. package/dist/core/human/requests.d.ts +3 -1
  264. package/dist/core/human/requests.js +6 -6
  265. package/dist/core/inspector/model.js +2 -2
  266. package/dist/core/io.js +5 -5
  267. package/dist/core/layout-migrate/index.d.ts +24 -1
  268. package/dist/core/layout-migrate/index.js +4 -4
  269. package/dist/core/layout-migrate/paths.d.ts +4 -0
  270. package/dist/core/layout-migrate/paths.js +1 -1
  271. package/dist/core/layout-migrate/stored-paths.d.ts +7 -0
  272. package/dist/core/layout-migrate/stored-paths.js +11 -11
  273. package/dist/core/layout-migrate/stores.d.ts +19 -6
  274. package/dist/core/layout-migrate/stores.js +3 -4
  275. package/dist/core/manifest.d.ts +0 -2
  276. package/dist/core/manifest.js +1 -1
  277. package/dist/core/{memory/extensions.d.ts → plugin-extensions.d.ts} +9 -10
  278. package/dist/core/plugin-extensions.js +1 -0
  279. package/dist/core/preview-registry.d.ts +1 -1
  280. package/dist/core/preview-registry.js +3 -2
  281. package/dist/core/profiles/manifest.d.ts +7 -7
  282. package/dist/core/profiles/manifest.js +1 -1
  283. package/dist/core/profiles/select.js +3 -3
  284. package/dist/core/review/birth.js +1 -1
  285. package/dist/core/review/companion.js +1 -1
  286. package/dist/core/review/stage.d.ts +12 -1
  287. package/dist/core/review/stage.js +1 -1
  288. package/dist/core/review/store.d.ts +2 -0
  289. package/dist/core/review/store.js +1 -1
  290. package/dist/core/review/types.d.ts +7 -1
  291. package/dist/core/runs/events.js +1 -1
  292. package/dist/core/runs/operations.js +5 -5
  293. package/dist/core/runs/questions.js +2 -2
  294. package/dist/core/runtime/bearings-render.d.ts +13 -7
  295. package/dist/core/runtime/bearings-render.js +12 -12
  296. package/dist/core/runtime/bearings.d.ts +8 -18
  297. package/dist/core/runtime/bearings.js +7 -7
  298. package/dist/core/runtime/broker/daemon-ops.d.ts +7 -12
  299. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  300. package/dist/core/runtime/broker/fault-retry.d.ts +2 -0
  301. package/dist/core/runtime/broker/fault-retry.js +1 -1
  302. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  303. package/dist/core/runtime/broker/frame-memory-refs.d.ts +7 -2
  304. package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
  305. package/dist/core/runtime/broker/inbox.d.ts +1 -4
  306. package/dist/core/runtime/broker/inbox.js +1 -10
  307. package/dist/core/runtime/broker/rebind.js +1 -1
  308. package/dist/core/runtime/broker/retry-card-elision.d.ts +7 -0
  309. package/dist/core/runtime/broker/retry-card-elision.js +1 -0
  310. package/dist/core/runtime/broker-extension-render.d.ts +0 -13
  311. package/dist/core/runtime/broker-extension-render.js +2 -4
  312. package/dist/core/runtime/broker-persona-guidance.js +3 -3
  313. package/dist/core/runtime/broker-protocol.d.ts +1 -1
  314. package/dist/core/runtime/broker.js +1 -1
  315. package/dist/core/runtime/close.d.ts +9 -4
  316. package/dist/core/runtime/close.js +1 -1
  317. package/dist/core/runtime/deliver-live.js +1 -1
  318. package/dist/core/runtime/kickoff.js +17 -19
  319. package/dist/core/runtime/launch-target.d.ts +7 -0
  320. package/dist/core/runtime/launch-target.js +1 -1
  321. package/dist/core/runtime/ledger.d.ts +10 -0
  322. package/dist/core/runtime/ledger.js +3 -0
  323. package/dist/core/runtime/lifecycle.js +2 -2
  324. package/dist/core/runtime/nodes.d.ts +10 -2
  325. package/dist/core/runtime/nodes.js +1 -1
  326. package/dist/core/runtime/outcome-document.d.ts +2 -2
  327. package/dist/core/runtime/outcome-document.js +1 -1
  328. package/dist/core/runtime/persona.js +2 -2
  329. package/dist/core/runtime/placement.js +1 -1
  330. package/dist/core/runtime/promote.d.ts +2 -2
  331. package/dist/core/runtime/promote.js +1 -1
  332. package/dist/core/runtime/prospective-inventory-cli.js +2 -2
  333. package/dist/core/runtime/recycle.js +1 -1
  334. package/dist/core/runtime/reopen.js +1 -1
  335. package/dist/core/runtime/revive.js +2 -2
  336. package/dist/core/runtime/roadmap.d.ts +17 -9
  337. package/dist/core/runtime/roadmap.js +4 -4
  338. package/dist/core/runtime/spawn-env.js +1 -1
  339. package/dist/core/runtime/spawn.d.ts +5 -3
  340. package/dist/core/runtime/spawn.js +2 -2
  341. package/dist/core/runtime/structured-output.d.ts +3 -1
  342. package/dist/core/runtime/structured-output.js +4 -4
  343. package/dist/core/scope.d.ts +1 -32
  344. package/dist/core/scope.js +1 -1
  345. package/dist/core/scoped-state/db.js +2 -1
  346. package/dist/core/scoped-state/migrate.js +2 -2
  347. package/dist/core/scoped-state/profiles.d.ts +11 -0
  348. package/dist/core/scoped-state/profiles.js +1 -1
  349. package/dist/core/scoped-state/schema.d.ts +1 -1
  350. package/dist/core/scoped-state/schema.js +7 -5
  351. package/dist/core/spaces/permissions.d.ts +0 -14
  352. package/dist/core/spaces/permissions.js +1 -1
  353. package/dist/core/spaces/stop.d.ts +13 -0
  354. package/dist/core/spaces/stop.js +2 -2
  355. package/dist/core/storage/tables.d.ts +1 -1
  356. package/dist/core/substrate/delivery/corpus.d.ts +21 -0
  357. package/dist/core/substrate/delivery/corpus.js +3 -0
  358. package/dist/core/substrate/delivery/deliver.d.ts +76 -0
  359. package/dist/core/substrate/delivery/deliver.js +6 -0
  360. package/dist/core/substrate/delivery/listings.d.ts +27 -0
  361. package/dist/core/substrate/delivery/listings.js +4 -0
  362. package/dist/core/substrate/delivery/match.d.ts +28 -0
  363. package/dist/core/substrate/delivery/match.js +1 -0
  364. package/dist/core/substrate/delivery/plan.d.ts +67 -0
  365. package/dist/core/substrate/delivery/plan.js +3 -0
  366. package/dist/core/substrate/delivery/render-boot.d.ts +20 -0
  367. package/dist/core/substrate/delivery/render-boot.js +54 -0
  368. package/dist/core/substrate/delivery/render-event.d.ts +47 -0
  369. package/dist/core/substrate/delivery/render-event.js +6 -0
  370. package/dist/core/substrate/delivery/sub-persona-menu.d.ts +2 -0
  371. package/dist/core/substrate/delivery/sub-persona-menu.js +6 -0
  372. package/dist/core/substrate/delivery/types.d.ts +30 -0
  373. package/dist/core/substrate/delivery/types.js +0 -0
  374. package/dist/core/substrate/gate-explain.d.ts +0 -13
  375. package/dist/core/substrate/gate-explain.js +1 -1
  376. package/dist/core/substrate/schema.d.ts +11 -139
  377. package/dist/core/substrate/schema.js +1 -1
  378. package/dist/core/substrate/subject-fields.d.ts +3 -0
  379. package/dist/core/substrate/subject.d.ts +2 -1
  380. package/dist/core/substrate/subject.js +1 -1
  381. package/dist/daemon/api/handlers/app-profiles.js +1 -1
  382. package/dist/daemon/api/handlers/bash-jobs.js +1 -2
  383. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  384. package/dist/daemon/api/handlers/canvas.js +5 -5
  385. package/dist/daemon/api/handlers/daemon.js +1 -1
  386. package/dist/daemon/api/handlers/delivery.d.ts +2 -0
  387. package/dist/daemon/api/handlers/delivery.js +1 -0
  388. package/dist/daemon/api/handlers/{memory.d.ts → docs.d.ts} +1 -1
  389. package/dist/daemon/api/handlers/docs.js +1 -0
  390. package/dist/daemon/api/handlers/hook-exec.js +1 -1
  391. package/dist/daemon/api/handlers/messages.js +2 -2
  392. package/dist/daemon/api/handlers/node-records.js +2 -2
  393. package/dist/daemon/api/handlers/nodes.js +1 -1
  394. package/dist/daemon/api/handlers/objects.d.ts +2 -0
  395. package/dist/daemon/api/handlers/objects.js +5 -0
  396. package/dist/daemon/api/handlers/package-docs.d.ts +2 -0
  397. package/dist/daemon/api/handlers/package-docs.js +1 -0
  398. package/dist/daemon/api/handlers/profiles.js +1 -1
  399. package/dist/daemon/api/handlers/reports.d.ts +2 -2
  400. package/dist/daemon/api/handlers/reports.js +4 -4
  401. package/dist/daemon/api/handlers/reviews.js +1 -1
  402. package/dist/daemon/api/map.d.ts +2 -2
  403. package/dist/daemon/api/map.js +2 -2
  404. package/dist/daemon/api/operations.d.ts +1 -1
  405. package/dist/daemon/api/operations.js +1 -1
  406. package/dist/daemon/api/reader.d.ts +17 -0
  407. package/dist/daemon/api/reader.js +1 -0
  408. package/dist/daemon/api/server.js +1 -1
  409. package/dist/daemon/control.d.ts +2 -3
  410. package/dist/daemon/crtrd.js +8 -6
  411. package/dist/daemon/fleet.js +4 -4
  412. package/dist/daemon/reconcilers/bash-deadline.d.ts +11 -1
  413. package/dist/daemon/reconcilers/bash-deadline.js +2 -1
  414. package/dist/daemon/reconcilers/broker-supervision.js +4 -4
  415. package/dist/daemon/reconcilers/live-obligation.js +1 -1
  416. package/dist/daemon/reconcilers/node-deadline.js +1 -1
  417. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  418. package/dist/daemon/reconcilers/storage-maintenance.d.ts +1 -0
  419. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  420. package/dist/daemon/review/deliver.js +2 -2
  421. package/dist/daemon/review/finish.js +1 -1
  422. package/dist/hook-authoring.d.ts +0 -1
  423. package/dist/hook-authoring.js +3 -3
  424. package/dist/migrations/004-canvas-documents/apply.d.ts +10 -0
  425. package/dist/migrations/004-canvas-documents/apply.js +1 -0
  426. package/dist/migrations/004-canvas-documents/fields.d.ts +24 -0
  427. package/dist/migrations/004-canvas-documents/fields.js +2 -0
  428. package/dist/migrations/004-canvas-documents/index.d.ts +16 -0
  429. package/dist/migrations/004-canvas-documents/index.js +2 -0
  430. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +16 -0
  431. package/dist/migrations/004-canvas-documents/legacy/discover.js +1 -0
  432. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +5 -0
  433. package/dist/migrations/004-canvas-documents/legacy/history.js +2 -0
  434. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +7 -0
  435. package/dist/migrations/004-canvas-documents/legacy/nested.js +1 -0
  436. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +14 -0
  437. package/dist/migrations/004-canvas-documents/legacy/parse.js +1 -0
  438. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +91 -0
  439. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  440. package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +6 -0
  441. package/dist/migrations/004-canvas-documents/legacy-edges.js +18 -0
  442. package/dist/migrations/004-canvas-documents/plan.d.ts +102 -0
  443. package/dist/migrations/004-canvas-documents/plan.js +3 -0
  444. package/dist/migrations/004-canvas-documents/pointers.d.ts +23 -0
  445. package/dist/migrations/004-canvas-documents/pointers.js +4 -0
  446. package/dist/migrations/activation.d.ts +9 -18
  447. package/dist/migrations/activation.js +2 -2
  448. package/dist/pi-extensions/broker-local.d.ts +2 -2
  449. package/dist/pi-extensions/broker-local.js +2 -2
  450. package/dist/pi-extensions/canvas-bash-valve.js +5 -4
  451. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  452. package/dist/pi-extensions/canvas-doc-substrate.d.ts +0 -1
  453. package/dist/pi-extensions/canvas-doc-substrate.js +6 -6
  454. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  455. package/dist/pi-extensions/canvas-passive-context.js +1 -1
  456. package/dist/pi-extensions/canvas-recap.js +2 -2
  457. package/dist/pi-extensions/canvas-stophook.d.ts +1 -1
  458. package/dist/pi-extensions/canvas-stophook.js +1 -1
  459. package/dist/prompts/review.js +3 -3
  460. package/dist/shared/env.d.ts +5 -0
  461. package/dist/shared/env.js +1 -1
  462. package/dist/shared/generated-context.js +2 -10
  463. package/dist/shared/inbox-entry-body.d.ts +22 -0
  464. package/dist/shared/inbox-entry-body.js +10 -0
  465. package/dist/{core/memory → shared}/inline-ref-guidance.d.ts +2 -2
  466. package/dist/shared/inline-ref-guidance.js +2 -0
  467. package/dist/types.d.ts +3 -1
  468. package/docs/cli/memory-and-preferences.md +12 -14
  469. package/docs/concepts/README.md +1 -1
  470. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  471. package/docs/concepts/memory.md +15 -15
  472. package/docs/concepts/nodes-and-the-canvas.md +1 -1
  473. package/docs/concepts/profiles-kinds-and-modes.md +5 -5
  474. package/docs/concepts/scopes-and-trust.md +1 -1
  475. package/docs/concepts/why-a-daemon.md +1 -1
  476. package/docs/sdk/README.md +5 -6
  477. package/docs/sdk/errors.md +0 -13
  478. package/docs/sdk/guides/README.md +0 -1
  479. package/docs/sdk/nodes.md +0 -2
  480. package/docs/sdk/resources.md +0 -1
  481. package/package.json +2 -2
  482. package/packages/crouter-identity/package.json +1 -1
  483. package/runtime.lock.json +11 -11
  484. package/dist/api/dto/memory.d.ts +0 -171
  485. package/dist/api/dto/memory.js +0 -1
  486. package/dist/builtin-memory/crouter-sdk/guides/app-memory.md +0 -73
  487. package/dist/builtin-memory/crouter-sdk/memory.md +0 -87
  488. package/dist/commands/broker-permissions.d.ts +0 -2
  489. package/dist/commands/broker-permissions.js +0 -1
  490. package/dist/commands/memory/client.d.ts +0 -11
  491. package/dist/commands/memory/client.js +0 -1
  492. package/dist/commands/memory/delete.d.ts +0 -1
  493. package/dist/commands/memory/delete.js +0 -1
  494. package/dist/commands/memory/edit.d.ts +0 -1
  495. package/dist/commands/memory/edit.js +0 -21
  496. package/dist/commands/memory/find.d.ts +0 -1
  497. package/dist/commands/memory/find.js +0 -1
  498. package/dist/commands/memory/history.d.ts +0 -1
  499. package/dist/commands/memory/history.js +0 -5
  500. package/dist/commands/memory/lint.d.ts +0 -1
  501. package/dist/commands/memory/lint.js +0 -1
  502. package/dist/commands/memory/list.d.ts +0 -1
  503. package/dist/commands/memory/list.js +0 -1
  504. package/dist/commands/memory/move.d.ts +0 -1
  505. package/dist/commands/memory/move.js +0 -1
  506. package/dist/commands/memory/origin.d.ts +0 -1
  507. package/dist/commands/memory/origin.js +0 -1
  508. package/dist/commands/memory/read.d.ts +0 -1
  509. package/dist/commands/memory/read.js +0 -6
  510. package/dist/commands/memory/shared.d.ts +0 -22
  511. package/dist/commands/memory/shared.js +0 -1
  512. package/dist/commands/memory/write.d.ts +0 -1
  513. package/dist/commands/memory/write.js +0 -13
  514. package/dist/commands/memory.js +0 -1
  515. package/dist/commands/node-inspect-artifacts.d.ts +0 -1
  516. package/dist/commands/node-inspect-artifacts.js +0 -8
  517. package/dist/core/help/memory-extensions.d.ts +0 -3
  518. package/dist/core/help/memory-extensions.js +0 -2
  519. package/dist/core/memory/cli-selector.d.ts +0 -13
  520. package/dist/core/memory/cli-selector.js +0 -1
  521. package/dist/core/memory/doc-link-grammar.d.ts +0 -20
  522. package/dist/core/memory/doc-link-grammar.js +0 -2
  523. package/dist/core/memory/extensions.js +0 -1
  524. package/dist/core/memory/history.d.ts +0 -87
  525. package/dist/core/memory/history.js +0 -6
  526. package/dist/core/memory/identity.d.ts +0 -65
  527. package/dist/core/memory/identity.js +0 -1
  528. package/dist/core/memory/inline-ref-guidance.js +0 -2
  529. package/dist/core/memory/inline-ref-inventory.d.ts +0 -9
  530. package/dist/core/memory/inline-ref-inventory.js +0 -1
  531. package/dist/core/memory/lint.d.ts +0 -163
  532. package/dist/core/memory/lint.js +0 -2
  533. package/dist/core/memory/mutation-domain.d.ts +0 -113
  534. package/dist/core/memory/mutation-domain.js +0 -12
  535. package/dist/core/memory/mutations.d.ts +0 -74
  536. package/dist/core/memory/mutations.js +0 -1
  537. package/dist/core/memory/project-namespace.d.ts +0 -31
  538. package/dist/core/memory/project-namespace.js +0 -2
  539. package/dist/core/memory/repository-association.d.ts +0 -31
  540. package/dist/core/memory/repository-association.js +0 -1
  541. package/dist/core/memory/service.d.ts +0 -145
  542. package/dist/core/memory/service.js +0 -2
  543. package/dist/core/memory/tree.d.ts +0 -39
  544. package/dist/core/memory/tree.js +0 -1
  545. package/dist/core/memory-resolver.d.ts +0 -280
  546. package/dist/core/memory-resolver.js +0 -2
  547. package/dist/core/nested-stores.d.ts +0 -18
  548. package/dist/core/nested-stores.js +0 -1
  549. package/dist/core/runtime/memory.d.ts +0 -3
  550. package/dist/core/runtime/memory.js +0 -1
  551. package/dist/core/substrate/frontmatter-validation.d.ts +0 -11
  552. package/dist/core/substrate/frontmatter-validation.js +0 -1
  553. package/dist/core/substrate/gate.d.ts +0 -16
  554. package/dist/core/substrate/gate.js +0 -1
  555. package/dist/core/substrate/index.d.ts +0 -18
  556. package/dist/core/substrate/index.js +0 -1
  557. package/dist/core/substrate/injected-store.d.ts +0 -75
  558. package/dist/core/substrate/injected-store.js +0 -2
  559. package/dist/core/substrate/listings.d.ts +0 -28
  560. package/dist/core/substrate/listings.js +0 -1
  561. package/dist/core/substrate/memory-events.d.ts +0 -6
  562. package/dist/core/substrate/memory-events.js +0 -1
  563. package/dist/core/substrate/on-read-node.d.ts +0 -6
  564. package/dist/core/substrate/on-read-node.js +0 -1
  565. package/dist/core/substrate/on-read.d.ts +0 -101
  566. package/dist/core/substrate/on-read.js +0 -9
  567. package/dist/core/substrate/plan.d.ts +0 -94
  568. package/dist/core/substrate/plan.js +0 -1
  569. package/dist/core/substrate/render-node.d.ts +0 -12
  570. package/dist/core/substrate/render-node.js +0 -1
  571. package/dist/core/substrate/render.d.ts +0 -41
  572. package/dist/core/substrate/render.js +0 -65
  573. package/dist/core/substrate/session-cache.d.ts +0 -27
  574. package/dist/core/substrate/session-cache.js +0 -1
  575. package/dist/core/substrate/surface-match.d.ts +0 -73
  576. package/dist/core/substrate/surface-match.js +0 -1
  577. package/dist/daemon/api/handlers/memory.js +0 -5
  578. package/dist/migrations/001-surfaces-frontmatter.d.ts +0 -2
  579. package/dist/migrations/001-surfaces-frontmatter.js +0 -1
  580. package/dist/migrations/002-profile-project-memory.d.ts +0 -2
  581. package/dist/migrations/002-profile-project-memory.js +0 -1
  582. package/dist/migrations/003-repository-root-memory-identity/front-door.d.ts +0 -26
  583. package/dist/migrations/003-repository-root-memory-identity/front-door.js +0 -11
  584. package/dist/migrations/003-repository-root-memory-identity/index.d.ts +0 -2
  585. package/dist/migrations/003-repository-root-memory-identity/index.js +0 -5
  586. package/dist/migrations/003-repository-root-memory-identity/references.d.ts +0 -95
  587. package/dist/migrations/003-repository-root-memory-identity/references.js +0 -5
  588. package/dist/migrations/003-repository-root-memory-identity/repository-facts.d.ts +0 -39
  589. package/dist/migrations/003-repository-root-memory-identity/repository-facts.js +0 -3
  590. package/dist/migrations/convergent.d.ts +0 -43
  591. package/dist/migrations/convergent.js +0 -2
  592. package/dist/migrations/corpus.d.ts +0 -75
  593. package/dist/migrations/corpus.js +0 -3
  594. package/dist/migrations/frontmatter-splice.d.ts +0 -15
  595. package/dist/migrations/frontmatter-splice.js +0 -8
  596. package/dist/migrations/profile-manifests.d.ts +0 -30
  597. package/dist/migrations/profile-manifests.js +0 -2
  598. package/dist/migrations/registry.d.ts +0 -7
  599. package/dist/migrations/registry.js +0 -1
  600. package/dist/migrations/runner.d.ts +0 -43
  601. package/dist/migrations/runner.js +0 -1
  602. package/dist/migrations/types.d.ts +0 -211
  603. package/dist/shared/birth-announcement.d.ts +0 -12
  604. package/dist/shared/birth-announcement.js +0 -1
  605. package/docs/sdk/guides/app-memory.md +0 -22
  606. package/docs/sdk/memory.md +0 -85
  607. /package/dist/{migrations/types.js → api/dto/delivery.js} +0 -0
  608. /package/dist/{core/memory → shared}/inline-ref-grammar.d.ts +0 -0
  609. /package/dist/{core/memory → shared}/inline-ref-grammar.js +0 -0
@@ -0,0 +1,6 @@
1
+ var a=Object.defineProperty;var o=(e,n)=>a(e,"name",{value:n,configurable:!0});import{subKindsAvailableTo as r}from"../../config.js";import{packageFiles as u}from"../../graph/package-files.js";import{builtinMemoryRoot as p}from"../../scope.js";let s;function c(e){s??=u(p()).files.map(t=>t.name);const n=`kinds/${e}`;return s.some(t=>t===n||t.startsWith(`${n}/`))?` (\`crtr canvas read ${n}\`)`:""}o(c,"subKindDocCitation");function f(e){const n=r(e);if(n.length===0)return"";const t=n.map(i=>`- \`${i.kind}\` \u2014 ${i.whenToUse}${c(i.kind)}`);return`## Sub-personas you may spawn
2
+
3
+ These specialist sub-personas are available to the ${e} kind. Spawn one with \`crtr node new --kind <sub> "<scope>"\`, and treat it as its own scope instead of dragging unrelated context into it.
4
+
5
+ `+t.join(`
6
+ `)}o(f,"buildSubPersonaMenu");export{f as buildSubPersonaMenu};
@@ -0,0 +1,30 @@
1
+ /** Row-backed delivery engine: one document as the planner and renderers see it. */
2
+ import type { RuleRow } from '../../graph/rules.js';
3
+ import type { ObjectRow } from '../../graph/types.js';
4
+ import type { Rung } from '../schema.js';
5
+ export interface DeliveryDoc {
6
+ object: ObjectRow;
7
+ owner: ObjectRow;
8
+ /** How `<handle>/<name>` names the owner: a node's id, else the owner's name. */
9
+ ownerHandle: string;
10
+ /** The owner's index in the reader's view (0 = own node); lower wins a bare name. */
11
+ viewRank: number;
12
+ /** The document belongs to the reading node itself. */
13
+ ownNode: boolean;
14
+ /** A package document (`documents.source_path` set): an installed plugin's or crtr's own. */
15
+ shipped: boolean;
16
+ kind: 'knowledge' | 'preference';
17
+ name: string;
18
+ /** The bare name when `[[name]]` resolves to this object for the reader, else `<ownerHandle>/<name>`. */
19
+ displayName: string;
20
+ preview: string;
21
+ unlisted: boolean;
22
+ headsKey: string;
23
+ /** Body hash of the highest head revision. */
24
+ bodyHash: string;
25
+ /** Lazy: preview and name deliveries never read the body. */
26
+ body(): string;
27
+ rules: RuleRow[];
28
+ /** The profile's cap for this owner on `boot` / `workspace-open`. */
29
+ limit: Rung;
30
+ }
File without changes
@@ -1,5 +1,4 @@
1
1
  import type { NodeConfigSubject } from './subject-fields.js';
2
- import type { DeliveryRecord } from './plan.js';
3
2
  /** The subject has no value at this field path — distinct from a value of
4
3
  * `null`, which a gate can legitimately demand. */
5
4
  export declare const ABSENT: unique symbol;
@@ -34,15 +33,3 @@ export declare function formatClause(clause: GateClause): string;
34
33
  * the directory it names, else the longest literal run it insists on, else an
35
34
  * admission that it is a pattern. The source is never printed. */
36
35
  export declare function readableRegex(source: string): string;
37
- /** Which of a record's two gates is being explained. */
38
- export type GateSide = 'doc' | 'entry';
39
- /** The failing clauses of one record's document or entry gate, or an empty list
40
- * when there is nothing to explain — the gate passed, there is no subject to
41
- * match against, or the predicate resists decomposition. An evaluator that
42
- * throws is the planner's own `failed to evaluate` outcome and keeps its
43
- * sentence. */
44
- export declare function explainRecordGate(record: DeliveryRecord, side: GateSide, subject: NodeConfigSubject | null): GateClause[];
45
- /** Does every failing clause name a node value the reader can change? Only then
46
- * is "dial the snapshot" a true instruction — a malformed gate is fixed in the
47
- * document. */
48
- export declare function allMismatches(clauses: readonly GateClause[]): boolean;
@@ -1 +1 @@
1
- var O=Object.defineProperty;var o=(n,t)=>O(n,"name",{value:t,configurable:!0});import{getField as y,matchField as W,evalCondition as m}from"../predicate.js";import{tildify as w}from"../fs-utils.js";const h=Symbol("absent");function N(n,t){return g(n,t)??[]}o(N,"explainGate");function g(n,t){if(n==null||typeof n!="object")return[];if(Array.isArray(n))return A(n,t);const e=n,r=[];if(("any"in e||"not"in e)&&("any"in e&&!m({any:e.any},t)||"not"in e&&!m({not:e.not},t)))return null;if("all"in e){const s=A(Array.isArray(e.all)?e.all:[e.all],t);if(s===null)return null;r.push(...s)}const i=Object.keys(e).filter(s=>s!=="all"&&s!=="any"&&s!=="not");if(i.length===0&&!("all"in e)&&!("any"in e)&&!("not"in e))return[{field:"",failure:"malformed",actual:h,demand:e,defect:"is empty, and an empty gate never matches"}];for(const s of i){const l=e[s];W(y(t,s),l)||r.push(E(s,l,t))}return r}o(g,"walk");function A(n,t){const e=[];for(const r of n){const i=g(r,t);if(i===null)return null;e.push(...i)}return e}o(A,"collect");function E(n,t,e){const r=y(e,n),i=r===void 0?h:r,s=j(t);return s===null?{field:n,failure:"mismatch",actual:i,demand:t}:{field:n,failure:"malformed",actual:i,demand:t,defect:s}}o(E,"clauseFor");const R=new Set(["eq","ne","in","nin","exists","contains","containsAll","containsAny","matches","imatches","gt","gte","lt","lte"]);function j(n){if(n===null||Array.isArray(n)||typeof n!="object")return null;for(const[t,e]of Object.entries(n)){if(!R.has(t))return`uses unknown operator "${t}" \u2014 unknown operators never match`;if(t==="matches"||t==="imatches"){if(typeof e!="string")return"is matched against something that is not a pattern \u2014 it never matches";try{new RegExp(e,t==="imatches"?"i":"")}catch{return"has an invalid regular expression \u2014 an invalid pattern never matches"}}if(["gt","gte","lt","lte"].includes(t)&&Number.isNaN(Number(e)))return`compares ${t} against something that is not a number \u2014 it never matches`}return null}o(j,"matcherDefect");function $(n){return n==="hasManager"?"manager":n==="orchestration.depth"?"depth":n}o($,"labelFor");const L=" | gate: ";function D(n){return n.failure==="malformed"?`${n.field===""?"the gate":$(n.field)} ${n.defect??"never matches"}`:`${$(n.field)}: ${x(n.actual)}${L}${a(n.demand)}`}o(D,"formatClause");function x(n){return n===h||n===null||n===void 0?"none":typeof n=="boolean"?n?"yes":"no":Array.isArray(n)?n.map(t=>x(t)).join(", "):typeof n=="string"?n===""?"none":d(n):typeof n=="object"?JSON.stringify(n):String(n)}o(x,"renderActual");function a(n){if(n==null)return"none";if(typeof n=="boolean")return n?"yes":"no";if(typeof n=="string")return n===""?"none":d(n);if(typeof n=="number")return String(n);if(Array.isArray(n))return p(n);const t=Object.entries(n);return t.length===0?"nothing":t.map(([e,r])=>C(e,r)).join(" and ")}o(a,"renderDemand");function C(n,t){switch(n){case"eq":return a(t);case"ne":return`not ${a(t)}`;case"in":return p(t);case"nin":return`not ${p(t)}`;case"exists":return t===!1?"no value":"any value";case"contains":return`includes ${a(t)}`;case"containsAll":return`includes all of ${S(t)}`;case"containsAny":return`includes any of ${S(t)}`;case"matches":case"imatches":return typeof t=="string"?F(t):"a pattern";case"gt":return`> ${String(t)}`;case"gte":return`\u2265 ${String(t)}`;case"lt":return`< ${String(t)}`;case"lte":return`\u2264 ${String(t)}`;default:return`${n} ${String(t)}`}}o(C,"renderOp");function p(n){const t=(Array.isArray(n)?n:[n]).map(e=>a(e));return t.length===0?"nothing":t.join(" or ")}o(p,"orList");function S(n){return(Array.isArray(n)?n:[n]).map(t=>a(t)).join(", ")}o(S,"commaList");function d(n){return n.startsWith("/")?w(n):n}o(d,"shortPath");const c=new Set(["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"]);function F(n){let t=n;t.startsWith("^")&&(t=t.slice(1)),t=t.replace(/\((?:\?:)?\\?\/\|\$\)\??$/,""),t.endsWith("$")&&!t.endsWith("\\$")&&(t=t.slice(0,-1));const e=b(t);if(e!==null&&e!=="")return d(e);const r=G(t);if(r!==null)return r.map(s=>d(s)).join(" or ");const i=M(n);return i===null?"a pattern":`contains "${d(i)}"`}o(F,"readableRegex");function b(n){let t="";for(let e=0;e<n.length;e++){const r=n[e];if(r==="\\"){const i=n[e+1];if(i===void 0||!c.has(i)&&i!=="/"&&i!=="-")return null;t+=i,e++;continue}if(c.has(r))return null;t+=r}return t}o(b,"unescapeLiteral");function G(n){const t=n.indexOf("(");if(t===-1||!n.endsWith(")"))return null;const e=b(n.slice(0,t));if(e===null)return null;let r=n.slice(t+1,-1);if(r.startsWith("?:")&&(r=r.slice(2)),r.includes("(")||r.includes(")"))return null;const i=r.split("|");if(i.length<2)return null;const s=[];for(const l of i){const u=T(l);if(u===null)return null;s.push(e+u)}return s}o(G,"distributeAlternation");function T(n){let t="";for(let e=0;e<n.length;e++){if(n.startsWith("[^/]+",e)){t+="*",e+=4;continue}if(n.startsWith("[^\\/]+",e)){t+="*",e+=5;continue}if(n.startsWith(".*",e)){t+="*",e+=1;continue}const r=n[e];if(r==="\\"){const i=n[e+1];if(i===void 0||!c.has(i)&&i!=="/"&&i!=="-")return null;t+=i,e++;continue}if(c.has(r))return null;t+=r}return t}o(T,"branchText");function M(n){let t="",e="",r=0,i=!1;const s=o(()=>{e.length>t.length&&(t=e),e=""},"flush");for(let l=0;l<n.length;l++){const u=n[l];if(u==="\\"){const f=n[l+1];if(l++,r===0&&!i&&f!==void 0&&(c.has(f)||f==="/"||f==="-")){e+=f;continue}s();continue}if(i){u==="]"&&(i=!1);continue}if(u==="["){s(),i=!0;continue}if(u==="("){s(),r++;continue}if(u===")"){s(),r>0&&r--;continue}if(u==="|"&&r===0)return null;if(u==="{"){e.length>0&&(e=e.slice(0,-1)),s();const f=n.indexOf("}",l);f!==-1&&(l=f);continue}if(c.has(u)||r>0){(u==="?"||u==="*")&&e.length>0&&(e=e.slice(0,-1)),s();continue}e+=u}return s(),t.length>1?t:null}o(M,"longestLiteralRun");function _(n,t,e){const r=t==="doc"?n.docGate:n.entryGate;if(r===null||r.pass||e===null)return[];const i=t==="doc"?n.doc.gate:n.authoredEntries.find(s=>!s.gate.pass)?.entry.gate;if(i===void 0)return[];try{return N(i,e)}catch{return[]}}o(_,"explainRecordGate");function B(n){return n.length>0&&n.every(t=>t.failure==="mismatch")}o(B,"allMismatches");export{h as ABSENT,L as CLAUSE_SEPARATOR,B as allMismatches,N as explainGate,_ as explainRecordGate,D as formatClause,F as readableRegex};
1
+ var O=Object.defineProperty;var o=(n,t)=>O(n,"name",{value:t,configurable:!0});import{getField as y,matchField as W,evalCondition as m}from"../predicate.js";import{tildify as w}from"../fs-utils.js";const d=Symbol("absent");function M(n,t){return g(n,t)??[]}o(M,"explainGate");function g(n,t){if(n==null||typeof n!="object")return[];if(Array.isArray(n))return A(n,t);const e=n,r=[];if(("any"in e||"not"in e)&&("any"in e&&!m({any:e.any},t)||"not"in e&&!m({not:e.not},t)))return null;if("all"in e){const s=A(Array.isArray(e.all)?e.all:[e.all],t);if(s===null)return null;r.push(...s)}const i=Object.keys(e).filter(s=>s!=="all"&&s!=="any"&&s!=="not");if(i.length===0&&!("all"in e)&&!("any"in e)&&!("not"in e))return[{field:"",failure:"malformed",actual:d,demand:e,defect:"is empty, and an empty gate never matches"}];for(const s of i){const u=e[s];W(y(t,s),u)||r.push(N(s,u,t))}return r}o(g,"walk");function A(n,t){const e=[];for(const r of n){const i=g(r,t);if(i===null)return null;e.push(...i)}return e}o(A,"collect");function N(n,t,e){const r=y(e,n),i=r===void 0?d:r,s=E(t);return s===null?{field:n,failure:"mismatch",actual:i,demand:t}:{field:n,failure:"malformed",actual:i,demand:t,defect:s}}o(N,"clauseFor");const j=new Set(["eq","ne","in","nin","exists","contains","containsAll","containsAny","matches","imatches","gt","gte","lt","lte"]);function E(n){if(n===null||Array.isArray(n)||typeof n!="object")return null;for(const[t,e]of Object.entries(n)){if(!j.has(t))return`uses unknown operator "${t}" \u2014 unknown operators never match`;if(t==="matches"||t==="imatches"){if(typeof e!="string")return"is matched against something that is not a pattern \u2014 it never matches";try{new RegExp(e,t==="imatches"?"i":"")}catch{return"has an invalid regular expression \u2014 an invalid pattern never matches"}}if(["gt","gte","lt","lte"].includes(t)&&Number.isNaN(Number(e)))return`compares ${t} against something that is not a number \u2014 it never matches`}return null}o(E,"matcherDefect");function $(n){return n==="hasManager"?"manager":n==="orchestration.depth"?"depth":n}o($,"labelFor");const L=" | gate: ";function _(n){return n.failure==="malformed"?`${n.field===""?"the gate":$(n.field)} ${n.defect??"never matches"}`:`${$(n.field)}: ${x(n.actual)}${L}${a(n.demand)}`}o(_,"formatClause");function x(n){return n===d||n===null||n===void 0?"none":typeof n=="boolean"?n?"yes":"no":Array.isArray(n)?n.map(t=>x(t)).join(", "):typeof n=="string"?n===""?"none":h(n):typeof n=="object"?JSON.stringify(n):String(n)}o(x,"renderActual");function a(n){if(n==null)return"none";if(typeof n=="boolean")return n?"yes":"no";if(typeof n=="string")return n===""?"none":h(n);if(typeof n=="number")return String(n);if(Array.isArray(n))return p(n);const t=Object.entries(n);return t.length===0?"nothing":t.map(([e,r])=>R(e,r)).join(" and ")}o(a,"renderDemand");function R(n,t){switch(n){case"eq":return a(t);case"ne":return`not ${a(t)}`;case"in":return p(t);case"nin":return`not ${p(t)}`;case"exists":return t===!1?"no value":"any value";case"contains":return`includes ${a(t)}`;case"containsAll":return`includes all of ${S(t)}`;case"containsAny":return`includes any of ${S(t)}`;case"matches":case"imatches":return typeof t=="string"?C(t):"a pattern";case"gt":return`> ${String(t)}`;case"gte":return`\u2265 ${String(t)}`;case"lt":return`< ${String(t)}`;case"lte":return`\u2264 ${String(t)}`;default:return`${n} ${String(t)}`}}o(R,"renderOp");function p(n){const t=(Array.isArray(n)?n:[n]).map(e=>a(e));return t.length===0?"nothing":t.join(" or ")}o(p,"orList");function S(n){return(Array.isArray(n)?n:[n]).map(t=>a(t)).join(", ")}o(S,"commaList");function h(n){return n.startsWith("/")?w(n):n}o(h,"shortPath");const c=new Set(["\\","^","$",".","|","?","*","+","(",")","[","]","{","}"]);function C(n){let t=n;t.startsWith("^")&&(t=t.slice(1)),t=t.replace(/\((?:\?:)?\\?\/\|\$\)\??$/,""),t.endsWith("$")&&!t.endsWith("\\$")&&(t=t.slice(0,-1));const e=b(t);if(e!==null&&e!=="")return h(e);const r=F(t);if(r!==null)return r.map(s=>h(s)).join(" or ");const i=P(n);return i===null?"a pattern":`contains "${h(i)}"`}o(C,"readableRegex");function b(n){let t="";for(let e=0;e<n.length;e++){const r=n[e];if(r==="\\"){const i=n[e+1];if(i===void 0||!c.has(i)&&i!=="/"&&i!=="-")return null;t+=i,e++;continue}if(c.has(r))return null;t+=r}return t}o(b,"unescapeLiteral");function F(n){const t=n.indexOf("(");if(t===-1||!n.endsWith(")"))return null;const e=b(n.slice(0,t));if(e===null)return null;let r=n.slice(t+1,-1);if(r.startsWith("?:")&&(r=r.slice(2)),r.includes("(")||r.includes(")"))return null;const i=r.split("|");if(i.length<2)return null;const s=[];for(const u of i){const l=T(u);if(l===null)return null;s.push(e+l)}return s}o(F,"distributeAlternation");function T(n){let t="";for(let e=0;e<n.length;e++){if(n.startsWith("[^/]+",e)){t+="*",e+=4;continue}if(n.startsWith("[^\\/]+",e)){t+="*",e+=5;continue}if(n.startsWith(".*",e)){t+="*",e+=1;continue}const r=n[e];if(r==="\\"){const i=n[e+1];if(i===void 0||!c.has(i)&&i!=="/"&&i!=="-")return null;t+=i,e++;continue}if(c.has(r))return null;t+=r}return t}o(T,"branchText");function P(n){let t="",e="",r=0,i=!1;const s=o(()=>{e.length>t.length&&(t=e),e=""},"flush");for(let u=0;u<n.length;u++){const l=n[u];if(l==="\\"){const f=n[u+1];if(u++,r===0&&!i&&f!==void 0&&(c.has(f)||f==="/"||f==="-")){e+=f;continue}s();continue}if(i){l==="]"&&(i=!1);continue}if(l==="["){s(),i=!0;continue}if(l==="("){s(),r++;continue}if(l===")"){s(),r>0&&r--;continue}if(l==="|"&&r===0)return null;if(l==="{"){e.length>0&&(e=e.slice(0,-1)),s();const f=n.indexOf("}",u);f!==-1&&(u=f);continue}if(c.has(l)||r>0){(l==="?"||l==="*")&&e.length>0&&(e=e.slice(0,-1)),s();continue}e+=l}return s(),t.length>1?t:null}o(P,"longestLiteralRun");export{d as ABSENT,L as CLAUSE_SEPARATOR,M as explainGate,_ as formatClause,C as readableRegex};
@@ -1,11 +1,6 @@
1
1
  import { type ProfileProjectMemory } from '../../api/dto/profiles.js';
2
- import type { MemoryDoc, MemoryScope } from '../memory-resolver.js';
3
2
  export declare const KINDS: readonly ["knowledge", "preference"];
4
3
  export type DocKind = (typeof KINDS)[number];
5
- export declare const PRIVACY_LEVELS: readonly ["public", "friends", "private"];
6
- export type PrivacyLevel = (typeof PRIVACY_LEVELS)[number];
7
- /** Missing or malformed privacy is treated conservatively on reads; lint rejects malformed values. */
8
- export declare function effectivePrivacy(fm: Record<string, unknown> | null): PrivacyLevel;
9
4
  /** Is `v` one of the two valid document kinds? */
10
5
  export declare function isDocKind(v: unknown): v is DocKind;
11
6
  export declare const RUNGS: readonly ["none", "name", "preview", "content"];
@@ -17,141 +12,18 @@ export declare function rungAtLeast(r: Rung, min: Rung): boolean;
17
12
  /** The lower of two rungs — the clamp automatic delivery applies to an
18
13
  * authored rung against its project relationship's cap. */
19
14
  export declare function minRung(a: Rung, b: Rung): Rung;
20
- export { normalizeNameSegment, normalizeDocName, resolveLocalName as resolveDocName } from '../memory/identity.js';
21
- export declare const SURFACE_EVENTS: readonly ["boot", "workspace-open", "read", "memory-read", "command", "pre-command"];
22
- export type SurfaceEvent = (typeof SURFACE_EVENTS)[number];
23
- /** The rungs an entry may deliver at. There is no `none` — silence is the
24
- * absence of an entry. (`Rung`'s `none` survives only as the internal
25
- * ranking floor — the planner's verdict for a doc that delivers nothing.) */
26
- export declare const SURFACE_RUNGS: readonly ["name", "preview", "content"];
27
- export type SurfaceRung = (typeof SURFACE_RUNGS)[number];
28
- /** One routing entry: when event `on` exposes a subject that fits `match`
29
- * (and `matchFrontmatter`, `read` only) and its optional node-config `gate`,
30
- * the doc delivers at rung `at`. Constraints within one entry AND together
31
- * (each present constraint must fit; a `match` list is satisfied by any one
32
- * glob); multiple entries per event OR together. */
33
- export interface SurfaceEntry {
34
- on: SurfaceEvent;
35
- /** Globs vs the event's subject namespace. Required on read/memory-read/
36
- * command/pre-command (a read entry may carry `matchFrontmatter` instead);
37
- * meaningless on boot/workspace-open (presence of the entry is the match). */
38
- match?: string[];
39
- /** Predicate over the read file's own YAML frontmatter — `read` event only.
40
- * Frontmatter key `match-frontmatter`. */
41
- matchFrontmatter?: GatePredicate;
42
- /** Optional predicate over the current node config. Frontmatter key `gate`.
43
- * The document-level gate remains the hard eligibility check. */
44
- gate?: GatePredicate;
45
- at: SurfaceRung;
46
- }
47
15
  /** A gate predicate tree, evaluated by predicate.ts (`evalCondition`) against
48
16
  * the node-config subject. Typed loosely on purpose — the matcher engine owns
49
17
  * validation; structurally it is a field→matcher map with optional
50
- * `all`/`any`/`not` combinators (design §4). */
18
+ * `all`/`any`/`not` combinators. */
51
19
  export type GatePredicate = Record<string, unknown>;
52
- /** The frontmatter-derived schema of a substrate document, with kind-aware
53
- * defaults applied. Required fields (`kind`/`when-and-why-to-read`) and
54
- * optionals all resolved to concrete typed values. */
55
- export interface SubstrateSchema {
56
- /** Which of the two semantic kinds (knowledge | preference). */
57
- kind: DocKind;
58
- /** App access level; legacy documents without the field resolve to private. */
59
- privacy: PrivacyLevel;
60
- /** The read-routing line — a single sentence answering WHEN to read this doc
61
- * and WHY it is worth the read: "When <circumstance>, this <kind> should be
62
- * read because <broader downstream payoff>." (design §4). This is
63
- * read-routing: WHY is the reader's payoff for the task in front of them,
64
- * NEVER a document summary, its rule, or that rule reworded as an outcome (a
65
- * benefit-shaped restatement still fails). It IS the preview verbatim.
66
- * Frontmatter key `when-and-why-to-read`. */
67
- whenAndWhyToRead: string;
68
- /** Human-facing abbreviation for `crtr memory list`. NEVER loaded into an
69
- * agent's context (design §3). Empty string when absent. */
70
- shortForm: string;
71
- /** Suppress this doc from directory listings (default false). Suppression,
72
- * not a type — the doc is otherwise ordinary. */
73
- unlisted: boolean;
74
- /** Explicit event routing. Empty = no explicit routing (listings still
75
- * apply, unless `unlisted`). Invalid entries are dropped by the tolerant
76
- * runtime parser; lint enforces strictly. */
77
- surfaces: SurfaceEntry[];
78
- /** Optional eligibility predicate over the node's own config. Absent ⇒ always
79
- * eligible. An empty `{}` is carried as-is and is inert (never matches) — see
80
- * `gatePasses`. */
81
- gate?: GatePredicate;
82
- /** Opt-in: this doc is invocable as a pi slash command (`/<name>`, `/` in a
83
- * nested name rendered as `:`). Default `false` — most docs are consulted,
84
- * not invoked. Frontmatter key `slash`. */
85
- slash: boolean;
86
- /** The gap this doc exists to close — the observed agent failure that
87
- * prompted it (CTO ruling 2026-07-03, `insights/agent-memory/document-substrate` §"Rationale
88
- * is a frontmatter field, never delivered"). MAINTAINER-FACING ONLY: excluded
89
- * from every delivered surface by construction — it is frontmatter, never
90
- * body, so it never reaches a boot render, on-read injection, or `memory
91
- * read` content output; only the raw file at `path` (or `memory read
92
- * --frontmatter`) shows it. It is NOT read-routing (`whenAndWhyToRead` owns
93
- * that) and NOT a content summary (`shortForm` owns that) — it answers
94
- * "what observed failure made this doc exist," never "why obey it." Absent
95
- * when the doc carries none. Frontmatter key `rationale`. */
96
- rationale?: string;
97
- }
98
- /** A fully-resolved substrate document: the parsed schema PLUS the resolver's
99
- * identity (explicit frontmatter `name` when present, otherwise the normalized
100
- * path-derived fallback) and body. This single object flows through the whole
101
- * pipeline (gate eval → boot/on-read render), so a renderer never re-parses. */
102
- export interface SubstrateDoc extends SubstrateSchema {
103
- /** Resolver-supplied identity, e.g. `insights/agent-memory/document-substrate` or an explicit
104
- * frontmatter name when one is present. */
105
- name: string;
106
- /** The scope this doc resolved from. */
107
- scope: MemoryScope;
108
- /** Owning plugin name when the doc is mounted from an installed plugin;
109
- * undefined for a native scope doc. Shipped (builtin/plugin) docs and
110
- * agent-editable scope docs render differently at boot (see renderGrouped). */
111
- plugin?: string;
112
- /** Absolute path to the source .md. */
113
- path: string;
114
- /** Document body, frontmatter stripped. */
115
- body: string;
116
- /** The selected profile relationship's cap on the project store this doc
117
- * resolved from — the maximum rung automatic boot and workspace-open
118
- * delivery may disclose it at. `content` is the neutral ceiling every
119
- * non-project doc and every uncapped project root carries. Targeted reads,
120
- * command routing, and directory listings ignore it. */
121
- projectMemory: ProfileProjectMemory;
122
- }
123
- /** Parse a raw frontmatter record (from `parseFrontmatterGeneric`, via the
124
- * resolver) into a typed schema with defaults applied. Returns `null` when the
125
- * record is absent or carries no valid `kind` — i.e. it is not a substrate
126
- * document and cannot be classified. Tolerant of every other imperfection (a
127
- * missing `when-and-why-to-read` defaults to '', a missing/bad rung falls back
128
- * to the neutral floor `none`), so a renderer mapping over many docs never
129
- * throws. Authoring-time enforcement of these fields lives in `crtr memory
130
- * write` (on create) and `crtr memory lint`. */
131
- export declare function parseSubstrateFrontmatter(fm: Record<string, unknown> | null): SubstrateSchema | null;
132
- /** Parse a resolved MemoryDoc into a fully-typed SubstrateDoc (schema + the
133
- * resolver's name/scope/path/body). Returns `null` for a non-substrate doc
134
- * (no valid `kind`), so callers can `docs.map(parseSubstrateDoc).filter(...)`. */
135
- export declare function parseSubstrateDoc(doc: MemoryDoc): SubstrateDoc | null;
136
- /** The kind a doc resolves to for `--kind` filtering/matching: the substrate
137
- * kind when the frontmatter parses as a valid substrate doc, else the raw
138
- * frontmatter `kind` string when present (even if not one of the two valid
139
- * kinds — an authoring error, not grounds to silently reclassify it), else
140
- * the legacy default `knowledge` for a frontmatter-less/kindless doc. The
141
- * single coercion `memory read`'s resolution and result display share, so a
142
- * `--kind` filter and the displayed `kind` field never disagree. */
143
- export declare function effectiveDocKind(doc: MemoryDoc): string;
144
- /** The `preview`-rung routing line (design §4): the `when-and-why-to-read`
145
- * field rendered essentially verbatim — it is already authored as the complete
146
- * routing sentence ("When …, this <kind> should be read …"), so there is no
147
- * template to compose. Both boot and on-read render this identical line, so it
148
- * lives once here to prevent drift. Light cleanup normalizes the trailing
149
- * period. */
150
- export declare function previewLine(doc: Pick<SubstrateSchema, 'whenAndWhyToRead'>): string;
151
- /** Tolerant `surfaces` parse: a non-array yields `[]`; invalid entries are
152
- * dropped (bad `on`, bad `at`, a read/memory-read/command/pre-command entry
153
- * left with neither `match` nor — read only — `match-frontmatter`). `match-frontmatter`
154
- * on a non-read event is dropped from the entry, which survives iff it still
155
- * carries a `match`; an invalid entry `gate` is dropped. Lint owns strict
156
- * enforcement; the runtime parser maps over many docs and must never throw. */
157
- export declare function parseSurfaces(v: unknown): SurfaceEntry[];
20
+ export type DocRepresentation = 'leaf-file' | 'directory-index';
21
+ /** Which form a store-relative markdown path takes. */
22
+ export declare function representationForPath(physicalRelativePath: string): DocRepresentation;
23
+ /** Local name derived from a store-relative markdown path: ordering prefixes
24
+ * stripped from every segment and one trailing `INDEX` collapsed. Empty only
25
+ * for a root `INDEX.md`. */
26
+ export declare function localNameFromPath(physicalRelativePath: string): string;
27
+ /** A document's explicit frontmatter `name` as a local name — normalized with
28
+ * one trailing `INDEX` collapsed — or `null` when it carries none. */
29
+ export declare function explicitLocalName(fm: Record<string, unknown> | null | undefined): string | null;
@@ -1 +1 @@
1
- var l=Object.defineProperty;var t=(e,n)=>l(e,"name",{value:n,configurable:!0});import{PROFILE_PROJECT_MEMORY_VALUES as m}from"../../api/dto/profiles.js";const y=["knowledge","preference"],g=["public","friends","private"];function h(e){const n=e?.privacy;return typeof n=="string"&&g.includes(n)?n:"private"}t(h,"effectivePrivacy");function x(e){return typeof e=="string"&&y.includes(e)}t(x,"isDocKind");const A=m;function a(e){return A.indexOf(e)}t(a,"rungRank");function D(e,n){return a(e)>=a(n)}t(D,"rungAtLeast");function _(e,n){return a(e)<=a(n)?e:n}t(_,"minRung");import{normalizeNameSegment as G,normalizeDocName as O,resolveLocalName as P}from"../memory/identity.js";const R=["boot","workspace-open","read","memory-read","command","pre-command"],S=["name","preview","content"];function w(e){return e===null||!x(e.kind)?null:{kind:e.kind,privacy:h(e),whenAndWhyToRead:d(e["when-and-why-to-read"]),shortForm:d(e["short-form"]),unlisted:e.unlisted===!0,surfaces:E(e.surfaces),gate:p(e.gate),slash:e.slash===!0,rationale:k(e.rationale)}}t(w,"parseSubstrateFrontmatter");function b(e){const n=w(e.frontmatter);return n===null?null:{...n,name:e.name,scope:e.scope,plugin:e.plugin,path:e.path,body:e.body,projectMemory:e.projectMemory}}t(b,"parseSubstrateDoc");function M(e){const n=b(e);if(n!==null)return n.kind;const r=e.frontmatter?.kind;return typeof r=="string"?r:"knowledge"}t(M,"effectiveDocKind");function U(e){const n=e.whenAndWhyToRead.trim().replace(/\.+$/,"");return n===""?"":`${n}.`}t(U,"previewLine");function d(e){return typeof e=="string"?e:""}t(d,"strField");function k(e){return typeof e=="string"&&e.trim()!==""?e:void 0}t(k,"parseRationale");function p(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}t(p,"parseGate");function E(e){if(!Array.isArray(e))return[];const n=[];for(const r of e){if(r===null||typeof r!="object"||Array.isArray(r))continue;const i=r,o=i.on;if(typeof o!="string"||!R.includes(o))continue;const u=i.at;if(typeof u!="string"||!S.includes(u))continue;const s=N(i.match),c=o==="read"?p(i["match-frontmatter"]):void 0,f=p(i.gate);(o==="read"||o==="memory-read"||o==="command"||o==="pre-command")&&s===void 0&&c===void 0||n.push({on:o,at:u,...s!==void 0?{match:s}:{},...c!==void 0?{matchFrontmatter:c}:{},...f!==void 0?{gate:f}:{}})}return n}t(E,"parseSurfaces");function N(e){if(typeof e=="string"){const n=e.trim();return n===""?void 0:[n]}if(Array.isArray(e)){const n=e.filter(r=>typeof r=="string"&&r.trim()!=="").map(r=>r.trim());return n.length>0?n:void 0}}t(N,"parseMatchGlobs");export{y as KINDS,g as PRIVACY_LEVELS,A as RUNGS,R as SURFACE_EVENTS,S as SURFACE_RUNGS,M as effectiveDocKind,h as effectivePrivacy,x as isDocKind,_ as minRung,O as normalizeDocName,G as normalizeNameSegment,b as parseSubstrateDoc,w as parseSubstrateFrontmatter,E as parseSurfaces,U as previewLine,P as resolveDocName,D as rungAtLeast,a as rungRank};
1
+ var a=Object.defineProperty;var t=(n,e)=>a(n,"name",{value:e,configurable:!0});import{PROFILE_PROJECT_MEMORY_VALUES as l}from"../../api/dto/profiles.js";const f=["knowledge","preference"];function d(n){return typeof n=="string"&&f.includes(n)}t(d,"isDocKind");const s=l;function r(n){return s.indexOf(n)}t(r,"rungRank");function N(n,e){return r(n)>=r(e)}t(N,"rungAtLeast");function R(n,e){return r(n)<=r(e)?n:e}t(R,"minRung");const m=/^\d{2}-/,o="INDEX";function i(n){return n.replace(m,"")}t(i,"normalizeNameSegment");function g(n){return n.split("/").map(i).join("/")}t(g,"normalizeDocName");function c(n){return n.split("/").filter(e=>e!=="")}t(c,"canonicalSegments");function u(n){const e=c(n);return e[e.length-1]===o&&e.pop(),e.join("/")}t(u,"collapseTrailingIndex");function p(n){return c(n.replace(/\\/g,"/").replace(/\.md$/i,"")).map(i)}t(p,"pathIdentitySegments");function I(n){const e=p(n);return e[e.length-1]===o?"directory-index":"leaf-file"}t(I,"representationForPath");function S(n){return u(p(n).join("/"))}t(S,"localNameFromPath");function _(n){const e=n?.name;return typeof e!="string"||e.trim()===""?null:u(g(e.trim()))}t(_,"explicitLocalName");export{f as KINDS,s as RUNGS,_ as explicitLocalName,d as isDocKind,S as localNameFromPath,R as minRung,I as representationForPath,N as rungAtLeast,r as rungRank};
@@ -30,6 +30,9 @@ export interface NodeConfigSubject {
30
30
  profile: string | null;
31
31
  /** Effective per-run scopes. */
32
32
  scopes: readonly string[];
33
+ /** DERIVED: handles of the repos enclosing `cwd`, nearest first. A rule's
34
+ * `if: {repo: crouter}` holds when any element is `crouter`. */
35
+ repo: readonly string[];
33
36
  }
34
37
  export declare function effectiveScopes(scopes: readonly string[] | null | undefined): string[];
35
38
  /** The scope a cwd resolves into: `project` when scope.ts finds a
@@ -1,3 +1,4 @@
1
+ import type { ObjectRow } from '../graph/types.js';
1
2
  import { type NodeConfigSubject } from './subject-fields.js';
2
3
  export { effectiveScopes, scopeForCwd, profileNameFor } from './subject-fields.js';
3
4
  export type { NodeConfigSubject } from './subject-fields.js';
@@ -9,4 +10,4 @@ export declare function spineDepth(nodeId: string): number;
9
10
  /** Assemble the node-config subject for `nodeId` from its `NodeMeta` + the
10
11
  * derived fields. Returns `null` when the node has no canvas-db row (an
11
12
  * unknown id). Pure aside from the canvas-db + profile-manifest reads. */
12
- export declare function assembleNodeSubject(nodeId: string): NodeConfigSubject | null;
13
+ export declare function assembleNodeSubject(nodeId: string, repos?: readonly ObjectRow[]): NodeConfigSubject | null;
@@ -1 +1 @@
1
- var l=Object.defineProperty;var t=(o,e)=>l(o,"name",{value:e,configurable:!0});import{getNode as p,getRow as i}from"../canvas/index.js";import{effectiveScopes as s,scopeForCwd as f,profileNameFor as a}from"./subject-fields.js";import{effectiveScopes as F,scopeForCwd as N,profileNameFor as S}from"./subject-fields.js";function d(o){let e=o;const n=new Set;let c=0;for(;!n.has(e);){n.add(e);const r=i(e);if(r===null||r.parent==null)break;e=r.parent,c++}return c}t(d,"spineDepth");function h(o){const e=p(o);return e===null?null:{kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,hasManager:(e.parent??null)!==null,cwd:e.cwd,scope:f(e.cwd),orchestration:{depth:d(o)},profile:a(e.profile_id),scopes:s(e.scopes)}}t(h,"assembleNodeSubject");export{h as assembleNodeSubject,F as effectiveScopes,S as profileNameFor,N as scopeForCwd,d as spineDepth};
1
+ var c=Object.defineProperty;var n=(r,o)=>c(r,"name",{value:o,configurable:!0});import{getNode as l,getRow as i}from"../canvas/index.js";import{openDb as f}from"../canvas/db.js";import{reposForCwd as s}from"../graph/repo-sync/repos.js";import{effectiveScopes as a,scopeForCwd as m,profileNameFor as d}from"./subject-fields.js";import{effectiveScopes as x,scopeForCwd as C,profileNameFor as v}from"./subject-fields.js";function u(r){let o=r;const e=new Set;let t=0;for(;!e.has(o);){e.add(o);const p=i(o);if(p===null||p.parent==null)break;o=p.parent,t++}return t}n(u,"spineDepth");function N(r,o){const e=l(r);return e===null?null:{kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,hasManager:(e.parent??null)!==null,cwd:e.cwd,scope:m(e.cwd),orchestration:{depth:u(r)},profile:d(e.profile_id),scopes:a(e.scopes),repo:(o??s(f(),e.cwd)).map(t=>t.name)}}n(N,"assembleNodeSubject");export{N as assembleNodeSubject,x as effectiveScopes,v as profileNameFor,C as scopeForCwd,u as spineDepth};
@@ -1 +1 @@
1
- var a=Object.defineProperty;var i=(e,o)=>a(e,"name",{value:o,configurable:!0});import{covers as f}from"@north-light/crouter-identity";import{ensureAppProfile as l,listProfiles as m}from"../../../core/profiles/manifest.js";function P(e){const o=l(e.grantee).profileId;return{profiles:m().filter(({profileId:t,manifest:r})=>{const n=r.grantee??"app:terminal";if(n===e.grantee)return!0;const p=`crtr:memory:rw:${n}:profile:${t}`;return e.resolved.some(s=>f(s,p))}).map(({profileId:t,manifest:r})=>({profile_id:t,name:r.name,grantee:r.grantee??"app:terminal",default_kind:r.default_kind??"general",default:t===o}))}}i(P,"listAppProfiles");export{P as listAppProfiles};
1
+ var s=Object.defineProperty;var t=(r,o)=>s(r,"name",{value:o,configurable:!0});import{covers as m}from"@north-light/crouter-identity";import{ensureAppProfile as a,listProfiles as l}from"../../../core/profiles/manifest.js";import{resolveRunKind as d}from"../../../core/runtime/launch-target.js";function P(r){const o=a(r.grantee).profileId;return{profiles:l().filter(({profileId:e,manifest:p})=>{const i=p.grantee??"app:terminal";if(i===r.grantee)return!0;const n=`crtr:memory:rw:${i}:profile:${e}`;return r.resolved.some(f=>m(f,n))}).map(e=>({profile_id:e.profileId,name:e.manifest.name,grantee:e.manifest.grantee??"app:terminal",default_kind:d(e),default:e.profileId===o}))}}t(P,"listAppProfiles");export{P as listAppProfiles};
@@ -1,2 +1 @@
1
- var I=Object.defineProperty;var l=(t,o)=>I(t,"name",{value:o,configurable:!0});import{enqueueNodeMail as S}from"../../../core/feed/messages.js";import{join as k}from"node:path";import{createFileBeneath as f,existsBeneath as B,unlinkBeneath as E}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as J,appProcessSandboxed as A}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as P}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as $}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as w}from"./broker-recovery.js";import{isSafeNodeId as N}from"../../../core/canvas/paths.js";import{contextDir as y}from"../../../core/canvas/node-agent-paths.js";import{getNode as m}from"../../../core/canvas/canvas.js";import{isBrokerLive as q}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as O}from"../../../core/runtime/reopen.js";import{reviveNode as L}from"../../../core/runtime/revive.js";import{activeBackgroundBashJobs as T,bashJobPaths as j,isBashJobProcessGroupAlive as R,readJobPgid as C,readJobPgidIdentity as D,isSafeBashJobId as _,readBashNiceness as x,stopBackgroundBashJob as z}from"../../../core/bash-jobs.js";import{ApiError as d}from"../../../api/index.js";import{notFound as M}from"../../../core/errors.js";function g(t){const o=t.params.id;if(o===void 0||!N(o))throw new d(400,"invalid_node_id",`invalid node id: ${JSON.stringify(o)}`);if(m(o)===null)throw M(`unknown node: ${o}`,{received:o});const i=t.params.jobId;if(i!==void 0){if(!_(i))throw new d(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(i)}`);return{nodeId:o,jobId:i,dir:y(o)}}return{nodeId:o,dir:y(o)}}l(g,"requireTarget");async function F(t){const{nodeId:o,dir:n}=g(t);if(t.principal.class!=="broker"||t.principal.node!==o)throw new d(403,"permission_error","only this node\u2019s broker may start a job");const i=t.body;if(!i||typeof i!="object"||Array.isArray(i))throw new d(400,"invalid_request","job.start requires a JSON body");const c=i;w(o,c.expected_execution_id);const e=c.job_id,a=c.cwd,b=c.env;if(typeof e!="string"||!_(e)||typeof a!="string"||!b||typeof b!="object"||Array.isArray(b)||Object.entries(b).some(([s,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)||typeof p!="string"))throw new d(400,"invalid_request","invalid job id, cwd or environment");if(!A())throw new d(400,"invalid_request","job.start is only used with the root launcher");const r=j(n,e);if(![r.jobRun,r.cmdSh,r.jobLog].every(s=>B(r.root,s)))throw new d(404,"job_not_found","job was not prepared by this node");const h=k(r.dir,"job.starting");try{f(r.root,h,"")}catch(s){throw s.code==="EEXIST"?new d(409,"job_already_started","job was already started"):s}let u;try{const s=b,p=$("bash",s,a),v=m(o);return u=await J({nodeId:o,app:v.grantee??"app:terminal",cwd:a,env:s,capture:!1,command:[p,"-c",P,"--",r.cmdSh,r.jobLog,r.jobExit,r.jobRun,r.jobDone,r.jobBg,e,o,p,String(x(n)),process.execPath,"daemon"]}),f(r.root,r.jobPgid,String(u.pid),384),f(r.root,r.jobPgidIdentity,`launcher:${u.pid}`,384),{status:201,body:{pid:u.pid}}}catch(s){if(u!==void 0)try{await u.stop()}catch(p){throw new AggregateError([s,p],`job ${e} launched but could not be recorded or stopped`)}try{E(r.root,h)}catch(p){if(p.code!=="ENOENT")throw p}throw s}}l(F,"handleStart");function G(t){const{nodeId:o,dir:n}=g(t),i=Date.now();return{status:200,body:T(n).map(e=>{const a=C(n,e.jobId)??null;return{job_id:e.jobId,command:e.command,purpose:e.purpose,started_at:new Date(e.startedAtMs).toISOString(),elapsed_ms:Math.max(0,i-e.startedAtMs),pgid:a,pgid_alive:a!==null&&R(a,D(n,e.jobId))}})}}l(G,"handleList");async function H(t){const{nodeId:o,jobId:n,dir:i}=g(t);if(n===void 0)throw new d(400,"invalid_request","a job id is required");const c=t.query.get("foreground")==="1";if(c){if(t.principal.class!=="broker"||t.principal.node!==o)throw new d(403,"permission_error","only this node\u2019s broker may abort its foreground job");w(o,t.body?.expected_execution_id)}const e=await z(i,n,c,o);if(e.kind==="missing")throw new d(404,"job_not_found",`no background job ${n} for ${o}`);if(e.kind==="retired")throw new d(404,"job_not_found",`background job ${n} for ${o} is no longer running`,{log_path:e.logPath});if(e.kind==="not-stoppable")throw new d(409,"job_not_stoppable",`job ${n} recorded no trusted process identity`,{log_path:e.logPath});if(c)return{status:200,body:{node_id:o,job_id:n,signaled:e.signaled}};O(o);const a=j(i,n),b=`Background bash job ${n} was stopped by the user before it finished. Log: ${a.jobLog} Command: ${a.cmdSh}`;S(o,{senderNodeId:null,urgency:"urgent",wake:1,kind:"message",label:b.split(`
2
- `)[0].slice(0,120),bodyJson:{body:b}});const r=m(o);if(r!==null&&!q(r))try{await L(o,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:o,job_id:n,signaled:e.signaled}}}l(H,"handleStop");const po=[{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:F},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:G},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:H}];export{po as bashJobRoutes};
1
+ var k=Object.defineProperty;var h=(e,o)=>k(e,"name",{value:o,configurable:!0});import{killBashJobObject as S,recordBashJobObject as B}from"../../../core/spaces/stop.js";import{readerFor as E}from"../reader.js";import{join as J}from"node:path";import{createFileBeneath as m,existsBeneath as g,unlinkBeneath as P}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as $,appProcessSandboxed as A}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as q}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as O}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as w}from"./broker-recovery.js";import{isSafeNodeId as N}from"../../../core/canvas/paths.js";import{contextDir as _}from"../../../core/canvas/node-agent-paths.js";import{getNode as j}from"../../../core/canvas/canvas.js";import{isBrokerLive as L}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as T}from"../../../core/runtime/reopen.js";import{reviveNode as D}from"../../../core/runtime/revive.js";import{activeBackgroundBashJobs as R,bashJobPaths as y,isBashJobProcessGroupAlive as z,readJobPgid as C,readJobPgidIdentity as F,isSafeBashJobId as v,readBashNiceness as M,stopBackgroundBashJob as G}from"../../../core/bash-jobs.js";import{ApiError as i}from"../../../api/index.js";import{notFound as H}from"../../../core/errors.js";function f(e){const o=e.params.id;if(o===void 0||!N(o))throw new i(400,"invalid_node_id",`invalid node id: ${JSON.stringify(o)}`);if(j(o)===null)throw H(`unknown node: ${o}`,{received:o});const d=e.params.jobId;if(d!==void 0){if(!v(d))throw new i(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(d)}`);return{nodeId:o,jobId:d,dir:_(o)}}return{nodeId:o,dir:_(o)}}h(f,"requireTarget");async function Z(e){const{nodeId:o,dir:t}=f(e);if(e.principal.class!=="broker"||e.principal.node!==o)throw new i(403,"permission_error","only this node\u2019s broker may start a job");const d=e.body;if(!d||typeof d!="object"||Array.isArray(d))throw new i(400,"invalid_request","job.start requires a JSON body");const s=d;w(o,s.expected_execution_id);const r=s.job_id,a=s.cwd,u=s.env;if(typeof r!="string"||!v(r)||typeof a!="string"||!u||typeof u!="object"||Array.isArray(u)||Object.entries(u).some(([c,b])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(c)||typeof b!="string"))throw new i(400,"invalid_request","invalid job id, cwd or environment");if(!A())throw new i(400,"invalid_request","job.start is only used with the root launcher");const n=y(t,r);if(![n.jobRun,n.cmdSh,n.jobLog].every(c=>g(n.root,c)))throw new i(404,"job_not_found","job was not prepared by this node");const p=J(n.dir,"job.starting");try{m(n.root,p,"")}catch(c){throw c.code==="EEXIST"?new i(409,"job_already_started","job was already started"):c}let l;try{const c=u,b=O("bash",c,a),I=j(o);return l=await $({nodeId:o,app:I.grantee??"app:terminal",cwd:a,env:c,capture:!1,command:[b,"-c",q,"--",n.cmdSh,n.jobLog,n.jobExit,n.jobRun,n.jobDone,b,String(M(t)),process.execPath]}),m(n.root,n.jobPgid,String(l.pid),384),m(n.root,n.jobPgidIdentity,`launcher:${l.pid}`,384),{status:201,body:{pid:l.pid}}}catch(c){if(l!==void 0)try{await l.stop()}catch(b){throw new AggregateError([c,b],`job ${r} launched but could not be recorded or stopped`)}try{P(n.root,p)}catch(b){if(b.code!=="ENOENT")throw b}throw c}}h(Z,"handleStart");function U(e){const{nodeId:o,dir:t}=f(e),d=Date.now();return{status:200,body:R(t).map(r=>{const a=C(t,r.jobId)??null;return{job_id:r.jobId,command:r.command,purpose:r.purpose,started_at:new Date(r.startedAtMs).toISOString(),elapsed_ms:Math.max(0,d-r.startedAtMs),pgid:a,pgid_alive:a!==null&&z(a,F(t,r.jobId))}})}}h(U,"handleList");async function V(e){const{nodeId:o,jobId:t,dir:d}=f(e);if(t===void 0)throw new i(400,"invalid_request","a job id is required");const s=e.query.get("foreground")==="1";if(s){if(e.principal.class!=="broker"||e.principal.node!==o)throw new i(403,"permission_error","only this node\u2019s broker may abort its foreground job");w(o,e.body?.expected_execution_id)}const r=await G(d,t,s,o);if(r.kind==="missing")throw new i(404,"job_not_found",`no background job ${t} for ${o}`);if(r.kind==="retired")throw new i(404,"job_not_found",`background job ${t} for ${o} is no longer running`,{log_path:r.logPath});if(r.kind==="not-stoppable")throw new i(409,"job_not_stoppable",`job ${t} recorded no trusted process identity`,{log_path:r.logPath});if(s)return{status:200,body:{node_id:o,job_id:t,signaled:r.signaled}};T(o),S(t,n=>{const p=E(n,e);return p.class==="person"?p.person:p.class==="app"?p.app:p.node});const a=j(o);if(a!==null&&!L(a))try{await D(o,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:o,job_id:t,signaled:r.signaled}}}h(V,"handleStop");function X(e){const{nodeId:o,jobId:t,dir:d}=f(e);if(t===void 0)throw new i(400,"invalid_request","a job id is required");if(e.principal.class!=="broker"||e.principal.node!==o)throw new i(403,"permission_error","only this node\u2019s broker may record its job");const s=e.body,r=y(d,t);if(typeof s?.command!="string"||s.job_dir!==r.dir||s.log_path!==r.jobLog)throw new i(400,"invalid_request",`job.background requires command, job_dir ${r.dir} and log_path ${r.jobLog}`);if(!g(r.root,r.jobBg))throw new i(404,"job_not_found",`job ${t} of ${o} is not backgrounded`);const a=s.command;return{status:201,body:{id:B(o,t,{command:a,jobDir:r.dir,logPath:r.jobLog}).id}}}h(X,"handleBackground");const ho=[{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/background",handler:X},{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:Z},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:U},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:V}];export{ho as bashJobRoutes};
@@ -1 +1 @@
1
- var q=Object.defineProperty;var s=(t,e)=>q(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as D,findNodeBySessionFile as L,getNode as y,isWarmSpare as W,listNodeIdentities as G,recordSettledTurn as J,setPresence as x,subscriptionsOf as X,updateNode as S,updateNodeTelemetry as Y}from"../../../core/canvas/canvas.js";import{recordExecutionPid as V}from"../../../core/canvas/executions.js";import{bindSession as z,readLiveSession as U,transferSession as H}from"../../../core/canvas/sessions.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{appForNode as h}from"../../../core/canvas/node-agent-paths.js";import{isPidAlive as Q}from"../../../core/canvas/pid.js";import{editorLabel as T}from"../../../core/canvas/labels.js";import{assembleNodeSubject as P}from"../../../core/substrate/subject.js";import{withCanvasWrite as f}from"../../../core/canvas/db.js";import{notFound as _,usage as d}from"../../../core/errors.js";import{ApiError as Z}from"../../../api/errors.js";import{hasUnseenWakeMail as C}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as ee}from"../../../core/runtime/kickoff.js";import{forkSourceNode as te}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{focusOf as w,tearDownNode as O}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as ne}from"../viewer-presence.js";import{evaluateStop as oe}from"../../../core/runtime/stop-guard.js";import{clearFault as b,recordFault as re}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ie}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as se}from"../../review/finish.js";import{emitEvent as E}from"../../../core/events/emit.js";import{consumePendingPark as ae,recordPendingParkActivity as de}from"../../park-pending.js";import{shouldParkAfterSummary as ce}from"../../park-activity.js";import{ownerOnly as ue}from"../router.js";import{requireCurrentExecution as p}from"./broker-recovery.js";import{ensureRunObserver as le}from"../../runs/observer.js";import{buildContextBearings as pe}from"../../../core/runtime/bearings.js";import{renderPreferencesForNodeSubject as me}from"../../../core/runtime/broker-extension-render.js";import{automaticMemoryTarget as A}from"../../../core/spaces/permissions.js";import{buildRefInventory as fe}from"../../../core/memory/inline-ref-inventory.js";import{clearSessionCache as he}from"../../../core/substrate/session-cache.js";import{insertMemoryReads as be}from"../../../core/canvas/memory-reads.js";import{MAX_MEMORY_READ_EVENTS as F,MAX_MEMORY_READ_TEXT as B}from"./memory-reads.js";import{memoryEvents as ye}from"../../../core/substrate/memory-events.js";import{cloneContextExposureState as R,cloneTranscriptExposureState as _e,emptyContextExposureState as j,exposureTarget as N,freezePreferenceSnapshot as ke,hasTranscriptExposure as we,loadContextExposureState as I,restoreContextExposure as ge,saveContextExposureState as ve,snapshotContextExposure as $}from"../../../core/substrate/injected-store.js";import{renderOnReadDocsForSubject as xe,renderOnCommandDocsForSubject as Se,renderPreCommandDocsForSubject as Pe,demotePreCommandExposures as Oe}from"../../../core/substrate/on-read.js";import{renderConfigChangeDelta as Ae}from"../../../core/substrate/render.js";function l(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} requires a JSON body`);return t}s(l,"objectBody");function Ne(t){const e=l(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw d("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw d("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw d("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw d("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw d("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw d("reviewBoundaryIds must be an array of strings");return e}s(Ne,"parseSessionBoundBody");function Te(t){const e=l(t,"broker settle");if(typeof e.stopReason!="string")throw d("stopReason must be a string");for(const n of["backgroundJobsRunning","pushedFinal"])if(typeof e[n]!="boolean")throw d(`${n} must be a boolean`);return e}s(Te,"parseSettleBody");function Ce(t){const e=l(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw d("outcome must be completed or failed");return e}s(Ce,"parseParkCompleteBody");function Ee(t){const e=l(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw d("expected_execution_id must be a non-empty string");if(typeof e.tokens_in!="number"||!Number.isFinite(e.tokens_in)||e.tokens_in<0)throw d("tokens_in must be a non-negative finite number");if(e.context_tokens!==null&&(typeof e.context_tokens!="number"||!Number.isFinite(e.context_tokens)||e.context_tokens<0))throw d("context_tokens must be a non-negative finite number or null");if(e.last_activity!==null&&typeof e.last_activity!="string")throw d("last_activity must be a string or null");if(typeof e.updated_at!="string"||Number.isNaN(Date.parse(e.updated_at)))throw d("updated_at must be an ISO timestamp");return{...e,updated_at:new Date(e.updated_at).toISOString()}}s(Ee,"parseTelemetryBody");function Fe(t){const e=l(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw d("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw d("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw d("userSelected must be a boolean");return e}s(Fe,"parseModelCommitBody");function m(t){const e=y(t);if(e===null)throw _(`unknown node: ${t}`,{received:t});return e}s(m,"requireNode");function g(t){return{node_id:t.node_id,grantee:h(t.node_id),name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(g,"extensionNode");function Be(t){const e=m(t),n=[],r=new Set([t]);let o=e.parent??null;for(;o!==null&&o!==""&&!r.has(o);){r.add(o);const c=y(o);if(c===null)break;n.unshift(g(c)),o=c.parent??null}const a=X(t).map(c=>y(c.node_id)).filter(c=>c!==null&&c.kind!=="human").sort((c,v)=>c.status===v.status?0:c.status==="active"?-1:v.status==="active"?1:0).map(g),i=typeof e.fork_source_file=="string"?te(e.fork_source_file):null,u=P(t);if(u===null)throw _(`unknown node: ${t}`,{received:t});return{node:g(e),warm_spare:W(t),ancestors:n,children:a,fork_source:i===null?null:g(i),subject:u,report_nodes:G().map(c=>({...c,grantee:h(c.node_id)}))}}s(Be,"extensionState");function M(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(M,"samePersona");function Re(t){const e=l(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw d("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw d("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw d("recap expected must contain name, description, title, icon, and kind strings");return e}s(Re,"parseGeneratedNameBody");function je(t){const e=l(t,"broker persona-ack"),n=s(r=>{const o=e[r];if(typeof o!="object"||o===null||Array.isArray(o)||typeof o.kind!="string"||o.mode!=="base"&&o.mode!=="orchestrator"||o.lifecycle!=="terminal"&&o.lifecycle!=="resident")throw d(`${r} must be a persona state`);return o},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(je,"parsePersonaAckBody");function Ie(t){const e=t.params.id,n=Ne(t.body),r=n.sessionFile===null?null:D(n.sessionFile);return{status:200,body:f(()=>{const a=m(e);if(V(n.executionId,e,n.pid)==="shutdown")return{action:"shutdown"};const i=a.review_binding?.review_id;if(i!==void 0&&!n.reviewBoundaryIds.includes(i))return{action:"shutdown"};if(n.reason==="new"&&a.parent==null)return{action:"relaunch_root"};if(n.reason!=="new"&&a.fork_from!=null&&a.pi_session_id==null&&r===null)return{action:"shutdown"};const u=r===null?null:L(r);if(u!==null&&u.node_id!==e){if(Q(u.pi_pid))return re(e,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${r}: it is owned by live node ${u.node_id}`}),{action:"shutdown"};const c=U(u.node_id);if(c===null||H({fromNodeId:u.node_id,fromBindingId:c.bindingId,toNodeId:e,executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:r})!=="transferred")return{action:"shutdown"}}else if(z(e,{executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:r})==="shutdown")return{action:"shutdown"};return n.reason!=="new"&&(ee(e),a.intent==="refresh"&&k(e,"revive")),{action:"none"}})}}s(Ie,"handleSessionBound");function $e(t,e){const n=y(t);if(n===null){if(e.pushedFinal)return{action:"shutdown"};throw _(`unknown node: ${t}`,{received:t})}if(J(t,new Date().toISOString()),e.stopReason==="quit")return(n.status==="active"||n.status==="idle")&&n.intent===null&&(k(t,"finish"),b(t),w(t)!==null&&O(t),x(t,{pane:null,tmux_session:null,window:null})),{action:"shutdown"};if(e.stopReason!=="stop"&&e.stopReason!=="length")return b(t,{link:"daemon\u2192node"}),n.intent==="refresh"?{action:"shutdown"}:{action:"stay_dormant"};const r={pushedFinal:e.pushedFinal};if(r.pushedFinal||n.status==="done")return b(t),w(t)!==null&&O(t),x(t,{pane:null,tmux_session:null,window:null}),{action:"shutdown"};if(n.intent==="refresh")return b(t),{action:"shutdown"};const o=oe(t,r,e.backgroundJobsRunning);return b(t),o.action==="reprompt"?{action:"reprompt",prompt:o.message}:o.reason==="finished"?C(t)?{action:"stay_dormant"}:{action:"shutdown"}:o.reason!=="awaiting"&&o.reason!=="scheduled"?{action:"stay_dormant"}:w(t)!==null||ne(t)||C(t)?{action:"stay_dormant"}:(k(t,"release"),{action:"shutdown"})}s($e,"settleBroker");function Me(t){const e=t.params.id,n=Te(t.body);p(e,n.expected_execution_id);const r=f(()=>$e(e,n));return r.action!=="reprompt"&&se(e),{status:200,body:r}}s(Me,"handleSettle");function qe(t){const e=t.params.id,n=Ce(t.body);return p(e,n.expected_execution_id),{status:200,body:f(()=>{const o=ae(e);if(o===void 0)return{action:"stay_dormant"};const a=m(e);return ce(e,a,o)?(b(e),k(e,"park"),w(e)!==null&&O(e),x(e,{pane:null,tmux_session:null,window:null}),E({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...K(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}})}}s(qe,"handleParkComplete");function De(t){const e=t.params.id;return p(e,l(t.body,"broker park-activity").expected_execution_id),{status:200,body:f(()=>({activity:de(e)?"recorded":"none"}))}}s(De,"handleParkActivity");function Le(t){const e=t.params.id,n=Ee(t.body);return p(e,n.expected_execution_id),f(()=>{Y(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at})}),{status:204}}s(Le,"handleTelemetry");function We(t){const e=t.params.id,n=Fe(t.body);return p(e,n.expected_execution_id),{status:200,body:{modelOverride:f(()=>ie(m(e),n.spec,n.intent,n.userSelected)).model_override}}}s(We,"handleModelCommit");function Ge(t){const e=t.params.id,n=m(e);return n.run_id&&le(e,n.run_id),{status:200,body:Be(e)}}s(Ge,"handleExtensionState");function Je(t){const e=t.params.id,n=l(t.body,"broker context");if(p(e,n.expected_execution_id),n.mode!=="baseline"&&n.mode!=="compact"&&n.mode!=="preferences")throw d("invalid broker context mode");const r=m(e),o=n.mode==="baseline"?j():I(e),a=n.mode==="compact"&&we(o),i=a?_e(o):n.mode==="preferences"?R(o):j(),u=[],c=n.mode!=="preferences"&&!a?pe(e,N(i,"transcript",u)):"";return i.preferenceSnapshot===null&&ke(i,me(e,P(e),N(i,"system",u),h(e),A({...r,grantee:h(e)}))),{status:200,body:{content:c,compact:a,snapshot:$(i),loads:u}}}s(Je,"handleContext");function Xe(t){const e=t.params.id,n=l(t.body,"broker memory refs");p(e,n.expected_execution_id);const r=m(e);he();const o=fe(A({...r,grantee:h(e)}));return{status:200,body:{refs:o.refs,names:[...o.names]}}}s(Xe,"handleMemoryRefs");function Ye(t){if(t===void 0)return[];if(!Array.isArray(t)||t.length>F)throw d(`loads must be an array of at most ${F} entries`);const e=s((n,r,o)=>{if(typeof n!="string"||n===""||n.length>B)throw d(`loads[${o}].${r} must be a non-empty string of at most ${B} characters`);return n},"field");return t.map((n,r)=>{if(typeof n!="object"||n===null||Array.isArray(n))throw d(`loads[${r}] must be an object`);const o=n,a=Object.keys(o).filter(i=>i!=="name"&&i!=="scope");if(a.length>0)throw d(`loads[${r}] has unknown field: ${a.join(", ")}`);return{name:e(o.name,"name",r),scope:e(o.scope,"scope",r)}})}s(Ye,"parseLoads");function Ve(t,e){if(e.length!==0)try{be(t,ye(e,"loaded"))}catch(n){E({level:"warn",event:"memory_reads.insert_failed",error:n,fields:{node_id:t}})}}s(Ve,"recordLoaded");function ze(t){const e=t.params.id,n=l(t.body,"broker context commit");p(e,n.expected_execution_id);const r=Ye(n.loads);return ve(e,ge(n.snapshot)),Ve(e,r),{status:204}}s(ze,"handleContextCommit");function Ue(t){const e=t.params.id,n=l(t.body,"broker context event");if(p(e,n.expected_execution_id),!["read","command","pre-command","compact","persona"].includes(n.event))throw d("invalid broker context event");if(["read","command","pre-command"].includes(n.event)&&(typeof n.value!="string"||n.value===""))throw d("broker context event requires a value");const r=m(e),o=P(e);if(o===null)throw _(`unknown node: ${e}`);const a=R(I(e)),i=A({...r,grantee:h(e)});if(n.event==="read"&&(typeof n.value!="string"||!n.value.startsWith("/")||i.allowsProject?.(n.value)===!1))throw new Z(403,"scope_missing","read file is outside the run mounts");const u=[],c=N(a,"transcript",u);return{status:200,body:{content:n.event==="read"?xe(o,n.value,c,void 0,i):n.event==="command"?Se(o,n.value,c,void 0,i):n.event==="pre-command"?Pe(o,n.value,c,void 0,i):n.event==="persona"?Ae(o,e,c,h(e),i):(Oe(a,i),""),compact:!1,snapshot:$(a),loads:u}}}s(Ue,"handleContextEvent");function He(t){const e=t.params.id,n=Re(t.body);return p(e,n.expected_execution_id),{status:200,body:f(()=>{const o=m(e);if(n.kind==="initial"){if((o.description??"").trim()!=="")return{applied:!1};const u=S(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:T(u),description:u.description??"",title:u.title??"",icon:u.icon??""}}const a=n.expected;if(o.name!==a.name||(o.description??"")!==a.description||(o.title??"")!==a.title||(o.icon??"")!==a.icon||o.kind!==a.kind)return{applied:!1};const i=S(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:T(i),description:i.description??"",title:i.title??"",icon:i.icon??""}})}}s(He,"handleGeneratedName");function Ke(t){const e=t.params.id,n=je(t.body);return p(e,n.expected_execution_id),{status:200,body:f(()=>{const o=m(e),a={kind:o.kind,mode:o.mode,lifecycle:o.lifecycle},i=o.persona_ack,u=i===void 0?a:{kind:i.kind??o.kind,mode:i.mode,lifecycle:i.lifecycle};return!M(a,n.to)||!M(u,n.from)?{applied:!1}:(S(e,{persona_ack:n.to}),{applied:!0})})}}s(Ke,"handlePersonaAck");const $t=ue([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:Ie},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:Me},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:qe},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:De},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:Le},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:We},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:Ge},{method:"POST",pattern:"/v1/nodes/:id/broker/context",handler:Je},{method:"POST",pattern:"/v1/nodes/:id/broker/memory-refs",handler:Xe},{method:"POST",pattern:"/v1/nodes/:id/broker/context/commit",handler:ze},{method:"POST",pattern:"/v1/nodes/:id/broker/context/event",handler:Ue},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:He},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:Ke}]);export{$t as brokerOperationRoutes};
1
+ var O=Object.defineProperty;var r=(t,e)=>O(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as A,findNodeBySessionFile as T,getNode as _,isWarmSpare as R,listNodeIdentities as I,recordSettledTurn as $,setPresence as w,subscriptionsOf as j,updateNode as g,updateNodeTelemetry as q}from"../../../core/canvas/canvas.js";import{recordExecutionPid as C}from"../../../core/canvas/executions.js";import{bindSession as E,readLiveSession as M,transferSession as D}from"../../../core/canvas/sessions.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{appForNode as P}from"../../../core/canvas/node-agent-paths.js";import{isPidAlive as G}from"../../../core/canvas/pid.js";import{editorLabel as N}from"../../../core/canvas/labels.js";import{assembleNodeSubject as J}from"../../../core/substrate/subject.js";import{withCanvasWrite as l}from"../../../core/canvas/db.js";import{notFound as v,usage as s}from"../../../core/errors.js";import{hasUnseenWakeMail as F}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as W}from"../../../core/runtime/kickoff.js";import{readRoadmap as U}from"../../../core/runtime/roadmap.js";import{forkSourceNode as V}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{focusOf as y,tearDownNode as x}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as Y}from"../viewer-presence.js";import{evaluateStop as z}from"../../../core/runtime/stop-guard.js";import{clearFault as h,recordFault as H}from"../../../core/canvas/recovery.js";import{updateModelRecipe as K}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as Q}from"../../review/finish.js";import{emitEvent as X}from"../../../core/events/emit.js";import{consumePendingPark as Z,recordPendingParkActivity as ee}from"../../park-pending.js";import{shouldParkAfterSummary as te}from"../../park-activity.js";import{ownerOnly as ne}from"../router.js";import{requireCurrentExecution as m}from"./broker-recovery.js";import{ensureRunObserver as oe}from"../../runs/observer.js";function p(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw s(`${e} requires a JSON body`);return t}r(p,"objectBody");function ie(t){const e=p(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw s("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw s("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw s("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw s("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw s("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw s("reviewBoundaryIds must be an array of strings");return e}r(ie,"parseSessionBoundBody");function re(t){const e=p(t,"broker settle");if(typeof e.stopReason!="string")throw s("stopReason must be a string");for(const n of["backgroundJobsRunning","pushedFinal"])if(typeof e[n]!="boolean")throw s(`${n} must be a boolean`);return e}r(re,"parseSettleBody");function se(t){const e=p(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw s("outcome must be completed or failed");return e}r(se,"parseParkCompleteBody");function ae(t){const e=p(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw s("expected_execution_id must be a non-empty string");if(typeof e.tokens_in!="number"||!Number.isFinite(e.tokens_in)||e.tokens_in<0)throw s("tokens_in must be a non-negative finite number");if(e.context_tokens!==null&&(typeof e.context_tokens!="number"||!Number.isFinite(e.context_tokens)||e.context_tokens<0))throw s("context_tokens must be a non-negative finite number or null");if(e.last_activity!==null&&typeof e.last_activity!="string")throw s("last_activity must be a string or null");if(typeof e.updated_at!="string"||Number.isNaN(Date.parse(e.updated_at)))throw s("updated_at must be an ISO timestamp");return{...e,updated_at:new Date(e.updated_at).toISOString()}}r(ae,"parseTelemetryBody");function de(t){const e=p(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw s("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const i=n!==null&&typeof n=="object"?n:void 0;if(i===void 0||typeof i.family!="string"||i.family===""||!["ultra","strong","medium","light"].includes(i.strength))throw s("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw s("userSelected must be a boolean");return e}r(de,"parseModelCommitBody");function f(t){const e=_(t);if(e===null)throw v(`unknown node: ${t}`,{received:t});return e}r(f,"requireNode");function b(t){return{node_id:t.node_id,grantee:P(t.node_id),name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}r(b,"extensionNode");function ue(t){const e=f(t),n=[],i=new Set([t]);let o=e.parent??null;for(;o!==null&&o!==""&&!i.has(o);){i.add(o);const d=_(o);if(d===null)break;n.unshift(b(d)),o=d.parent??null}const a=j(t).map(d=>_(d.node_id)).filter(d=>d!==null&&d.kind!=="human").sort((d,S)=>d.status===S.status?0:d.status==="active"?-1:S.status==="active"?1:0).map(b),c=typeof e.fork_source_file=="string"?V(e.fork_source_file):null,u=J(t);if(u===null)throw v(`unknown node: ${t}`,{received:t});return{node:b(e),warm_spare:R(t),ancestors:n,children:a,fork_source:c===null?null:b(c),subject:u,report_nodes:I().map(d=>({...d,grantee:P(d.node_id)})),roadmap:U(t)}}r(ue,"extensionState");function B(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}r(B,"samePersona");function ce(t){const e=p(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw s("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw s("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(i=>typeof n[i]!="string"))throw s("recap expected must contain name, description, title, icon, and kind strings");return e}r(ce,"parseGeneratedNameBody");function le(t){const e=p(t,"broker persona-ack"),n=r(i=>{const o=e[i];if(typeof o!="object"||o===null||Array.isArray(o)||typeof o.kind!="string"||o.mode!=="base"&&o.mode!=="orchestrator"||o.lifecycle!=="terminal"&&o.lifecycle!=="resident")throw s(`${i} must be a persona state`);return o},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}r(le,"parsePersonaAckBody");function pe(t){const e=t.params.id,n=ie(t.body),i=n.sessionFile===null?null:A(n.sessionFile);return{status:200,body:l(()=>{const a=f(e);if(C(n.executionId,e,n.pid)==="shutdown")return{action:"shutdown"};const c=a.review_binding?.review_id;if(c!==void 0&&!n.reviewBoundaryIds.includes(c))return{action:"shutdown"};if(n.reason==="new"&&a.parent==null)return{action:"relaunch_root"};if(n.reason!=="new"&&a.fork_from!=null&&a.pi_session_id==null&&i===null)return{action:"shutdown"};const u=i===null?null:T(i);if(u!==null&&u.node_id!==e){if(G(u.pi_pid))return H(e,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${i}: it is owned by live node ${u.node_id}`}),{action:"shutdown"};const d=M(u.node_id);if(d===null||D({fromNodeId:u.node_id,fromBindingId:d.bindingId,toNodeId:e,executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:i})!=="transferred")return{action:"shutdown"}}else if(E(e,{executionId:n.executionId,sessionId:n.piSessionId,transcriptPath:i})==="shutdown")return{action:"shutdown"};return n.reason!=="new"&&(W(e),a.intent==="refresh"&&k(e,"revive")),{action:"none"}})}}r(pe,"handleSessionBound");function me(t,e){const n=_(t);if(n===null){if(e.pushedFinal)return{action:"shutdown"};throw v(`unknown node: ${t}`,{received:t})}if($(t,new Date().toISOString()),e.stopReason==="quit")return(n.status==="active"||n.status==="idle")&&n.intent===null&&(k(t,"finish"),h(t),y(t)!==null&&x(t),w(t,{pane:null,tmux_session:null,window:null})),{action:"shutdown"};if(e.stopReason!=="stop"&&e.stopReason!=="length")return h(t,{link:"daemon\u2192node"}),n.intent==="refresh"?{action:"shutdown"}:{action:"stay_dormant"};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||n.status==="done")return h(t),y(t)!==null&&x(t),w(t,{pane:null,tmux_session:null,window:null}),{action:"shutdown"};if(n.intent==="refresh")return h(t),{action:"shutdown"};const o=z(t,i,e.backgroundJobsRunning);return h(t),o.action==="reprompt"?{action:"reprompt",prompt:o.message}:o.reason==="finished"?F(t)?{action:"stay_dormant"}:{action:"shutdown"}:o.reason!=="awaiting"&&o.reason!=="scheduled"?{action:"stay_dormant"}:y(t)!==null||Y(t)||F(t)?{action:"stay_dormant"}:(k(t,"release"),{action:"shutdown"})}r(me,"settleBroker");function fe(t){const e=t.params.id,n=re(t.body);m(e,n.expected_execution_id);const i=l(()=>me(e,n));return i.action!=="reprompt"&&Q(e),{status:200,body:i}}r(fe,"handleSettle");function he(t){const e=t.params.id,n=se(t.body);return m(e,n.expected_execution_id),{status:200,body:l(()=>{const o=Z(e);if(o===void 0)return{action:"stay_dormant"};const a=f(e);return te(e,a,o)?(h(e),k(e,"park"),y(e)!==null&&x(e),w(e,{pane:null,tmux_session:null,window:null}),X({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...L(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}})}}r(he,"handleParkComplete");function _e(t){const e=t.params.id;return m(e,p(t.body,"broker park-activity").expected_execution_id),{status:200,body:l(()=>({activity:ee(e)?"recorded":"none"}))}}r(_e,"handleParkActivity");function ke(t){const e=t.params.id,n=ae(t.body);return m(e,n.expected_execution_id),l(()=>{q(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at})}),{status:204}}r(ke,"handleTelemetry");function ye(t){const e=t.params.id,n=de(t.body);return m(e,n.expected_execution_id),{status:200,body:{modelOverride:l(()=>K(f(e),n.spec,n.intent,n.userSelected)).model_override}}}r(ye,"handleModelCommit");function be(t){const e=t.params.id,n=f(e);return n.run_id&&oe(e,n.run_id),{status:200,body:ue(e)}}r(be,"handleExtensionState");function we(t){const e=t.params.id,n=ce(t.body);return m(e,n.expected_execution_id),{status:200,body:l(()=>{const o=f(e);if(n.kind==="initial"){if((o.description??"").trim()!=="")return{applied:!1};const u=g(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:N(u),description:u.description??"",title:u.title??"",icon:u.icon??""}}const a=n.expected;if(o.name!==a.name||(o.description??"")!==a.description||(o.title??"")!==a.title||(o.icon??"")!==a.icon||o.kind!==a.kind)return{applied:!1};const c=g(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:N(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}r(we,"handleGeneratedName");function ge(t){const e=t.params.id,n=le(t.body);return m(e,n.expected_execution_id),{status:200,body:l(()=>{const o=f(e),a={kind:o.kind,mode:o.mode,lifecycle:o.lifecycle},c=o.persona_ack,u=c===void 0?a:{kind:c.kind??o.kind,mode:c.mode,lifecycle:c.lifecycle};return!B(a,n.to)||!B(u,n.from)?{applied:!1}:(g(e,{persona_ack:n.to}),{applied:!0})})}}r(ge,"handlePersonaAck");const Ke=ne([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:pe},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:fe},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:he},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:_e},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:ke},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:ye},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:be},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:we},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:ge}]);export{Ke as brokerOperationRoutes};
@@ -1,6 +1,6 @@
1
- var H=Object.defineProperty;var c=(t,e)=>H(t,"name",{value:e,configurable:!0});import{graphNodes as q,listNodes as M,pruneNodes as x,pruneToLimit as J,rosterEdges as N,rosterNodes as z}from"../../../core/canvas/canvas.js";import{activeBackgroundBashJobs as Q}from"../../../core/bash-jobs.js";import{contextDir as U}from"../../../core/canvas/node-agent-paths.js";import{nowIso as k}from"../../../core/fs-utils.js";import{isPidPresent as Y}from"../../../core/canvas/pid.js";import{dashboardRowsAllFromSource as V,enrichRowsFromSource as W}from"../../../core/canvas/render-source.js";import{localCanvasSource as j}from"../../../core/canvas/source.js";import{ticketCountsForNodes as B,ticketsAcrossCanvas as X}from"../../../core/canvas/attention.js";import{buildCorpus as Z,groupCorpus as ee,resolveRef as te}from"../../../core/canvas/history.js";import{listFocuses as O,reapEmptyNodes as ne}from"../../../core/runtime/placement.js";import{boundFleet as oe}from"../../../core/runtime/fleet.js";import{retentionHold as re}from"../../reconcilers/live-obligation.js";import{notFound as se,usage as p}from"../../../core/errors.js";import{toGraphNodeDTO as ie}from"../map.js";import{canReadNode as L,canReadRun as de}from"../router.js";import{ApiError as ae}from"../../../api/errors.js";function g(t){return t.principal.class==="person"?null:new Set(M().filter(e=>L(t.principal,e.grantee??"app:terminal")).map(e=>e.node_id))}c(g,"visibleNodes");function T(t){return t.principal.class==="person"?null:new Set(M().filter(e=>e.run_id?de(t.principal,e.grantee??"app:terminal"):L(t.principal,e.grantee??"app:terminal")).map(e=>e.node_id))}c(T,"visibleHistoryNodes");function ce(t){const e=g(t);return{status:200,body:{items:X().filter(n=>e===null||e.has(n.node_id)).map(n=>({node_id:n.node_id,name:n.name,cwd:n.cwd,count:n.count,subjects:n.subjects}))}}}c(ce,"handleAttention");function le(t){const e=t.body;if(e===null||typeof e!="object"||!Array.isArray(e.node_ids))throw p("attention count request requires node_ids: string[]");const o=e.node_ids;if(!o.every(i=>typeof i=="string"))throw p("attention count request node_ids must contain only strings");const n=g(t);return{status:200,body:{counts:B(o.filter(i=>n===null||n.has(i)))}}}c(le,"handleAttentionCounts");function E(t){return Buffer.from(String(t),"utf8").toString("base64")}c(E,"encodeCursor");function F(t){const e=Number(Buffer.from(t,"base64").toString("utf8"));if(!Number.isInteger(e)||e<0)throw p(`invalid cursor: ${t}`);return e}c(F,"decodeCursor");function ue(t,e,o){const s=t.loadBody().split(`
2
- `);if(e.length>0){const a=s.findIndex(u=>{const l=u.toLowerCase();return e.some(m=>l.includes(m))});if(a!==-1)return s.slice(a,a+o).map(u=>u.trim()).filter(u=>u!=="").join(" \u23CE ")}const i=s.map(a=>a.trim()).filter(a=>a!=="").slice(0,o).join(" \u23CE ");return i!==""?i:t.title}c(ue,"snippet");function fe(t,e,o){const n=[...t];return e==="relevance"&&o!==void 0?n.sort((s,i)=>(o.get(i.ref)??0)-(o.get(s.ref)??0)||i.tsMs-s.tsMs||s.ref.localeCompare(i.ref)):e==="oldest"?n.sort((s,i)=>s.tsMs-i.tsMs||s.ref.localeCompare(i.ref)):n.sort((s,i)=>i.tsMs-s.tsMs||s.ref.localeCompare(i.ref)),n}c(fe,"sortArtifacts");function pe(t){if(t==null)return{};if(typeof t!="object")throw p("history search body must be a JSON object");return t}c(pe,"parseSearchBody");function me(t){if(t===null||typeof t!="object")throw p("history grep body must be a JSON object");const e=t;if(typeof e.pattern!="string"||e.pattern==="")throw p("history grep body requires a non-empty pattern");return e}c(me,"parseGrepBody");function $(t,e){const o={cwd:t.cwd,allCwds:t.all_cwds===!0,under:t.under,nodes:t.nodes},n={types:t.types,reportKind:t.report_kind,kinds:t.kinds,statuses:t.statuses,sinceMs:t.since_ms,untilMs:t.until_ms,origins:t.origins,roles:t.roles,from:t.from},s=T(e);return Z(o,n).filter(i=>s===null||s.has(i.nodeId))}c($,"buildCorpusFromQuery");function he(t){if(t==null)return{};if(typeof t!="object")throw p("history stats body must be a JSON object");return t}c(he,"parseStatsBody");const I=["origin","node","kind","day","type","role"];function ye(t){const e=he(t.body),o=e.group_by??"type";if(!I.includes(o))throw p(`--group-by must be one of: ${I.join(", ")}; received: ${String(e.group_by)}`);const n=$(e,t),s=ee(n,o);return{status:200,body:{group_by:o,groups:s,total:s.reduce((a,u)=>a+u.count,0),scanned:n.length}}}c(ye,"handleHistoryStats");function _e(t){const e=me(t.body),o=Math.min(100,Math.max(1,e.limit??20)),n=$(e,t),s=e.cursor!==void 0?F(e.cursor):0;let i;try{i=new RegExp(e.pattern,"i")}catch{throw p(`invalid regex pattern: ${e.pattern}`)}const a=[];for(const r of n)r.loadBody().split(`
3
- `).forEach((y,b)=>{i.test(y)&&a.push({ref:r.ref,node:`${r.nodeName} (${r.nodeId})`,ts:r.ts,line:b+1,text:y.trim()})});a.sort((r,d)=>r.ref.localeCompare(d.ref)||r.line-d.line);const u=a.slice(s,s+o),l=s+o<a.length?E(s+o):null;return{status:200,body:{hits:u,next_cursor:l,total:a.length}}}c(_e,"handleHistoryGrep");function be(t){const e=pe(t.body),o=(e.query??"").trim(),n=e.weigh_body===!0,s=e.full===!0,i=Math.max(1,e.snippet_lines??1),a=Math.min(100,Math.max(1,e.limit??20)),u=$(e,t),l=e.cursor!==void 0?F(e.cursor):0,m=o.toLowerCase().split(/\s+/).filter(f=>f.length>0);let r=u,d;const y=e.sort??(m.length>0?"relevance":"recency");if(m.length>0&&y==="relevance"){d=new Map;const f=[];for(const h of u){const C=h.title.toLowerCase(),K=h.nodeName.toLowerCase(),D=h.nodeDesc.toLowerCase(),R=n?h.loadBody().toLowerCase():null;let _=0;for(const w of m)C.includes(w)&&(_+=10),K.includes(w)&&(_+=5),D.includes(w)&&(_+=3),R!==null&&R.includes(w)&&(_+=1);_>0&&(d.set(h.ref,_),f.push(h))}r=f}else m.length>0&&(r=u.filter(f=>{const h=`${f.title}
1
+ var x=Object.defineProperty;var c=(t,e)=>x(t,"name",{value:e,configurable:!0});import{graphNodes as q,listNodes as M,pruneNodes as J,pruneToLimit as K,rosterEdges as N,rosterNodes as z}from"../../../core/canvas/canvas.js";import{activeBackgroundBashJobs as Q}from"../../../core/bash-jobs.js";import{contextDir as U}from"../../../core/canvas/node-agent-paths.js";import{nowIso as k}from"../../../core/fs-utils.js";import{isPidPresent as Y}from"../../../core/canvas/pid.js";import{dashboardRowsAllFromSource as V,enrichRowsFromSource as W}from"../../../core/canvas/render-source.js";import{localCanvasSource as j}from"../../../core/canvas/source.js";import{ticketCountsForNodes as B,ticketsAcrossCanvas as X}from"../../../core/canvas/attention.js";import{buildCorpus as Z,groupCorpus as ee,resolveRef as te}from"../../../core/canvas/history.js";import{listFocuses as O,reapEmptyNodes as ne}from"../../../core/runtime/placement.js";import{boundFleet as oe}from"../../../core/runtime/fleet.js";import{retentionHold as se}from"../../reconcilers/live-obligation.js";import{notFound as re,usage as m}from"../../../core/errors.js";import{toGraphNodeDTO as ie}from"../map.js";import{canReadNode as L,canReadRun as de}from"../router.js";import{ApiError as ae}from"../../../api/errors.js";function g(t){return t.principal.class==="person"?null:new Set(M().filter(e=>L(t.principal,e.grantee??"app:terminal")).map(e=>e.node_id))}c(g,"visibleNodes");function T(t){return t.principal.class==="person"?null:new Set(M().filter(e=>e.run_id?de(t.principal,e.grantee??"app:terminal"):L(t.principal,e.grantee??"app:terminal")).map(e=>e.node_id))}c(T,"visibleHistoryNodes");function ce(t){const e=g(t);return{status:200,body:{items:X().filter(o=>e===null||e.has(o.node_id)).map(o=>({node_id:o.node_id,name:o.name,cwd:o.cwd,count:o.count,subjects:o.subjects}))}}}c(ce,"handleAttention");function le(t){const e=t.body;if(e===null||typeof e!="object"||!Array.isArray(e.node_ids))throw m("attention count request requires node_ids: string[]");const n=e.node_ids;if(!n.every(i=>typeof i=="string"))throw m("attention count request node_ids must contain only strings");const o=g(t);return{status:200,body:{counts:B(n.filter(i=>o===null||o.has(i)))}}}c(le,"handleAttentionCounts");function E(t){return Buffer.from(String(t),"utf8").toString("base64")}c(E,"encodeCursor");function I(t){const e=Number(Buffer.from(t,"base64").toString("utf8"));if(!Number.isInteger(e)||e<0)throw m(`invalid cursor: ${t}`);return e}c(I,"decodeCursor");function ue(t,e,n){const r=t.loadBody().split(`
2
+ `);if(e.length>0){const a=r.findIndex(u=>{const l=u.toLowerCase();return e.some(p=>l.includes(p))});if(a!==-1)return r.slice(a,a+n).map(u=>u.trim()).filter(u=>u!=="").join(" \u23CE ")}const i=r.map(a=>a.trim()).filter(a=>a!=="").slice(0,n).join(" \u23CE ");return i!==""?i:t.title}c(ue,"snippet");function fe(t,e,n){const o=[...t];return e==="relevance"&&n!==void 0?o.sort((r,i)=>(n.get(i.ref)??0)-(n.get(r.ref)??0)||i.tsMs-r.tsMs||r.ref.localeCompare(i.ref)):e==="oldest"?o.sort((r,i)=>r.tsMs-i.tsMs||r.ref.localeCompare(i.ref)):o.sort((r,i)=>i.tsMs-r.tsMs||r.ref.localeCompare(i.ref)),o}c(fe,"sortArtifacts");function me(t){if(t==null)return{};if(typeof t!="object")throw m("history search body must be a JSON object");return t}c(me,"parseSearchBody");function pe(t){if(t===null||typeof t!="object")throw m("history grep body must be a JSON object");const e=t;if(typeof e.pattern!="string"||e.pattern==="")throw m("history grep body requires a non-empty pattern");return e}c(pe,"parseGrepBody");function R(t,e){const n={cwd:t.cwd,allCwds:t.all_cwds===!0,under:t.under,nodes:t.nodes},o={types:t.types,kinds:t.kinds,statuses:t.statuses,sinceMs:t.since_ms,untilMs:t.until_ms,origins:t.origins,roles:t.roles,from:t.from},r=T(e);return Z(n,o).filter(i=>r===null||r.has(i.nodeId))}c(R,"buildCorpusFromQuery");function he(t){if(t==null)return{};if(typeof t!="object")throw m("history stats body must be a JSON object");return t}c(he,"parseStatsBody");const F=["origin","node","kind","day","type","role"];function ye(t){const e=he(t.body),n=e.group_by??"type";if(!F.includes(n))throw m(`--group-by must be one of: ${F.join(", ")}; received: ${String(e.group_by)}`);const o=R(e,t),r=ee(o,n);return{status:200,body:{group_by:n,groups:r,total:r.reduce((a,u)=>a+u.count,0),scanned:o.length}}}c(ye,"handleHistoryStats");function _e(t){const e=pe(t.body),n=Math.min(100,Math.max(1,e.limit??20)),o=R(e,t),r=e.cursor!==void 0?I(e.cursor):0;let i;try{i=new RegExp(e.pattern,"i")}catch{throw m(`invalid regex pattern: ${e.pattern}`)}const a=[];for(const s of o)s.loadBody().split(`
3
+ `).forEach((y,b)=>{i.test(y)&&a.push({ref:s.ref,node:`${s.nodeName} (${s.nodeId})`,ts:s.ts,line:b+1,text:y.trim()})});a.sort((s,d)=>s.ref.localeCompare(d.ref)||s.line-d.line);const u=a.slice(r,r+n),l=r+n<a.length?E(r+n):null;return{status:200,body:{hits:u,next_cursor:l,total:a.length}}}c(_e,"handleHistoryGrep");function be(t){const e=me(t.body),n=(e.query??"").trim(),o=e.weigh_body===!0,r=e.full===!0,i=Math.max(1,e.snippet_lines??1),a=Math.min(100,Math.max(1,e.limit??20)),u=R(e,t),l=e.cursor!==void 0?I(e.cursor):0,p=n.toLowerCase().split(/\s+/).filter(f=>f.length>0);let s=u,d;const y=e.sort??(p.length>0?"relevance":"recency");if(p.length>0&&y==="relevance"){d=new Map;const f=[];for(const h of u){const C=h.title.toLowerCase(),D=h.nodeName.toLowerCase(),H=h.nodeDesc.toLowerCase(),$=o?h.loadBody().toLowerCase():null;let _=0;for(const w of p)C.includes(w)&&(_+=10),D.includes(w)&&(_+=5),H.includes(w)&&(_+=3),$!==null&&$.includes(w)&&(_+=1);_>0&&(d.set(h.ref,_),f.push(h))}s=f}else p.length>0&&(s=u.filter(f=>{const h=`${f.title}
4
4
  ${f.nodeName}
5
- ${f.nodeDesc}${n?`
6
- `+f.loadBody():""}`.toLowerCase();return m.some(C=>h.includes(C))}));const b=fe(r,y,d),P=b.slice(l,l+a),A=l+a<b.length?E(l+a):null;return{status:200,body:{hits:P.map(f=>{const h={ref:f.ref,node:`${f.nodeName} (${f.nodeId})`,kind:f.nodeKind,source:f.source==="report"&&f.reportKind?`report:${f.reportKind}`:f.source,ts:f.ts};return y==="relevance"&&d!==void 0&&(h.score=d.get(f.ref)??0),s?h.body=f.loadBody():h.snippet=ue(f,m,i),h}),next_cursor:A,total:b.length}}}c(be,"handleHistorySearch");function ge(t){const e=(t.query.get("ref")??"").trim(),o=t.query.get("frontmatter")==="true";if(!e.includes(":"))throw p(`ref must be <node-id>:<relpath>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search` or `crtr node inspect artifacts <node-id>`."});let n;try{n=te(e)}catch(l){throw p(`ref rejected: ${l.message}`,{received:e,next:"Refs come verbatim from `crtr canvas history search`; do not hand-construct relpaths."})}if(n===null)throw se(`no artifact for ref: ${e}`,{ref:e,next:"The node or file may not exist. Re-run `crtr canvas history search` for a current ref, or `crtr node inspect artifacts <node-id>` to list a node's artifacts."});if(T(t)?.has(n.nodeId)===!1)throw new ae(404,"not_found","artifact not found");const s=n.source==="report"&&n.reportKind?`report:${n.reportKind}`:n.source,a=(t.query.get("format")==="raw"||o)&&n.raw!==null?n.raw:n.body;return{status:200,body:{ref:e,node:`${n.nodeName} (${n.nodeId})`,source:s,ts:n.ts,content:a}}}c(ge,"handleHistoryRead");function ve(t){for(const[n]of t.query)if(n!=="live")throw p(`unknown snapshot query parameter: ${n}`);const e=t.query.getAll("live");if(e.length>1)throw p("live must appear at most once");const o=e[0];if(o===void 0||o==="false"||o==="0")return!1;if(o==="true"||o==="1")return!0;throw p("live must be true or false")}c(ve,"snapshotLiveOnly");async function we(t){const e=new Set(O().map(r=>r.node_id)),o=g(t),n=(await V(j,e,ve(t))).filter(r=>o===null||o.has(r.node_id)),s=B(n.map(r=>r.node_id));await W(j,n,s);const i=n.map(r=>{const d=r.srcRow,y=d?.host_kind??"tmux";return{node_id:r.node_id,name:r.name,title:r.handle??r.name,description:r.description??null,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle??d?.lifecycle,status:r.status,cwd:r.cwd,profile_id:r.profile_id??null,parent:d?.parent??null,created:r.created,host_kind:y,enterable:y==="broker",attention_count:r.asks,...d?.cycles!=null?{cycles:d.cycles}:{},...r.mtimeMs!==void 0?{last_activity:new Date(r.mtimeMs).toISOString()}:{},ctx_tokens:r.ctx_tokens,streaming:r.streaming??!1,jobs_active:d!==void 0&&Y(d.pi_pid)?Q(U(r.node_id)).length:0,waiting_for:d?.waiting_for??null,hanging:r.hanging??null,viewed:r.viewed??!1,final_report:d?.final_report??null,finalized_at:d?.finalized_at??null}}),a=new Map;for(const r of N()){const d=a.get(r.from_id);d===void 0?a.set(r.from_id,[r.to_id]):d.push(r.to_id)}const u=new Set(n.map(r=>r.node_id)),l=Object.fromEntries(n.map(r=>[r.node_id,(a.get(r.node_id)??[]).filter(d=>u.has(d))]));return{status:200,body:{generated_at:k(),nodes:i,subscriptions:l}}}c(we,"handleSnapshot");function G(){const t=z().map(o=>{const n=o.host_kind??"tmux";return{node_id:o.node_id,name:o.name,kind:o.kind,mode:o.mode,lifecycle:o.lifecycle,status:o.status,cwd:o.cwd,host_kind:n,enterable:n==="broker",parent:o.parent,created:o.created}}),e=N().map(o=>({from_id:o.from_id,to_id:o.to_id,active:o.active,created:o.created}));return{generated_at:k(),nodes:t,edges:e}}c(G,"buildRoster");let v=null,S=null;function Se(){return v===null?(v=Promise.resolve().then(()=>G()).finally(()=>{v=null}),v):(S===null&&(S=v.then(()=>G()).finally(()=>{S=null})),S)}c(Se,"rosterCoalesced");async function Ce(t){const e=await Se(),o=g(t);return o===null?{status:200,body:e}:{status:200,body:{...e,nodes:e.nodes.filter(n=>o.has(n.node_id)),edges:e.edges.filter(n=>o.has(n.from_id)&&o.has(n.to_id))}}}c(Ce,"handleRoster");function Ne(t){const e=g(t);return{status:200,body:{generated_at:k(),nodes:q().filter(n=>e===null||e.has(n.node_id)).map(ie),edges:N().filter(n=>e===null||e.has(n.from_id)&&e.has(n.to_id)).map(n=>({from_id:n.from_id,to_id:n.to_id,active:n.active,created:n.created})),focused_node_ids:O().map(n=>n.node_id).filter(n=>e===null||e.has(n))}}}c(Ne,"handleGraph");function ke(t){if(t==null)return{};if(typeof t!="object")throw p("prune body must be a JSON object");const e=t,o=c(r=>{const d=e[r];if(d!==void 0){if(typeof d!="number"||!Number.isFinite(d))throw p(`${r} must be a number`);return d}},"num"),n=c(r=>{const d=e[r];if(d!==void 0){if(typeof d!="boolean")throw p(`${r} must be a boolean`);return d}},"bool"),s={},i=o("limit");i!==void 0&&(s.limit=i);const a=o("ttl_days");a!==void 0&&(s.ttl_days=a);const u=n("include_stale");u!==void 0&&(s.include_stale=u);const l=n("empty");l!==void 0&&(s.empty=l);const m=n("dry_run");return m!==void 0&&(s.dry_run=m),s}c(ke,"parsePruneBody");function $e(t){const e=ke(t.body),o=e.ttl_days??14,n=e.dry_run??!1,s=re(oe());let i;return e.limit!==void 0?i=J({maxNodes:e.limit,held:s,dryRun:n}).pruned.map(l=>({node_id:l.node_id,status:l.status,created:l.created})):e.empty===!0?i=ne({dryRun:n}).map(l=>({node_id:l,status:"empty",created:""})):i=x({ttlDays:o,held:s,dryRun:n,includeStale:e.include_stale??!1}).pruned.map(l=>({node_id:l.node_id,status:l.status,created:l.created})),{status:200,body:{pruned:i,dry_run:n,ttl_days:o}}}c($e,"handlePrune");const ze=[{method:"GET",pattern:"/v1/canvas/attention",handler:ce},{method:"POST",pattern:"/v1/canvas/attention/counts",handler:le},{method:"POST",pattern:"/v1/canvas/history/search",handler:be},{method:"POST",pattern:"/v1/canvas/history/grep",handler:_e},{method:"GET",pattern:"/v1/canvas/history/read",handler:ge},{method:"POST",pattern:"/v1/canvas/history/stats",handler:ye},{method:"GET",pattern:"/v1/canvas/snapshot",handler:we},{method:"GET",pattern:"/v1/canvas/roster",handler:Ce},{method:"GET",pattern:"/v1/canvas/graph",handler:Ne},{method:"POST",pattern:"/v1/canvas/prune",ownerOnly:!0,handler:$e}];export{ze as canvasRoutes};
5
+ ${f.nodeDesc}${o?`
6
+ `+f.loadBody():""}`.toLowerCase();return p.some(C=>h.includes(C))}));const b=fe(s,y,d),P=b.slice(l,l+a),A=l+a<b.length?E(l+a):null;return{status:200,body:{hits:P.map(f=>{const h={ref:f.ref,node:`${f.nodeName} (${f.nodeId})`,kind:f.nodeKind,source:f.source,ts:f.ts};return y==="relevance"&&d!==void 0&&(h.score=d.get(f.ref)??0),r?h.body=f.loadBody():h.snippet=ue(f,p,i),h}),next_cursor:A,total:b.length}}}c(be,"handleHistorySearch");function ge(t){const e=(t.query.get("ref")??"").trim();if(!e.includes(":"))throw m(`ref must be <node-id>:inbox/<n>, <node-id>:session, or <node-id>:session/<n>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search`. Reports and documents are `crtr canvas read <name>`."});const n=te(e);if(n===null)throw re(`no inbox entry or message for ref: ${e}`,{ref:e,next:"Re-run `crtr canvas history search` for a current ref. Reports and documents are `crtr canvas read <name>`."});if(T(t)?.has(n.nodeId)===!1)throw new ae(404,"not_found","artifact not found");const o=n.source,i=t.query.get("format")==="raw"&&n.raw!==null?n.raw:n.body;return{status:200,body:{ref:e,node:`${n.nodeName} (${n.nodeId})`,source:o,ts:n.ts,content:i}}}c(ge,"handleHistoryRead");function ve(t){for(const[o]of t.query)if(o!=="live")throw m(`unknown snapshot query parameter: ${o}`);const e=t.query.getAll("live");if(e.length>1)throw m("live must appear at most once");const n=e[0];if(n===void 0||n==="false"||n==="0")return!1;if(n==="true"||n==="1")return!0;throw m("live must be true or false")}c(ve,"snapshotLiveOnly");async function we(t){const e=new Set(O().map(s=>s.node_id)),n=g(t),o=(await V(j,e,ve(t))).filter(s=>n===null||n.has(s.node_id)),r=B(o.map(s=>s.node_id));await W(j,o,r);const i=o.map(s=>{const d=s.srcRow,y=d?.host_kind??"tmux";return{node_id:s.node_id,name:s.name,title:s.handle??s.name,description:s.description??null,kind:s.kind,mode:s.mode,lifecycle:s.lifecycle??d?.lifecycle,status:s.status,cwd:s.cwd,profile_id:s.profile_id??null,parent:d?.parent??null,created:s.created,host_kind:y,enterable:y==="broker",attention_count:s.asks,...d?.cycles!=null?{cycles:d.cycles}:{},...s.mtimeMs!==void 0?{last_activity:new Date(s.mtimeMs).toISOString()}:{},ctx_tokens:s.ctx_tokens,streaming:s.streaming??!1,jobs_active:d!==void 0&&Y(d.pi_pid)?Q(U(s.node_id)).length:0,waiting_for:d?.waiting_for??null,hanging:s.hanging??null,viewed:s.viewed??!1,final_report:d?.final_report??null,finalized_at:d?.finalized_at??null}}),a=new Map;for(const s of N()){const d=a.get(s.from_id);d===void 0?a.set(s.from_id,[s.to_id]):d.push(s.to_id)}const u=new Set(o.map(s=>s.node_id)),l=Object.fromEntries(o.map(s=>[s.node_id,(a.get(s.node_id)??[]).filter(d=>u.has(d))]));return{status:200,body:{generated_at:k(),nodes:i,subscriptions:l}}}c(we,"handleSnapshot");function G(){const t=z().map(n=>{const o=n.host_kind??"tmux";return{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:o,enterable:o==="broker",parent:n.parent,created:n.created}}),e=N().map(n=>({from_id:n.from_id,to_id:n.to_id,active:n.active,created:n.created}));return{generated_at:k(),nodes:t,edges:e}}c(G,"buildRoster");let v=null,S=null;function Se(){return v===null?(v=Promise.resolve().then(()=>G()).finally(()=>{v=null}),v):(S===null&&(S=v.then(()=>G()).finally(()=>{S=null})),S)}c(Se,"rosterCoalesced");async function Ce(t){const e=await Se(),n=g(t);return n===null?{status:200,body:e}:{status:200,body:{...e,nodes:e.nodes.filter(o=>n.has(o.node_id)),edges:e.edges.filter(o=>n.has(o.from_id)&&n.has(o.to_id))}}}c(Ce,"handleRoster");function Ne(t){const e=g(t);return{status:200,body:{generated_at:k(),nodes:q().filter(o=>e===null||e.has(o.node_id)).map(ie),edges:N().filter(o=>e===null||e.has(o.from_id)&&e.has(o.to_id)).map(o=>({from_id:o.from_id,to_id:o.to_id,active:o.active,created:o.created})),focused_node_ids:O().map(o=>o.node_id).filter(o=>e===null||e.has(o))}}}c(Ne,"handleGraph");function ke(t){if(t==null)return{};if(typeof t!="object")throw m("prune body must be a JSON object");const e=t,n=c(s=>{const d=e[s];if(d!==void 0){if(typeof d!="number"||!Number.isFinite(d))throw m(`${s} must be a number`);return d}},"num"),o=c(s=>{const d=e[s];if(d!==void 0){if(typeof d!="boolean")throw m(`${s} must be a boolean`);return d}},"bool"),r={},i=n("limit");i!==void 0&&(r.limit=i);const a=n("ttl_days");a!==void 0&&(r.ttl_days=a);const u=o("include_stale");u!==void 0&&(r.include_stale=u);const l=o("empty");l!==void 0&&(r.empty=l);const p=o("dry_run");return p!==void 0&&(r.dry_run=p),r}c(ke,"parsePruneBody");function Re(t){const e=ke(t.body),n=e.ttl_days??14,o=e.dry_run??!1,r=se(oe());let i;return e.limit!==void 0?i=K({maxNodes:e.limit,held:r,dryRun:o}).pruned.map(l=>({node_id:l.node_id,status:l.status,created:l.created})):e.empty===!0?i=ne({dryRun:o}).map(l=>({node_id:l,status:"empty",created:""})):i=J({ttlDays:n,held:r,dryRun:o,includeStale:e.include_stale??!1}).pruned.map(l=>({node_id:l.node_id,status:l.status,created:l.created})),{status:200,body:{pruned:i,dry_run:o,ttl_days:n}}}c(Re,"handlePrune");const ze=[{method:"GET",pattern:"/v1/canvas/attention",handler:ce},{method:"POST",pattern:"/v1/canvas/attention/counts",handler:le},{method:"POST",pattern:"/v1/canvas/history/search",handler:be},{method:"POST",pattern:"/v1/canvas/history/grep",handler:_e},{method:"GET",pattern:"/v1/canvas/history/read",handler:ge},{method:"POST",pattern:"/v1/canvas/history/stats",handler:ye},{method:"GET",pattern:"/v1/canvas/snapshot",handler:we},{method:"GET",pattern:"/v1/canvas/roster",handler:Ce},{method:"GET",pattern:"/v1/canvas/graph",handler:Ne},{method:"POST",pattern:"/v1/canvas/prune",ownerOnly:!0,handler:Re}];export{ze as canvasRoutes};
@@ -1 +1 @@
1
- var i=Object.defineProperty;var s=(e,t)=>i(e,"name",{value:t,configurable:!0});import{toMigrateStateDTO as u}from"../map.js";import{boundDaemonControl as a}from"../../control.js";import{ownerOnly as m}from"../router.js";function c(){const e=a();if(e===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot hand over"};const{graceMs:t}=e.requestHandover();return{status:202,body:{accepted:!0,predecessor_pid:process.pid,predecessor_epoch:e.epoch,grace_ms:t}}}s(c,"handleRestart");async function l(e){if(e.body!==void 0)throw{status:400,code:"invalid_request",message:"admission request must not include a body"};const t=a();if(t===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot admit normal work"};return{status:200,body:await t.admitStartup()}}s(l,"handleAdmit");async function y(e){const t=a();if(t===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot migrate its corpus"};const r=e.body;if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw{status:400,code:"invalid_request",message:"migration request body must be an object"};const o=r??{};if(o.dry_run!==void 0&&typeof o.dry_run!="boolean")throw{status:400,code:"invalid_request",message:"dry_run must be a boolean"};if(o.dirs!==void 0&&(!Array.isArray(o.dirs)||o.dirs.some(d=>typeof d!="string")))throw{status:400,code:"invalid_request",message:"dirs must be an array of strings"};const n=await t.repairMigrations({dryRun:o.dry_run===!0,dirs:o.dirs??[]});return{status:200,body:u(n.result,{resumed:n.resumed,resumeError:n.resumeError})}}s(y,"handleMigrate");const v=m([{method:"POST",pattern:"/v1/daemon/restart",handler:s(e=>c(),"handler")},{method:"POST",pattern:"/v1/daemon/migrate",handler:y},{method:"POST",pattern:"/v1/daemon/admit",handler:l}]);export{v as daemonRoutes};
1
+ var d=Object.defineProperty;var n=(e,t)=>d(e,"name",{value:t,configurable:!0});import{toMigrateStateDTO as i}from"../map.js";import{boundDaemonControl as s}from"../../control.js";import{ownerOnly as u}from"../router.js";function c(){const e=s();if(e===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot hand over"};const{graceMs:t}=e.requestHandover();return{status:202,body:{accepted:!0,predecessor_pid:process.pid,predecessor_epoch:e.epoch,grace_ms:t}}}n(c,"handleRestart");async function m(e){if(e.body!==void 0)throw{status:400,code:"invalid_request",message:"admission request must not include a body"};const t=s();if(t===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot admit normal work"};return{status:200,body:await t.admitStartup()}}n(m,"handleAdmit");async function l(e){const t=s();if(t===null)throw{status:503,code:"daemon_control_unavailable",message:"this API server is not hosted by a live daemon and cannot run the canvas import"};const o=e.body;if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw{status:400,code:"invalid_request",message:"migration request body must be an object"};const r=o??{};if(r.dry_run!==void 0&&typeof r.dry_run!="boolean")throw{status:400,code:"invalid_request",message:"dry_run must be a boolean"};const a=await t.repairMigrations({dryRun:r.dry_run===!0});return{status:200,body:i(a.result,{resumed:a.resumed,resumeError:a.resumeError})}}n(l,"handleMigrate");const v=u([{method:"POST",pattern:"/v1/daemon/restart",handler:n(e=>c(),"handler")},{method:"POST",pattern:"/v1/daemon/migrate",handler:l},{method:"POST",pattern:"/v1/daemon/admit",handler:m}]);export{v as daemonRoutes};
@@ -0,0 +1,2 @@
1
+ import type { RouteTable } from '../router.js';
2
+ export declare const deliveryRoutes: RouteTable;
@@ -0,0 +1 @@
1
+ var v=Object.defineProperty;var d=(e,n)=>v(e,"name",{value:n,configurable:!0});import{ApiError as i}from"../../../api/errors.js";import{openDb as _,withCanvasWrite as j}from"../../../core/canvas/db.js";import{readerForNode as l}from"../../../core/graph/reader.js";import{noteNodeBooting as A}from"../../../core/graph/repo-sync/index.js";import{reposForCwd as f}from"../../../core/graph/repo-sync/repos.js";import{DRY_RUN_ONLY as E,deliver as I,hypotheticalFrom as O,hypotheticalReader as k,inspect as p}from"../../../core/substrate/delivery/deliver.js";import{requireCurrentExecution as h}from"./broker-recovery.js";const N=["boot","system-prompt","compact","persona","file-read","command","pre-command","slash-command","names",...E];function y(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new i(400,"usage","delivery requires a JSON body");const n=e;if(!N.includes(n.activity))throw new i(400,"usage",`invalid delivery activity: ${String(n.activity)}`);if(n.subject!==void 0&&typeof n.subject!="string")throw new i(400,"usage","delivery subject must be a string");return n}d(y,"parse");function m(e){if(e.principal.class!=="person"&&e.principal.class!=="broker")throw new i(403,"permission_error","a delivery dry run is available to a person or a node only")}d(m,"requirePerson");function w(e){const n=_(),r=n.isTransaction;n.exec(r?"SAVEPOINT delivery_dry_run":"BEGIN IMMEDIATE");try{return e(n)}finally{r?n.exec("ROLLBACK TO delivery_dry_run; RELEASE delivery_dry_run"):n.exec("ROLLBACK")}}d(w,"rolledBack");function R(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new i(400,"usage","hypothetical must be an object");const n=d((a,s)=>{if(a!==void 0){if(typeof a!="string"||a==="")throw new i(400,"usage",`hypothetical.${s} must be a non-empty string`);return a}},"str"),r=n(e.cwd,"cwd");if(r!==void 0&&!r.startsWith("/"))throw new i(400,"usage","hypothetical.cwd must be an absolute path");if(e.mode!==void 0&&e.mode!=="base"&&e.mode!=="orchestrator")throw new i(400,"usage","hypothetical.mode must be base or orchestrator");if(e.lifecycle!==void 0&&e.lifecycle!=="terminal"&&e.lifecycle!=="resident")throw new i(400,"usage","hypothetical.lifecycle must be terminal or resident");if(e.has_manager!==void 0&&typeof e.has_manager!="boolean")throw new i(400,"usage","hypothetical.has_manager must be a boolean");if(e.depth!==void 0&&(!Number.isInteger(e.depth)||e.depth<0))throw new i(400,"usage","hypothetical.depth must be a non-negative integer");const t={};r!==void 0&&(t.cwd=r),e.profile!==void 0&&(t.profile=e.profile===null?null:n(e.profile,"profile"));const c=n(e.grantee,"grantee");c!==void 0&&(t.grantee=c);const o=n(e.kind,"kind");return o!==void 0&&(t.kind=o),e.mode!==void 0&&(t.mode=e.mode),e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),e.has_manager!==void 0&&(t.hasManager=e.has_manager),e.depth!==void 0&&(t.depth=e.depth),t}d(R,"hypotheticalOf");async function T(e){m(e);const n=y(e.body);if(n.node!==void 0&&typeof n.node!="string")throw new i(400,"usage","node must be a node id");const r={activity:n.activity,...n.subject!==void 0?{subject:n.subject}:{}},{result:t,plan:c}=w(o=>{if(n.hypothetical===void 0){if(n.node===void 0)throw new i(400,"usage","a delivery dry run names a node, a hypothetical node, or both");return p(o,l(o,n.node,g=>f(o,g)),r,n.subject_override)}const a=R(n.hypothetical),s=n.node!==void 0?O(n.node,a):{...a,cwd:a.cwd??""};if(s.cwd==="")throw new i(400,"usage","a hypothetical node needs a cwd");const{reader:u,subject:b}=k(o,s);return p(o,u,r,n.subject_override,b)});return{status:200,body:{...t,plan:c}}}d(T,"handleDryRun");async function S(e){const n=e.params.id,r=y(e.body),t={activity:r.activity,...r.subject!==void 0?{subject:r.subject}:{},...r.inherited===!0?{inherited:!0}:{}};if(r.dry_run===!0){m(e);const{result:o,plan:a}=w(s=>p(s,l(s,n,u=>f(s,u)),t,r.subject_override));return{status:200,body:{...o,plan:a}}}if(e.principal.class==="broker"&&e.principal.node!==n)throw new i(403,"permission_error","delivery is performed by the node's own broker");return h(n,r.expected_execution_id),r.activity==="boot"&&(await A(n),h(n,r.expected_execution_id)),{status:200,body:j(o=>I(o,l(o,n,a=>f(o,a)),t))}}d(S,"handleDelivery");const M=[{method:"POST",pattern:"/v1/nodes/:id/delivery",handler:S},{method:"POST",pattern:"/v1/delivery/dry-run",handler:T}];export{M as deliveryRoutes};