@north-light/crouter 0.3.352 → 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 (616) 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/app-listener.js +11 -11
  382. package/dist/daemon/api/handlers/app-profiles.js +1 -1
  383. package/dist/daemon/api/handlers/bash-jobs.js +1 -2
  384. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  385. package/dist/daemon/api/handlers/canvas.js +5 -5
  386. package/dist/daemon/api/handlers/daemon.js +1 -1
  387. package/dist/daemon/api/handlers/delivery.d.ts +2 -0
  388. package/dist/daemon/api/handlers/delivery.js +1 -0
  389. package/dist/daemon/api/handlers/{memory.d.ts → docs.d.ts} +1 -1
  390. package/dist/daemon/api/handlers/docs.js +1 -0
  391. package/dist/daemon/api/handlers/hook-exec.js +1 -1
  392. package/dist/daemon/api/handlers/messages.js +2 -2
  393. package/dist/daemon/api/handlers/modelauth.d.ts +3 -0
  394. package/dist/daemon/api/handlers/modelauth.js +1 -1
  395. package/dist/daemon/api/handlers/node-records.js +2 -2
  396. package/dist/daemon/api/handlers/nodes.js +1 -1
  397. package/dist/daemon/api/handlers/objects.d.ts +2 -0
  398. package/dist/daemon/api/handlers/objects.js +5 -0
  399. package/dist/daemon/api/handlers/package-docs.d.ts +2 -0
  400. package/dist/daemon/api/handlers/package-docs.js +1 -0
  401. package/dist/daemon/api/handlers/profiles.js +1 -1
  402. package/dist/daemon/api/handlers/reports.d.ts +2 -2
  403. package/dist/daemon/api/handlers/reports.js +4 -4
  404. package/dist/daemon/api/handlers/reviews.js +1 -1
  405. package/dist/daemon/api/handlers/vendor-status.d.ts +8 -0
  406. package/dist/daemon/api/handlers/vendor-status.js +1 -0
  407. package/dist/daemon/api/map.d.ts +2 -2
  408. package/dist/daemon/api/map.js +2 -2
  409. package/dist/daemon/api/operations.d.ts +1 -1
  410. package/dist/daemon/api/operations.js +1 -1
  411. package/dist/daemon/api/principal.d.ts +5 -0
  412. package/dist/daemon/api/principal.js +1 -1
  413. package/dist/daemon/api/reader.d.ts +17 -0
  414. package/dist/daemon/api/reader.js +1 -0
  415. package/dist/daemon/api/server.js +1 -1
  416. package/dist/daemon/control.d.ts +2 -3
  417. package/dist/daemon/crtrd.js +8 -6
  418. package/dist/daemon/fleet.js +4 -4
  419. package/dist/daemon/reconcilers/bash-deadline.d.ts +11 -1
  420. package/dist/daemon/reconcilers/bash-deadline.js +2 -1
  421. package/dist/daemon/reconcilers/broker-supervision.js +4 -4
  422. package/dist/daemon/reconcilers/live-obligation.js +1 -1
  423. package/dist/daemon/reconcilers/node-deadline.js +1 -1
  424. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  425. package/dist/daemon/reconcilers/storage-maintenance.d.ts +1 -0
  426. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  427. package/dist/daemon/review/deliver.js +2 -2
  428. package/dist/daemon/review/finish.js +1 -1
  429. package/dist/hook-authoring.d.ts +0 -1
  430. package/dist/hook-authoring.js +3 -3
  431. package/dist/migrations/004-canvas-documents/apply.d.ts +10 -0
  432. package/dist/migrations/004-canvas-documents/apply.js +1 -0
  433. package/dist/migrations/004-canvas-documents/fields.d.ts +24 -0
  434. package/dist/migrations/004-canvas-documents/fields.js +2 -0
  435. package/dist/migrations/004-canvas-documents/index.d.ts +16 -0
  436. package/dist/migrations/004-canvas-documents/index.js +2 -0
  437. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +16 -0
  438. package/dist/migrations/004-canvas-documents/legacy/discover.js +1 -0
  439. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +5 -0
  440. package/dist/migrations/004-canvas-documents/legacy/history.js +2 -0
  441. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +7 -0
  442. package/dist/migrations/004-canvas-documents/legacy/nested.js +1 -0
  443. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +14 -0
  444. package/dist/migrations/004-canvas-documents/legacy/parse.js +1 -0
  445. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +91 -0
  446. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  447. package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +6 -0
  448. package/dist/migrations/004-canvas-documents/legacy-edges.js +18 -0
  449. package/dist/migrations/004-canvas-documents/plan.d.ts +102 -0
  450. package/dist/migrations/004-canvas-documents/plan.js +3 -0
  451. package/dist/migrations/004-canvas-documents/pointers.d.ts +23 -0
  452. package/dist/migrations/004-canvas-documents/pointers.js +4 -0
  453. package/dist/migrations/activation.d.ts +9 -18
  454. package/dist/migrations/activation.js +2 -2
  455. package/dist/pi-extensions/broker-local.d.ts +2 -2
  456. package/dist/pi-extensions/broker-local.js +2 -2
  457. package/dist/pi-extensions/canvas-bash-valve.js +5 -4
  458. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  459. package/dist/pi-extensions/canvas-doc-substrate.d.ts +0 -1
  460. package/dist/pi-extensions/canvas-doc-substrate.js +6 -6
  461. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  462. package/dist/pi-extensions/canvas-passive-context.js +1 -1
  463. package/dist/pi-extensions/canvas-recap.js +2 -2
  464. package/dist/pi-extensions/canvas-stophook.d.ts +1 -1
  465. package/dist/pi-extensions/canvas-stophook.js +1 -1
  466. package/dist/prompts/review.js +3 -3
  467. package/dist/shared/env.d.ts +5 -0
  468. package/dist/shared/env.js +1 -1
  469. package/dist/shared/generated-context.js +2 -10
  470. package/dist/shared/inbox-entry-body.d.ts +22 -0
  471. package/dist/shared/inbox-entry-body.js +10 -0
  472. package/dist/{core/memory → shared}/inline-ref-guidance.d.ts +2 -2
  473. package/dist/shared/inline-ref-guidance.js +2 -0
  474. package/dist/types.d.ts +3 -1
  475. package/docs/cli/memory-and-preferences.md +12 -14
  476. package/docs/concepts/README.md +1 -1
  477. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  478. package/docs/concepts/memory.md +15 -15
  479. package/docs/concepts/nodes-and-the-canvas.md +1 -1
  480. package/docs/concepts/profiles-kinds-and-modes.md +5 -5
  481. package/docs/concepts/scopes-and-trust.md +1 -1
  482. package/docs/concepts/why-a-daemon.md +1 -1
  483. package/docs/sdk/README.md +5 -6
  484. package/docs/sdk/errors.md +0 -13
  485. package/docs/sdk/guides/README.md +0 -1
  486. package/docs/sdk/nodes.md +0 -2
  487. package/docs/sdk/resources.md +0 -1
  488. package/package.json +2 -2
  489. package/packages/crouter-identity/package.json +1 -1
  490. package/runtime.lock.json +11 -11
  491. package/dist/api/dto/memory.d.ts +0 -171
  492. package/dist/api/dto/memory.js +0 -1
  493. package/dist/builtin-memory/crouter-sdk/guides/app-memory.md +0 -73
  494. package/dist/builtin-memory/crouter-sdk/memory.md +0 -87
  495. package/dist/commands/broker-permissions.d.ts +0 -2
  496. package/dist/commands/broker-permissions.js +0 -1
  497. package/dist/commands/memory/client.d.ts +0 -11
  498. package/dist/commands/memory/client.js +0 -1
  499. package/dist/commands/memory/delete.d.ts +0 -1
  500. package/dist/commands/memory/delete.js +0 -1
  501. package/dist/commands/memory/edit.d.ts +0 -1
  502. package/dist/commands/memory/edit.js +0 -21
  503. package/dist/commands/memory/find.d.ts +0 -1
  504. package/dist/commands/memory/find.js +0 -1
  505. package/dist/commands/memory/history.d.ts +0 -1
  506. package/dist/commands/memory/history.js +0 -5
  507. package/dist/commands/memory/lint.d.ts +0 -1
  508. package/dist/commands/memory/lint.js +0 -1
  509. package/dist/commands/memory/list.d.ts +0 -1
  510. package/dist/commands/memory/list.js +0 -1
  511. package/dist/commands/memory/move.d.ts +0 -1
  512. package/dist/commands/memory/move.js +0 -1
  513. package/dist/commands/memory/origin.d.ts +0 -1
  514. package/dist/commands/memory/origin.js +0 -1
  515. package/dist/commands/memory/read.d.ts +0 -1
  516. package/dist/commands/memory/read.js +0 -6
  517. package/dist/commands/memory/shared.d.ts +0 -22
  518. package/dist/commands/memory/shared.js +0 -1
  519. package/dist/commands/memory/write.d.ts +0 -1
  520. package/dist/commands/memory/write.js +0 -13
  521. package/dist/commands/memory.js +0 -1
  522. package/dist/commands/node-inspect-artifacts.d.ts +0 -1
  523. package/dist/commands/node-inspect-artifacts.js +0 -8
  524. package/dist/core/help/memory-extensions.d.ts +0 -3
  525. package/dist/core/help/memory-extensions.js +0 -2
  526. package/dist/core/memory/cli-selector.d.ts +0 -13
  527. package/dist/core/memory/cli-selector.js +0 -1
  528. package/dist/core/memory/doc-link-grammar.d.ts +0 -20
  529. package/dist/core/memory/doc-link-grammar.js +0 -2
  530. package/dist/core/memory/extensions.js +0 -1
  531. package/dist/core/memory/history.d.ts +0 -87
  532. package/dist/core/memory/history.js +0 -6
  533. package/dist/core/memory/identity.d.ts +0 -65
  534. package/dist/core/memory/identity.js +0 -1
  535. package/dist/core/memory/inline-ref-guidance.js +0 -2
  536. package/dist/core/memory/inline-ref-inventory.d.ts +0 -9
  537. package/dist/core/memory/inline-ref-inventory.js +0 -1
  538. package/dist/core/memory/lint.d.ts +0 -163
  539. package/dist/core/memory/lint.js +0 -2
  540. package/dist/core/memory/mutation-domain.d.ts +0 -113
  541. package/dist/core/memory/mutation-domain.js +0 -12
  542. package/dist/core/memory/mutations.d.ts +0 -74
  543. package/dist/core/memory/mutations.js +0 -1
  544. package/dist/core/memory/project-namespace.d.ts +0 -31
  545. package/dist/core/memory/project-namespace.js +0 -2
  546. package/dist/core/memory/repository-association.d.ts +0 -31
  547. package/dist/core/memory/repository-association.js +0 -1
  548. package/dist/core/memory/service.d.ts +0 -145
  549. package/dist/core/memory/service.js +0 -2
  550. package/dist/core/memory/tree.d.ts +0 -39
  551. package/dist/core/memory/tree.js +0 -1
  552. package/dist/core/memory-resolver.d.ts +0 -280
  553. package/dist/core/memory-resolver.js +0 -2
  554. package/dist/core/nested-stores.d.ts +0 -18
  555. package/dist/core/nested-stores.js +0 -1
  556. package/dist/core/runtime/memory.d.ts +0 -3
  557. package/dist/core/runtime/memory.js +0 -1
  558. package/dist/core/substrate/frontmatter-validation.d.ts +0 -11
  559. package/dist/core/substrate/frontmatter-validation.js +0 -1
  560. package/dist/core/substrate/gate.d.ts +0 -16
  561. package/dist/core/substrate/gate.js +0 -1
  562. package/dist/core/substrate/index.d.ts +0 -18
  563. package/dist/core/substrate/index.js +0 -1
  564. package/dist/core/substrate/injected-store.d.ts +0 -75
  565. package/dist/core/substrate/injected-store.js +0 -2
  566. package/dist/core/substrate/listings.d.ts +0 -28
  567. package/dist/core/substrate/listings.js +0 -1
  568. package/dist/core/substrate/memory-events.d.ts +0 -6
  569. package/dist/core/substrate/memory-events.js +0 -1
  570. package/dist/core/substrate/on-read-node.d.ts +0 -6
  571. package/dist/core/substrate/on-read-node.js +0 -1
  572. package/dist/core/substrate/on-read.d.ts +0 -101
  573. package/dist/core/substrate/on-read.js +0 -9
  574. package/dist/core/substrate/plan.d.ts +0 -94
  575. package/dist/core/substrate/plan.js +0 -1
  576. package/dist/core/substrate/render-node.d.ts +0 -12
  577. package/dist/core/substrate/render-node.js +0 -1
  578. package/dist/core/substrate/render.d.ts +0 -41
  579. package/dist/core/substrate/render.js +0 -65
  580. package/dist/core/substrate/session-cache.d.ts +0 -27
  581. package/dist/core/substrate/session-cache.js +0 -1
  582. package/dist/core/substrate/surface-match.d.ts +0 -73
  583. package/dist/core/substrate/surface-match.js +0 -1
  584. package/dist/daemon/api/handlers/memory.js +0 -5
  585. package/dist/migrations/001-surfaces-frontmatter.d.ts +0 -2
  586. package/dist/migrations/001-surfaces-frontmatter.js +0 -1
  587. package/dist/migrations/002-profile-project-memory.d.ts +0 -2
  588. package/dist/migrations/002-profile-project-memory.js +0 -1
  589. package/dist/migrations/003-repository-root-memory-identity/front-door.d.ts +0 -26
  590. package/dist/migrations/003-repository-root-memory-identity/front-door.js +0 -11
  591. package/dist/migrations/003-repository-root-memory-identity/index.d.ts +0 -2
  592. package/dist/migrations/003-repository-root-memory-identity/index.js +0 -5
  593. package/dist/migrations/003-repository-root-memory-identity/references.d.ts +0 -95
  594. package/dist/migrations/003-repository-root-memory-identity/references.js +0 -5
  595. package/dist/migrations/003-repository-root-memory-identity/repository-facts.d.ts +0 -39
  596. package/dist/migrations/003-repository-root-memory-identity/repository-facts.js +0 -3
  597. package/dist/migrations/convergent.d.ts +0 -43
  598. package/dist/migrations/convergent.js +0 -2
  599. package/dist/migrations/corpus.d.ts +0 -75
  600. package/dist/migrations/corpus.js +0 -3
  601. package/dist/migrations/frontmatter-splice.d.ts +0 -15
  602. package/dist/migrations/frontmatter-splice.js +0 -8
  603. package/dist/migrations/profile-manifests.d.ts +0 -30
  604. package/dist/migrations/profile-manifests.js +0 -2
  605. package/dist/migrations/registry.d.ts +0 -7
  606. package/dist/migrations/registry.js +0 -1
  607. package/dist/migrations/runner.d.ts +0 -43
  608. package/dist/migrations/runner.js +0 -1
  609. package/dist/migrations/types.d.ts +0 -211
  610. package/dist/shared/birth-announcement.d.ts +0 -12
  611. package/dist/shared/birth-announcement.js +0 -1
  612. package/docs/sdk/guides/app-memory.md +0 -22
  613. package/docs/sdk/memory.md +0 -85
  614. /package/dist/{migrations/types.js → api/dto/delivery.js} +0 -0
  615. /package/dist/{core/memory → shared}/inline-ref-grammar.d.ts +0 -0
  616. /package/dist/{core/memory → shared}/inline-ref-grammar.js +0 -0
@@ -0,0 +1,2 @@
1
+ var N=Object.defineProperty;var o=(t,r)=>N(t,"name",{value:r,configurable:!0});import{existsSync as D}from"node:fs";import{readFile as z,writeFile as B}from"node:fs/promises";import{join as R}from"node:path";import{emitEvent as K}from"../../events/emit.js";import{exportRepo as q,importTree as G}from"./exchange.js";import{checkoutChain as J}from"./identity.js";import{reposForCwd as F}from"./repos.js";import{commitTree as I,fetchDocs as Q,FIRST_FETCH_MARKER as V,isAncestor as L,mergeBase as X,openMirror as M,pushDocs as Y,readTree as p,remoteDocsTip as Z,resolveRef as w,setRef as h}from"./mirror.js";import{mergeTrees as ee}from"./ref-format.js";const te=2e4,A=3,O="remote-url",l="refs/crtr/docs",re="refs/crtr/remote-docs",g="refs/crtr/imported";function y(t){try{K(t)}catch{}}o(y,"emitEvent");let T=null;const k=new Map,H=new Set;function ye(t,r){T={lifecycle:t,db:r}}o(ye,"startRepoSync");function U(t,r){return r.type!=="repo"?!1:t.prepare("SELECT 1 FROM identities WHERE object = ? AND scheme = 'git'").get(r.rowid)!==void 0}o(U,"gitScheme");async function W(t,r){const e=new Map;for(const f of J(r))f.ok&&f.scheme==="git"&&e.set(f.externalId,f.remoteUrl);if(e.size===0)return;const s=T.db().prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'git'");for(const f of t){const a=s.get(f.rowid),c=a&&e.get(a.external_id);if(!c)continue;const n=await M(f.id);await B(R(n.dir,O),`${c}
2
+ `)}}o(W,"recordRemoteUrls");async function ne(t,r){const i=E().db(),s=t.filter(n=>U(i,n));if(s.length===0)return;await W(s,r);const f=[];for(const n of s){const d=!H.has(n.id)&&!D(R((await M(n.id)).dir,V)),u=v(n);d&&u&&f.push(u)}if(f.length===0)return;let a;const c=new Promise(n=>{a=setTimeout(n,te)});await Promise.race([Promise.all(f),c]),clearTimeout(a)}o(ne,"noteNodeWorking");async function Te(t){try{const r=E().db(),e=r.prepare("SELECT cwd FROM nodes WHERE node_id = ?").get(t);if(!e)return;const i=se(r,()=>F(r,e.cwd));i.length>0&&await ne(i,e.cwd)}catch(r){y({level:"warn",event:"repo_sync.failed",outcome:"failed",error:r,node_id:t,fields:{step:"fetch",reason:`the boot trigger failed: ${r instanceof Error?r.message:String(r)}`}})}}o(Te,"noteNodeBooting");function se(t,r){if(t.isTransaction)return r();t.exec("BEGIN IMMEDIATE");try{const e=r();return t.exec("COMMIT"),e}catch(e){throw t.exec("ROLLBACK"),e}}o(se,"inWrite");function ve(t,r){const e=E();if(!U(e.db(),t))return;if(r===void 0){v(t);return}const i=W([t],r).then(()=>{v(t)},s=>{y({level:"error",event:"repo_sync.failed",error:s,fields:{repo:t.name,step:"fetch",reason:"recording the remote URL failed"}})});e.lifecycle.registerDetached(i)}o(ve,"noteRepoDocumentsChanged");function E(){if(!T)throw new Error("repo sync is not started: crtrd must call startRepoSync first");return T}o(E,"requireEngine");function v(t){const r=E(),e=k.get(t.id)??{running:null,again:!1};if(k.set(t.id,e),e.running)return e.again=!0,e.running.then(()=>k.get(t.id)?.running??null).then(s=>s??{ok:!0,pushed:!1,imported:$()});if(!r.lifecycle.acceptsDetachedWork())return null;H.add(t.id);const i=oe(t).then(s=>(P(t,s),s),s=>{const f={ok:!1,step:"export",reason:s instanceof Error?s.message:String(s)};return P(t,f),f}).finally(()=>{e.running=null,e.again&&(e.again=!1,v(t))});return e.running=i,r.lifecycle.registerDetached(i.then(()=>{})),i}o(v,"schedule");function P(t,r){if(r.ok){const e=r.imported;y({level:"info",event:"repo_sync.completed",outcome:"succeeded",fields:{repo:t.name,pushed:r.pushed,created:e.created,revisions:e.revisions,deleted:e.deleted,needs_merge:e.needsMerge,refused:e.refused}})}else y({level:"warn",event:"repo_sync.failed",outcome:"failed",fields:{repo:t.name,step:r.step,reason:r.reason}})}o(P,"report");function $(){return{created:0,revisions:0,deleted:0,needsMerge:[],refused:[]}}o($,"emptyImport");class x extends Error{static{o(this,"StepError")}step;constructor(r,e){super(e),this.step=r}}async function S(t,r){try{return await r()}catch(e){throw e instanceof x?e:new x(t,e instanceof Error?e.message:String(e))}}o(S,"step");async function oe(t){const r=E();try{const e=await M(t.id),i=await ie(e);if(i===null)return{ok:!1,step:"fetch",reason:`no checkout of ${t.name} with an origin remote has been seen by this runtime`};let s=$();const f=o(()=>S("import",async()=>{const a=await w(e,l),c=await w(e,g);if(a===null||c===a)return;const n=c?await p(e,g):new Map,d=r.db(),u=G(d,t,n,await p(e,l),m=>F(d,m));s={created:s.created+u.created,revisions:s.revisions+u.revisions,deleted:s.deleted+u.deleted,needsMerge:[...new Set([...s.needsMerge,...u.needsMerge])],refused:[...s.refused,...u.refused]},await h(e,g,a,c)}),"importLocal");await f(),await S("export",async()=>{const a=await w(e,l),c=a?await p(e,l):null,n=q(r.db(),t,c);if(a?ce(c,n):n.size===0)return;const d=await I(e,n,a?[a]:[],`crtr: export ${t.name}`);await h(e,l,d,a),await h(e,g,d,await w(e,g))});for(let a=1;;a++){const c=await Z(e,i);if(!c.ok)return{ok:!1,step:"fetch",reason:c.reason};let n=await w(e,l);if(c.value!==null&&!(n&&await ae(e,c.value)&&await L(e,c.value,n))){const u=await Q(e,i);if(!u.ok)return{ok:!1,step:"fetch",reason:u.reason};const m=u.value;n=await S("merge",async()=>{if(!n||await L(e,n,m))return await h(e,l,m,n),m;const _=await X(e,n,m),b=ee(_?await p(e,_):new Map,await p(e,l),await p(e,re));for(const j of b.refused)s.refused.push(j);const C=await I(e,b.tree,[n,m],`crtr: merge ${t.name}`);return await h(e,l,C,n),C})}if(await f(),n===null||n===c.value)return{ok:!0,pushed:!1,imported:s};const d=await Y(e,i,n);if(d.ok)return{ok:!0,pushed:!0,imported:s};if(d.reason!=="rejected")return{ok:!1,step:"push",reason:d.reason};if(a>=A)return{ok:!1,step:"push",reason:`push rejected ${A} times`}}}catch(e){if(e instanceof x)return{ok:!1,step:e.step,reason:e.message};throw e}}o(oe,"syncRepo");async function ie(t){const r=R(t.dir,O);return D(r)&&(await z(r,"utf8")).trim()||null}o(ie,"readUrl");async function ae(t,r){return await w(t,r)!==null}o(ae,"hasCommit");function ce(t,r){if(t.size!==r.size)return!1;for(const[e,i]of t)if(r.get(e)!==i)return!1;return!0}o(ce,"sameTree");export{te as FIRST_FETCH_WAIT_MS,Te as noteNodeBooting,ne as noteNodeWorking,ve as noteRepoDocumentsChanged,ye as startRepoSync,oe as syncRepo};
@@ -0,0 +1,26 @@
1
+ /** A document's delivery rules as `rules` rows. `rules.owner` mirrors the
2
+ * document's `objects.owner` so delivery can select rules by owner through
3
+ * `rules_on_owner`; `replaceRules` and `setRulesOwner` are the only writers. */
4
+ import type { DatabaseSync } from 'node:sqlite';
5
+ import type { ObjectRow, RuleOn, RuleSpec } from './types.js';
6
+ export declare const RULE_ONS: readonly RuleOn[];
7
+ export interface RuleRow extends RuleSpec {
8
+ rowid: number;
9
+ object: number;
10
+ owner: number | null;
11
+ position: number;
12
+ }
13
+ /** Replace the document's rules; `position` is the array index, `owner` the document's owner. */
14
+ export declare function replaceRules(db: DatabaseSync, object: ObjectRow, specs: readonly RuleSpec[]): void;
15
+ /** Re-point the document's rule rows at its current owner (after a move). */
16
+ export declare function setRulesOwner(db: DatabaseSync, object: ObjectRow): void;
17
+ export declare function rulesOf(db: DatabaseSync, object: ObjectRow): RuleRow[];
18
+ /** Every rule on one of `on` whose document belongs to one of `owners`. */
19
+ export declare function rulesForOwners(db: DatabaseSync, on: readonly RuleOn[], owners: readonly number[]): RuleRow[];
20
+ /** The only converter from package/legacy frontmatter (`surfaces`, `gate`,
21
+ * `slash`) to rules. Tolerant like the runtime parser it replaces: invalid
22
+ * entries are dropped; `lintRules` is the strict check. A document-level
23
+ * `gate` is ANDed into every rule's `if`. */
24
+ export declare function rulesFromFrontmatter(fm: Record<string, unknown>): RuleSpec[];
25
+ /** Strict validation of a rule list; null when valid. */
26
+ export declare function lintRules(value: unknown): string | null;
@@ -0,0 +1,3 @@
1
+ var g=Object.defineProperty;var a=(e,n)=>g(e,"name",{value:n,configurable:!0});const h=["boot","workspace-open","file-read","document-read","command","pre-command","slash-command"],m=["name","preview","content"],E=["file-read","document-read","command","pre-command"],y=["on","match","matchFrontmatter","if","deliver"];function O(e){return{rowid:e.rowid,object:e.object,owner:e.owner,position:e.position,on:e.on_event,deliver:e.deliver,...e.match_json!==null?{match:JSON.parse(e.match_json)}:{},...e.match_frontmatter_json!==null?{matchFrontmatter:JSON.parse(e.match_frontmatter_json)}:{},...e.if_json!==null?{if:JSON.parse(e.if_json)}:{}}}a(O,"fromRaw");function N(e,n,t){const i=S(t);if(i!==null)throw new Error(`replaceRules(${n.id}): ${i}`);e.prepare("DELETE FROM rules WHERE object = ?").run(n.rowid);const c=e.prepare(`INSERT INTO rules (object, owner, position, on_event, match_json, match_frontmatter_json, if_json, deliver)
2
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);t.forEach((r,o)=>{c.run(n.rowid,n.owner,o,r.on,r.match!==void 0?JSON.stringify(r.match):null,r.matchFrontmatter!==void 0?JSON.stringify(r.matchFrontmatter):null,r.if!==void 0?JSON.stringify(r.if):null,r.deliver)})}a(N,"replaceRules");function F(e,n){const t=e.prepare("SELECT owner FROM objects WHERE rowid = ?").get(n.rowid);if(t===void 0)throw new Error(`setRulesOwner: object ${n.id} does not exist`);e.prepare("UPDATE rules SET owner = ? WHERE object = ?").run(t.owner,n.rowid)}a(F,"setRulesOwner");function _(e,n){return e.prepare("SELECT * FROM rules WHERE object = ? ORDER BY position").all(n.rowid).map(O)}a(_,"rulesOf");function v(e,n,t){if(n.length===0||t.length===0)return[];const i=`SELECT * FROM rules WHERE on_event IN (${n.map(()=>"?").join(",")})
3
+ AND owner IN (${t.map(()=>"?").join(",")}) ORDER BY object, position`;return e.prepare(i).all(...n,...t).map(O)}a(v,"rulesForOwners");const R={boot:"boot","workspace-open":"workspace-open",read:"file-read","memory-read":"document-read",command:"command","pre-command":"pre-command"};function s(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}a(s,"predicate");function j(e){if(typeof e=="string")return e.trim()===""?void 0:[e.trim()];if(!Array.isArray(e))return;const n=e.filter(t=>typeof t=="string"&&t.trim()!=="").map(t=>t.trim());return n.length>0?n:void 0}a(j,"globs");function $(e){const n=s(e.gate),t=a(r=>n!==void 0&&r!==void 0?{all:[n,r]}:n??r,"withGate"),i=[],c=Array.isArray(e.surfaces)?e.surfaces:[];for(const r of c){const o=s(r);if(o===void 0)continue;const d=typeof o.on=="string"?R[o.on]:void 0,u=o.at;if(d===void 0||typeof u!="string"||!m.includes(u))continue;const f=j(o.match),l=d==="file-read"?s(o["match-frontmatter"]):void 0;if(E.includes(d)&&f===void 0&&l===void 0)continue;const p=t(s(o.gate));i.push({on:d,deliver:u,...f!==void 0&&d!=="boot"&&d!=="workspace-open"?{match:f}:{},...l!==void 0?{matchFrontmatter:l}:{},...p!==void 0?{if:p}:{}})}return e.slash===!0&&i.push({on:"slash-command",deliver:"content",...n!==void 0?{if:n}:{}}),i}a($,"rulesFromFrontmatter");function S(e){if(!Array.isArray(e))return`invalid rules: ${JSON.stringify(e)} (expected a list of {on, deliver, match?, matchFrontmatter?, if?} entries)`;for(const n of e){const t=s(n);if(t===void 0)return`invalid rule: ${JSON.stringify(n)} (expected an {on, deliver, match?, matchFrontmatter?, if?} object)`;for(const d of Object.keys(t))if(!y.includes(d))return`invalid rule: unknown key \`${d}\` (a rule carries only ${y.join(", ")})`;const i=t.on;if(typeof i!="string"||!h.includes(i))return`invalid rule \`on\`: ${JSON.stringify(i)} (expected ${h.join("|")})`;const c=t.deliver;if(typeof c!="string"||!m.includes(c))return`invalid rule \`deliver\`: ${JSON.stringify(c)} (expected ${m.join("|")})`;const r=t.match;if(r!==void 0){if(i==="boot"||i==="workspace-open"||i==="slash-command")return`invalid rule: \`match\` is meaningless on \`${i}\`; drop it`;if(!Array.isArray(r)||r.length===0||r.some(d=>typeof d!="string"||d.trim()===""))return`invalid rule \`match\`: ${JSON.stringify(r)} (expected a non-empty list of non-empty globs)`}const o=t.matchFrontmatter;if(o!==void 0){if(i!=="file-read")return"invalid rule: `matchFrontmatter` applies to `file-read` rules only";if(s(o)===void 0)return`invalid rule \`matchFrontmatter\`: ${JSON.stringify(o)} (expected a field\u2192matcher object)`}if(E.includes(i)&&r===void 0&&o===void 0)return`invalid rule: a \`${i}\` rule requires \`match\`${i==="file-read"?" or `matchFrontmatter`":""}`;if(t.if!==void 0&&s(t.if)===void 0)return`invalid rule \`if\`: ${JSON.stringify(t.if)} (expected a predicate object)`}return null}a(S,"lintRules");export{h as RULE_ONS,S as lintRules,N as replaceRules,v as rulesForOwners,$ as rulesFromFrontmatter,_ as rulesOf,F as setRulesOwner};
@@ -0,0 +1,3 @@
1
+ import type { Space } from './index.js';
2
+ /** An app: its nodes (with their documents and jobs), its profiles and its app documents. */
3
+ export declare const appSpace: Space;
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var p=(e,r)=>d(e,"name",{value:r,configurable:!0});import{covers as l}from"@north-light/crouter-identity";import{identityOf as s}from"./index.js";const w={identity:s,sync:"runtime",canRead(e,r,n,o,t){if(r.class==="person"||r.app.rowid===n.rowid||o.length===0)return!0;const i=s(e,n).external_id,c=p(m=>r.scopes!==null&&r.scopes.some(f=>l(f,m)),"held");return o[0].type==="node"?c(`crtr:objects:read:${i}`)||t.type==="document"&&t.kind==="report"&&c(`crtr:conversations:read:${i}`):c(u(e,i,"read",o))},canChange(e,r,n,o){if(r.class==="person"||r.app.rowid===n.rowid)return!0;if(o.length===0||o[0].type==="node")return!1;const t=u(e,s(e,n).external_id,"rw",o);return r.scopes!==null&&r.scopes.some(i=>l(i,t))}};function u(e,r,n,o){const t=o[0];return t.type!=="profile"?`crtr:memory:${n}:${r}`:`crtr:memory:${n}:${r}:profile:${s(e,t).external_id}`}p(u,"memoryScope");export{w as appSpace};
@@ -0,0 +1,19 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ import type { ObjectRow, Reader } from '../types.js';
3
+ export interface IdentityRow {
4
+ object: number;
5
+ scheme: string;
6
+ external_id: string;
7
+ }
8
+ export type SpaceType = 'person' | 'app' | 'repo';
9
+ /** The top of an owner chain. Only a space decides access and sync for what it owns.
10
+ * `path` is the owner chain below the space, top first, ending at the object
11
+ * (e.g. `[node, document]`); it is empty when the object is the space itself. */
12
+ export interface Space {
13
+ identity(db: DatabaseSync, space: ObjectRow): IdentityRow;
14
+ sync: 'runtime' | 'repo-ref';
15
+ canRead(db: DatabaseSync, reader: Reader, space: ObjectRow, path: ObjectRow[], object: ObjectRow): boolean;
16
+ canChange(db: DatabaseSync, reader: Reader, space: ObjectRow, path: ObjectRow[], object: ObjectRow): boolean;
17
+ }
18
+ export declare const SPACES: Record<SpaceType, Space>;
19
+ export declare function identityOf(db: DatabaseSync, object: ObjectRow): IdentityRow;
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty;var p=(r,e)=>t(r,"name",{value:e,configurable:!0});import{appSpace as i}from"./app.js";import{personSpace as n}from"./person.js";import{repoSpace as a}from"./repo.js";const f={person:n,app:i,repo:a};function E(r,e){const o=r.prepare("SELECT object, scheme, external_id FROM identities WHERE object = ?").get(e.rowid);if(!o)throw new Error(`${e.type} ${e.id} has no identity`);return o}p(E,"identityOf");export{f as SPACES,E as identityOf};
@@ -0,0 +1,5 @@
1
+ import type { Space } from './index.js';
2
+ /** You: your documents, and nodes started with your own authority. Reads and
3
+ * changes use the runtime-spaces memory permission strings; a change also
4
+ * requires the document's grantee — the app of the node that wrote its first revision. */
5
+ export declare const personSpace: Space;
@@ -0,0 +1,2 @@
1
+ import{covers as p}from"@north-light/crouter-identity";import{identityOf as i}from"./index.js";const f={identity:i,sync:"runtime",canRead(s,r,o,e,t){if(r.class==="person"||r.app.rowid===o.rowid||e.length===0)return!0;if(e[0].type!=="document")return!1;const n=`crtr:memory:read:user:${t.name}`;return r.scopes!==null&&r.scopes.some(c=>p(c,n))},canChange(s,r,o,e,t){if(r.class==="person"||r.app.rowid===o.rowid)return!0;if(e.length===0||e[0].type!=="document")return!1;const n=`crtr:memory:rw:user:${t.name}`;return r.scopes===null||!r.scopes.some(u=>p(u,n))?!1:s.prepare(`SELECT author.owner AS app FROM revisions r JOIN objects author ON author.rowid = r.author
2
+ WHERE r.document = ? ORDER BY r.number, r.created_at LIMIT 1`).get(e[0].rowid)?.app===r.app.rowid}};export{f as personSpace};
@@ -0,0 +1,4 @@
1
+ import type { Space } from './index.js';
2
+ /** A repo: read and changed by a run working in a checkout of it (the reader's
3
+ * `repos`). It owns only public documents, so a non-public one is never changed. */
4
+ export declare const repoSpace: Space;
@@ -0,0 +1 @@
1
+ import{identityOf as i}from"./index.js";const c={identity:i,sync:"repo-ref",canRead(s,r,e,n){return r.class==="person"||n.length===0?!0:r.class==="node"&&r.repos.some(o=>o.rowid===e.rowid)},canChange(s,r,e,n,o){return o.privacy!=="public"?!1:r.class==="person"?!0:r.class==="node"&&r.repos.some(t=>t.rowid===e.rowid)}};export{c as repoSpace};
@@ -0,0 +1,75 @@
1
+ /** Shared types of the canvas graph: documents, nodes, jobs and their owners as rows of `objects`. */
2
+ export type ObjectType = 'document' | 'node' | 'job' | 'person' | 'app' | 'repo' | 'profile';
3
+ export type Privacy = 'public' | 'friends' | 'private';
4
+ export interface ObjectRow {
5
+ rowid: number;
6
+ id: string;
7
+ type: ObjectType;
8
+ kind: string | null;
9
+ owner: number | null;
10
+ privacy: Privacy;
11
+ name: string;
12
+ preview: string;
13
+ created_at: string;
14
+ deleted_at: string | null;
15
+ }
16
+ export type EventName = 'created' | 'read' | 'watched' | 'deleted' | 'edited' | 'messaged' | 'sent' | 'configured' | 'report.update' | 'report.final' | 'report.result' | 'notice.crash' | 'notice.deadline' | 'notice.close' | 'exited' | 'killed';
17
+ export type Level = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
18
+ export type ListenDelivery = 'interrupt' | 'steer' | 'after-turn' | 'next-turn';
19
+ /** Stored as `{"10":"interrupt",...}`. */
20
+ export type ListenConfig = Array<{
21
+ threshold: Level;
22
+ delivery: ListenDelivery;
23
+ }>;
24
+ export declare const DEFAULT_LISTEN: ListenConfig;
25
+ export type WatchStart = 'spawn' | 'job-start' | 'ask' | 'read' | 'write' | 'act' | 'message' | 'deliver' | 'fork';
26
+ export interface CanvasEvent {
27
+ event: EventName;
28
+ object: ObjectRow;
29
+ actor: ObjectRow | null;
30
+ level: Level;
31
+ /** revision, rationale, exit-code, log-path, request id …; never content */
32
+ attrs: Record<string, string | number | boolean | null>;
33
+ /** the act's pointer (inbox entry id, report doc id, revision rev_id) */
34
+ pointer?: string;
35
+ /** ONLY for report.* and notice.*: the body today's report delivery carries */
36
+ messageBody?: unknown;
37
+ }
38
+ /** Who is asking. Mirrors the router's RequestPrincipal; brokers resolve to their node's object. */
39
+ export type Reader = {
40
+ class: 'person';
41
+ person: ObjectRow;
42
+ } | {
43
+ class: 'app';
44
+ app: ObjectRow;
45
+ scopes: readonly string[];
46
+ } | {
47
+ class: 'node';
48
+ node: ObjectRow;
49
+ app: ObjectRow;
50
+ scopes: readonly string[] | null;
51
+ cwd: string;
52
+ repos: ObjectRow[];
53
+ profile: ObjectRow | null;
54
+ };
55
+ export type RuleOn = 'boot' | 'workspace-open' | 'file-read' | 'document-read' | 'command' | 'pre-command' | 'slash-command';
56
+ export interface RuleSpec {
57
+ on: RuleOn;
58
+ match?: string[];
59
+ matchFrontmatter?: Record<string, unknown>;
60
+ if?: unknown;
61
+ deliver: 'name' | 'preview' | 'content';
62
+ }
63
+ export interface Revision {
64
+ rowid: number;
65
+ rev_id: string;
66
+ number: number;
67
+ body_hash: string;
68
+ /** the author object's id; null for revisions imported from another runtime */
69
+ author: string | null;
70
+ rationale: string | null;
71
+ verbatim: boolean;
72
+ created_at: string;
73
+ /** parent rev_ids */
74
+ parents: string[];
75
+ }
@@ -0,0 +1 @@
1
+ const e=[{threshold:10,delivery:"interrupt"},{threshold:7,delivery:"steer"},{threshold:5,delivery:"after-turn"},{threshold:3,delivery:"next-turn"}];export{e as DEFAULT_LISTEN};
@@ -0,0 +1,62 @@
1
+ /** Watches and their subscriptions, message-subscription ending, tree walks and fork copies.
2
+ * `watches.in_tree` is written only here: it is 1 while any subscription of the watch
3
+ * started from spawn, job-start or ask. */
4
+ import type { DatabaseSync } from 'node:sqlite';
5
+ import type { ListenConfig, ObjectRow, Reader, WatchStart } from './types.js';
6
+ export interface Subscription {
7
+ rowid: number;
8
+ pattern: string;
9
+ filter: unknown;
10
+ config: ListenConfig | null;
11
+ started_by: WatchStart;
12
+ ends_on: string | null;
13
+ created_at: string;
14
+ }
15
+ export interface Watch {
16
+ rowid: number;
17
+ watcher: ObjectRow;
18
+ object: ObjectRow;
19
+ in_tree: boolean;
20
+ read_heads_key: string | null;
21
+ created_at: string;
22
+ subscriptions: Subscription[];
23
+ }
24
+ export interface RecordWatchOpts {
25
+ patterns?: string[];
26
+ config?: ListenConfig;
27
+ filter?: unknown;
28
+ /** message subscriptions only: 'final' (the default) or 'result:<request message_id>' */
29
+ endsOn?: string;
30
+ readHeadsKey?: string;
31
+ }
32
+ export declare function configToJson(config: ListenConfig): string;
33
+ export declare function configFromJson(json: string): ListenConfig;
34
+ /** Record (or extend) watcher's watch on object. Adds only the subscriptions the watch lacks:
35
+ * a pattern already held without an end covers any new one, except that a tree start
36
+ * still adds its own subscription when only non-tree ones hold the pattern. */
37
+ export declare function recordWatch(db: DatabaseSync, watcher: ObjectRow, object: ObjectRow, start: WatchStart, opts?: RecordWatchOpts): void;
38
+ /** Remove the whole watch, the subscriptions with one pattern, or (tree-only form) the
39
+ * subscriptions one start made. A watch left with no subscription is deleted. */
40
+ export declare function unwatch(db: DatabaseSync, watcher: ObjectRow, object: ObjectRow, which?: string | {
41
+ startedBy: WatchStart;
42
+ }): void;
43
+ /** Change the listening configuration of the watcher's subscriptions with `pattern`; null = the watcher's default. */
44
+ export declare function setSubscriptionConfig(db: DatabaseSync, watcher: ObjectRow, object: ObjectRow, pattern: string, config: ListenConfig | null): void;
45
+ /** End the message subscriptions on `object` (a node): 'final' and 'done' end all of them;
46
+ * `{result}` ends those waiting for that request's answer. */
47
+ export declare function endMessageSubscriptions(db: DatabaseSync, object: ObjectRow, cause: 'final' | 'done' | {
48
+ result: string;
49
+ }): void;
50
+ /** The watches `watcher` holds that the reader may see (both ends readable). */
51
+ export declare function watchesOf(db: DatabaseSync, reader: Reader, watcher: ObjectRow): Watch[];
52
+ /** The watches held on `object` that the reader may see (both ends readable). */
53
+ export declare function watchersOf(db: DatabaseSync, reader: Reader, object: ObjectRow): Watch[];
54
+ /** Every node below `root` in the tree (in-tree watches, watcher → object), each once. */
55
+ export declare function descendants(db: DatabaseSync, root: ObjectRow): ObjectRow[];
56
+ /** Every node above `leaf` in the tree (in-tree watches, object → watcher), each once. */
57
+ export declare function ancestors(db: DatabaseSync, leaf: ObjectRow): ObjectRow[];
58
+ /** The objects whose in-tree watch covers `object` (its spawner, job starter, explicit watchers). */
59
+ export declare function treeWatchersOf(db: DatabaseSync, object: ObjectRow): ObjectRow[];
60
+ /** Give `fork` a copy of every watch `source` holds, with the same subscriptions, configurations
61
+ * and read base; each copied subscription records `fork`, so no copy is in the tree. */
62
+ export declare function copyWatchesForFork(db: DatabaseSync, source: ObjectRow, fork: ObjectRow): void;
@@ -0,0 +1,18 @@
1
+ var T=Object.defineProperty;var a=(e,r)=>T(e,"name",{value:r,configurable:!0});import{canRead as R}from"./access.js";import{getByRowid as O}from"./objects.js";const h=["spawn","job-start","ask"],D=["report.final","report.result","notice.>"];function S(e){return JSON.stringify(Object.fromEntries(e.map(r=>[String(r.threshold),r.delivery])))}a(S,"configToJson");function y(e){const r=JSON.parse(e);return Object.entries(r).map(([n,t])=>({threshold:Number(n),delivery:t})).sort((n,t)=>t.threshold-n.threshold)}a(y,"configFromJson");function u(e,r,n){return e.prepare("SELECT * FROM watches WHERE watcher = ? AND object = ?").get(r.rowid,n.rowid)}a(u,"watchRow");function E(e,r){return e.prepare("SELECT * FROM watch_subscriptions WHERE watch = ? ORDER BY rowid").all(r)}a(E,"subsOf");function l(e,r){const n=E(e,r);if(n.length===0){e.prepare("DELETE FROM watches WHERE rowid = ?").run(r);return}const t=n.some(o=>h.includes(o.started_by))?1:0;e.prepare("UPDATE watches SET in_tree = ? WHERE rowid = ? AND in_tree != ?").run(t,r,t)}a(l,"settle");function j(e,r){return e==="message"?D:e==="ask"&&r.patterns?.length?r.patterns:[">"]}a(j,"defaultPatterns");function F(e,r,n,t,o={}){if(t==="fork")throw new Error("recordWatch: fork watches are made by copyWatchesForFork");const i=new Date().toISOString();e.prepare(`INSERT INTO watches (watcher, object, in_tree, read_heads_key, created_at) VALUES (?, ?, 0, ?, ?)
2
+ ON CONFLICT (watcher, object) DO UPDATE SET read_heads_key = COALESCE(excluded.read_heads_key, read_heads_key)`).run(r.rowid,n.rowid,o.readHeadsKey??null,i);const c=u(e,r,n),w=t==="message"?o.endsOn??"final":null,_=h.includes(t),s=E(e,c.rowid),d=e.prepare(`INSERT INTO watch_subscriptions (watch, pattern, filter_json, config_json, started_by, ends_on, created_at)
3
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);for(const f of j(t,o))s.some(p=>p.pattern===f&&(p.ends_on===null||p.ends_on===w)&&(!_||h.includes(p.started_by)))||d.run(c.rowid,f,o.filter===void 0?null:JSON.stringify(o.filter),o.config?S(o.config):null,t,w,i);l(e,c.rowid)}a(F,"recordWatch");function W(e,r,n,t){const o=u(e,r,n);o&&(t===void 0?e.prepare("DELETE FROM watch_subscriptions WHERE watch = ?").run(o.rowid):typeof t=="string"?e.prepare("DELETE FROM watch_subscriptions WHERE watch = ? AND pattern = ?").run(o.rowid,t):e.prepare("DELETE FROM watch_subscriptions WHERE watch = ? AND started_by = ?").run(o.rowid,t.startedBy),l(e,o.rowid))}a(W,"unwatch");function b(e,r,n,t,o){const i=u(e,r,n),c=i?e.prepare("UPDATE watch_subscriptions SET config_json = ? WHERE watch = ? AND pattern = ?").run(o?S(o):null,i.rowid,t).changes:0;if(Number(c)===0)throw new Error(`${r.id} has no subscription ${t} on ${n.id}`)}a(b,"setSubscriptionConfig");function k(e,r,n){const t=typeof n=="string"?e.prepare(`DELETE FROM watch_subscriptions WHERE started_by = 'message'
4
+ AND watch IN (SELECT rowid FROM watches WHERE object = ?) RETURNING watch`).all(r.rowid):e.prepare(`DELETE FROM watch_subscriptions WHERE started_by = 'message' AND ends_on = ?
5
+ AND watch IN (SELECT rowid FROM watches WHERE object = ?) RETURNING watch`).all(`result:${n.result}`,r.rowid);for(const o of new Set(t.map(i=>i.watch)))l(e,o)}a(k,"endMessageSubscriptions");function I(e,r){const n=O(e,r.watcher),t=O(e,r.object);return!n||!t?null:{rowid:r.rowid,watcher:n,object:t,in_tree:r.in_tree===1,read_heads_key:r.read_heads_key,created_at:r.created_at,subscriptions:E(e,r.rowid).map(o=>({rowid:o.rowid,pattern:o.pattern,started_by:o.started_by,ends_on:o.ends_on,created_at:o.created_at,filter:o.filter_json===null?null:JSON.parse(o.filter_json),config:o.config_json===null?null:y(o.config_json)}))}}a(I,"hydrate");function N(e,r,n){return n.map(t=>I(e,t)).filter(t=>t!==null&&R(e,r,t.watcher)&&R(e,r,t.object))}a(N,"visible");function H(e,r,n){return N(e,r,e.prepare("SELECT * FROM watches WHERE watcher = ? ORDER BY rowid").all(n.rowid))}a(H,"watchesOf");function m(e,r,n){return N(e,r,e.prepare("SELECT * FROM watches WHERE object = ? ORDER BY rowid").all(n.rowid))}a(m,"watchersOf");function M(e,r){return e.prepare(`WITH RECURSIVE walk(rowid) AS (
6
+ SELECT ?
7
+ UNION
8
+ SELECT w.object FROM walk CROSS JOIN watches w INDEXED BY watches_tree_down ON w.watcher = walk.rowid AND w.in_tree = 1
9
+ ) SELECT o.* FROM walk CROSS JOIN objects o ON o.rowid = walk.rowid
10
+ WHERE o.type = 'node' AND o.rowid != ?`).all(r.rowid,r.rowid)}a(M,"descendants");function x(e,r){return e.prepare(`WITH RECURSIVE walk(rowid) AS (
11
+ SELECT ?
12
+ UNION
13
+ SELECT w.watcher FROM walk CROSS JOIN watches w INDEXED BY watches_tree_up ON w.object = walk.rowid AND w.in_tree = 1
14
+ ) SELECT o.* FROM walk CROSS JOIN objects o ON o.rowid = walk.rowid
15
+ WHERE o.type = 'node' AND o.rowid != ?`).all(r.rowid,r.rowid)}a(x,"ancestors");function U(e,r){return e.prepare(`SELECT o.* FROM watches w INDEXED BY watches_tree_up CROSS JOIN objects o ON o.rowid = w.watcher
16
+ WHERE w.object = ? AND w.in_tree = 1 ORDER BY w.rowid`).all(r.rowid)}a(U,"treeWatchersOf");function J(e,r,n){const t=new Date().toISOString(),o=e.prepare("SELECT * FROM watches WHERE watcher = ?").all(r.rowid),i=e.prepare(`INSERT INTO watch_subscriptions (watch, pattern, filter_json, config_json, started_by, ends_on, created_at)
17
+ VALUES (?, ?, ?, ?, 'fork', ?, ?)`);for(const c of o){if(c.object===n.rowid)continue;e.prepare(`INSERT INTO watches (watcher, object, in_tree, read_heads_key, created_at) VALUES (?, ?, 0, ?, ?)
18
+ ON CONFLICT (watcher, object) DO NOTHING`).run(n.rowid,c.object,c.read_heads_key,t);const w=u(e,n,{rowid:c.object}),_=E(e,w.rowid);for(const s of E(e,c.rowid))_.some(d=>d.pattern===s.pattern&&d.ends_on===s.ends_on)||i.run(w.rowid,s.pattern,s.filter_json,s.config_json,s.ends_on,t);l(e,w.rowid)}}a(J,"copyWatchesForFork");export{x as ancestors,y as configFromJson,S as configToJson,J as copyWatchesForFork,M as descendants,k as endMessageSubscriptions,F as recordWatch,b as setSubscriptionConfig,U as treeWatchersOf,W as unwatch,m as watchersOf,H as watchesOf};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var i=(e,o)=>f(e,"name",{value:o,configurable:!0});import{createHash as l}from"node:crypto";import{readFileSync as s}from"node:fs";import{getNode as u}from"../canvas/index.js";import{awaitCompanionBind as w,captureOrigin as h}from"../review/companion.js";import{COMPANION_BIND_DEADLINE_MS as t}from"../review/types.js";import{buildLaunchSpec as _}from"../runtime/launch.js";import{transition as k}from"../runtime/lifecycle.js";import{headlessBrokerHost as N}from"../runtime/host.js";import{spawnNode as b}from"../runtime/nodes.js";import{reviveNode as I}from"../runtime/revive.js";import{materializeSessionBranch as x}from"../runtime/session-branch.js";import{initializeForkContextExposure as F}from"../substrate/injected-store.js";import{pagePath as a}from"./convention.js";import{selectedPageDir as c}from"./tickets.js";function L(e){return l("sha256").update(s(a(c(e),"jsx"))).digest("hex")}i(L,"pageDocumentSha256");function S(e){try{k(e,"cancel",{reason:"retired"}),N.teardown(e)}catch{}}i(S,"discardFeedbackCompanion");async function q(e){const o=u(e.senderNodeId);if(o===null)throw new Error(`page sender was not found: ${e.senderNodeId}`);const d=await h(e.senderNodeId),n=x(d),{launch:m}=_(o.kind,o.mode,{lifecycle:"resident",hasManager:!1,model:d.modelSpec,modelExact:!0,cwd:o.cwd,profileId:o.profile_id??null}),r=await b({kind:o.kind,mode:o.mode,lifecycle:"resident",cwd:o.cwd,profile_id:o.profile_id??null,parent:e.senderNodeId,creator:e.senderNodeId,subscribe:!1,forkFrom:n,forkSourceFile:n,modelOverride:d.modelSpec,reviewBinding:{kind:"page_feedback",review_id:e.ticketId,origin_node_id:e.senderNodeId,branch_file:n,target_file:a(c(e.dir),"jsx")},name:`Feedback \xB7 ${e.title}`,launch:m});try{if(F(r.node_id,e.senderNodeId),await I(r.node_id,{resume:!1,capacity:"refuse"}),!await w(r.node_id,t))throw new Error(`feedback companion did not bind within ${t}ms`)}catch(p){throw S(r.node_id),p}return r.node_id}i(q,"realizeFeedbackCompanion");export{S as discardFeedbackCompanion,L as pageDocumentSha256,q as realizeFeedbackCompanion};
1
+ var f=Object.defineProperty;var i=(e,o)=>f(e,"name",{value:o,configurable:!0});import{createHash as l}from"node:crypto";import{readFileSync as s}from"node:fs";import{getNode as u}from"../canvas/index.js";import{awaitCompanionBind as w,captureOrigin as h}from"../review/companion.js";import{COMPANION_BIND_DEADLINE_MS as t}from"../review/types.js";import{buildLaunchSpec as _}from"../runtime/launch.js";import{transition as N}from"../runtime/lifecycle.js";import{headlessBrokerHost as k}from"../runtime/host.js";import{spawnNode as b}from"../runtime/nodes.js";import{reviveNode as I}from"../runtime/revive.js";import{materializeSessionBranch as S}from"../runtime/session-branch.js";import{forkNodeLedger as x}from"../runtime/ledger.js";import{pagePath as a}from"./convention.js";import{selectedPageDir as c}from"./tickets.js";function H(e){return l("sha256").update(s(a(c(e),"jsx"))).digest("hex")}i(H,"pageDocumentSha256");function y(e){try{N(e,"cancel",{reason:"retired"}),k.teardown(e)}catch{}}i(y,"discardFeedbackCompanion");async function q(e){const o=u(e.senderNodeId);if(o===null)throw new Error(`page sender was not found: ${e.senderNodeId}`);const d=await h(e.senderNodeId),n=S(d),{launch:m}=_(o.kind,o.mode,{lifecycle:"resident",hasManager:!1,model:d.modelSpec,modelExact:!0,cwd:o.cwd,profileId:o.profile_id??null}),r=await b({kind:o.kind,mode:o.mode,lifecycle:"resident",cwd:o.cwd,profile_id:o.profile_id??null,parent:e.senderNodeId,creator:e.senderNodeId,subscribe:!1,forkFrom:n,forkSourceFile:n,modelOverride:d.modelSpec,reviewBinding:{kind:"page_feedback",review_id:e.ticketId,origin_node_id:e.senderNodeId,branch_file:n,target_file:a(c(e.dir),"jsx")},name:`Feedback \xB7 ${e.title}`,launch:m});try{if(x(r.node_id,e.senderNodeId),await I(r.node_id,{resume:!1,capacity:"refuse"}),!await w(r.node_id,t))throw new Error(`feedback companion did not bind within ${t}ms`)}catch(p){throw y(r.node_id),p}return r.node_id}i(q,"realizeFeedbackCompanion");export{y as discardFeedbackCompanion,H as pageDocumentSha256,q as realizeFeedbackCompanion};
@@ -52,6 +52,8 @@ export interface NewReviewRequest {
52
52
  anchor_base_bytes: Buffer;
53
53
  created_at: string;
54
54
  subtitle?: string | null;
55
+ /** The inbox title; defaults to the file's basename. */
56
+ title?: string;
55
57
  inbox_listed: boolean;
56
58
  }
57
59
  export interface CreatePageRequestInput {
@@ -97,7 +99,7 @@ export declare function getRequestByCompanion(nodeId: string): HumanRequestRecor
97
99
  export declare function getRequestByIdempotencyKey(key: string): HumanRequestRecord | null;
98
100
  /** A page asked from a run of an app other than the terminal is that app's to show
99
101
  * (daemon-operations §question.*: the terminal shows `app:terminal` runs' questions). */
100
- export declare const NOT_OTHER_APP_QUESTION = "NOT (kind = 'page' AND EXISTS (SELECT 1 FROM nodes n WHERE n.node_id = human_requests.requester_node_id\n AND n.run_id IS NOT NULL AND n.grantee IS NOT NULL AND n.grantee <> 'app:terminal'))";
102
+ export declare const NOT_OTHER_APP_QUESTION = "NOT (kind = 'page' AND EXISTS (SELECT 1 FROM node_rows n WHERE n.node_id = human_requests.requester_node_id\n AND n.run_id IS NOT NULL AND n.grantee IS NOT NULL AND n.grantee <> 'app:terminal'))";
101
103
  export declare function listOpenInboxRequests(): HumanRequestRecord[];
102
104
  export declare function openRequestsByRequester(nodeId: string): HumanRequestRecord[];
103
105
  export declare function hasOpenReplyBearingRequestByRequester(nodeId: string): boolean;
@@ -1,4 +1,4 @@
1
- var de=Object.defineProperty;var i=(e,t)=>de(e,"name",{value:t,configurable:!0});import{createHash as ue,randomBytes as j}from"node:crypto";import{existsSync as g,mkdirSync as A,readFileSync as V,readdirSync as ce,realpathSync as L,statSync as le,writeFileSync as _e}from"node:fs";import{basename as w,join as c}from"node:path";import{z as d}from"zod";import{crtrHome as Q,isSafeNodeId as pe,nodesRoot as b}from"../canvas/paths.js";import{openDb as _,withCanvasWrite as f}from"../canvas/db.js";import{syncDirectory as me,syncFile as fe}from"../fs-utils.js";import{newNodeId as Ee}from"../runtime/nodes.js";import{pageManifestPath as ge,pageModulePath as ye,pagePath as he}from"./convention.js";import{preparePageSource as qe}from"./page-authoring.js";import{pageDeliverySchema as Ne,validatePageManifest as z}from"./page-schema.js";import{appendWaitingOnUser as be}from"../runs/questions.js";function G(e){return e===1||e===!0}i(G,"bool");function Y(e){return{request_id:e.request_id,kind:e.kind,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,presentation_dir:e.presentation_dir,requester_node_id:e.requester_node_id,companion_node_id:e.companion_node_id,idempotency_key:e.idempotency_key,state:e.state,outcome:e.outcome,inbox_listed:G(e.inbox_listed),settleable:G(e.settleable),title:e.title,subtitle:e.subtitle,file:e.file,specification_json:e.specification_json,action_json:e.action_json,progress_json:e.progress_json,feedback_json:e.feedback_json,result_json:e.result_json,anchor_base_sha256:e.anchor_base_sha256,anchor_base_bytes:e.anchor_base_bytes===null?null:Buffer.from(e.anchor_base_bytes),created_at:e.created_at,opened_at:e.opened_at,submit_requested_at:e.submit_requested_at,settled_at:e.settled_at,settlement_delivery_id:e.settlement_delivery_id,action_delivery_id:e.action_delivery_id,submit_note_delivery_id:e.submit_note_delivery_id,projected_at:e.projected_at,projection_error:e.projection_error,companion_retired_at:e.companion_retired_at,updated_at:e.updated_at}}i(Y,"recordFromRow");function q(e,t,...r){const s=e.prepare(`SELECT * FROM human_requests WHERE ${t}`).get(...r);return s===void 0?null:Y(s)}i(q,"one");function T(e,t,r=[],s="created_at ASC, request_id ASC"){return e.prepare(`SELECT * FROM human_requests WHERE ${t} ORDER BY ${s}`).all(...r).map(Y)}i(T,"many");function Z(){return c(Q(),"requests")}i(Z,"humanRequestsRoot");function C(e){if(!pe(e))throw new TypeError(`request_id must be a safe path segment: ${e}`);const t=Z();return A(t,{recursive:!0,mode:448}),c(L(t),e)}i(C,"requestDir");function U(){return j(32).toString("hex")}i(U,"randomTicketId");function P(e,t){return ue("sha256").update(`${L(e)}\0${t}`,"utf8").digest("hex")}i(P,"legacyTicketId");const Te={writeFile(e,t){_e(e,t,{flag:"wx",mode:384})},syncFile:fe,syncDirectory:me};function Se(e){return c(e,"revisions")}i(Se,"revisionRoot");function ee(e,t,r=Te){A(e,{recursive:!0,mode:448});const s=Se(e);A(s,{recursive:!0,mode:448});const n=c(s,j(16).toString("hex"));A(n,{mode:448});const o=he(n,t.manifest.dialect);if(r.writeFile(o,t.document),r.syncFile(o),t.manifest.dialect==="jsx"){const a=ye(n);r.writeFile(a,t.module),r.syncFile(a)}const u=ge(n);return r.writeFile(u,`${JSON.stringify(t.manifest,null,2)}
1
+ var de=Object.defineProperty;var i=(e,t)=>de(e,"name",{value:t,configurable:!0});import{createHash as ue,randomBytes as w}from"node:crypto";import{existsSync as g,mkdirSync as A,readFileSync as V,readdirSync as ce,realpathSync as L,statSync as le,writeFileSync as _e}from"node:fs";import{basename as j,join as c}from"node:path";import{z as d}from"zod";import{crtrHome as Q,isSafeNodeId as pe,nodesRoot as b}from"../canvas/paths.js";import{openDb as _,withCanvasWrite as f}from"../canvas/db.js";import{syncDirectory as me,syncFile as fe}from"../fs-utils.js";import{newNodeId as Ee}from"../runtime/nodes.js";import{pageManifestPath as ge,pageModulePath as ye,pagePath as he}from"./convention.js";import{preparePageSource as qe}from"./page-authoring.js";import{pageDeliverySchema as Ne,validatePageManifest as z}from"./page-schema.js";import{appendWaitingOnUser as be}from"../runs/questions.js";function G(e){return e===1||e===!0}i(G,"bool");function Y(e){return{request_id:e.request_id,kind:e.kind,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,presentation_dir:e.presentation_dir,requester_node_id:e.requester_node_id,companion_node_id:e.companion_node_id,idempotency_key:e.idempotency_key,state:e.state,outcome:e.outcome,inbox_listed:G(e.inbox_listed),settleable:G(e.settleable),title:e.title,subtitle:e.subtitle,file:e.file,specification_json:e.specification_json,action_json:e.action_json,progress_json:e.progress_json,feedback_json:e.feedback_json,result_json:e.result_json,anchor_base_sha256:e.anchor_base_sha256,anchor_base_bytes:e.anchor_base_bytes===null?null:Buffer.from(e.anchor_base_bytes),created_at:e.created_at,opened_at:e.opened_at,submit_requested_at:e.submit_requested_at,settled_at:e.settled_at,settlement_delivery_id:e.settlement_delivery_id,action_delivery_id:e.action_delivery_id,submit_note_delivery_id:e.submit_note_delivery_id,projected_at:e.projected_at,projection_error:e.projection_error,companion_retired_at:e.companion_retired_at,updated_at:e.updated_at}}i(Y,"recordFromRow");function q(e,t,...r){const s=e.prepare(`SELECT * FROM human_requests WHERE ${t}`).get(...r);return s===void 0?null:Y(s)}i(q,"one");function T(e,t,r=[],s="created_at ASC, request_id ASC"){return e.prepare(`SELECT * FROM human_requests WHERE ${t} ORDER BY ${s}`).all(...r).map(Y)}i(T,"many");function Z(){return c(Q(),"requests")}i(Z,"humanRequestsRoot");function C(e){if(!pe(e))throw new TypeError(`request_id must be a safe path segment: ${e}`);const t=Z();return A(t,{recursive:!0,mode:448}),c(L(t),e)}i(C,"requestDir");function U(){return w(32).toString("hex")}i(U,"randomTicketId");function P(e,t){return ue("sha256").update(`${L(e)}\0${t}`,"utf8").digest("hex")}i(P,"legacyTicketId");const Te={writeFile(e,t){_e(e,t,{flag:"wx",mode:384})},syncFile:fe,syncDirectory:me};function Se(e){return c(e,"revisions")}i(Se,"revisionRoot");function ee(e,t,r=Te){A(e,{recursive:!0,mode:448});const s=Se(e);A(s,{recursive:!0,mode:448});const n=c(s,w(16).toString("hex"));A(n,{mode:448});const o=he(n,t.manifest.dialect);if(r.writeFile(o,t.document),r.syncFile(o),t.manifest.dialect==="jsx"){const a=ye(n);r.writeFile(a,t.module),r.syncFile(a)}const u=ge(n);return r.writeFile(u,`${JSON.stringify(t.manifest,null,2)}
2
2
  `),r.syncFile(u),r.syncDirectory(n),r.syncDirectory(s),r.syncDirectory(e),r.syncDirectory(Z()),n}i(ee,"publishPageRevision");function Ye(e){if(e.kind!=="page"||e.presentation_dir===null)throw new Error(`page request has no selected presentation: ${e.request_id}`);return e.presentation_dir}i(Ye,"presentationDir");function Ze(e){const t=e.request_id??Ee(),r=C(t),s=ee(r,e.prepared),n=new Date().toISOString(),o=e.prepared.manifest;return f(u=>{u.prepare(`
3
3
  INSERT INTO human_requests (
4
4
  request_id, kind, inbox_ticket_id, request_dir, presentation_dir, requester_node_id, state, inbox_listed,
@@ -11,7 +11,7 @@ var de=Object.defineProperty;var i=(e,t)=>de(e,"name",{value:t,configurable:!0})
11
11
  specification_json, anchor_base_sha256, anchor_base_bytes, created_at, updated_at
12
12
  ) VALUES (?, 'review', ?, ?, ?, ?, ?, 'binding', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)
13
13
  ON CONFLICT(idempotency_key) DO NOTHING
14
- `).run(e.request_id,U(),e.request_dir,e.requester_node_id,e.companion_node_id,e.idempotency_key,e.inbox_listed?1:0,w(e.file),e.subtitle??null,e.file,JSON.stringify(e.specification),e.anchor_base_sha256,e.anchor_base_bytes,e.created_at,e.created_at),s=q(t,"idempotency_key = ?",e.idempotency_key);if(s===null)throw new Error(`review binding insert did not produce a row: ${e.idempotency_key}`);return{request_id:s.request_id,won:r.changes>0}})}i(et,"commitBindingRequest");function tt(e){return q(_(),"request_id = ?",e)}i(tt,"getRequest");function nt(e){return q(_(),"inbox_ticket_id = ?",e)}i(nt,"getRequestByInboxTicket");function rt(e){let t=e;try{t=L(e)}catch{}return q(_(),"request_dir = ?",t)}i(rt,"getRequestByDirectory");function it(e){return q(_(),"companion_node_id = ? AND state <> 'binding'",e)}i(it,"getRequestByCompanion");function st(e){return q(_(),"idempotency_key = ?",e)}i(st,"getRequestByIdempotencyKey");const ve=`NOT (kind = 'page' AND EXISTS (SELECT 1 FROM nodes n WHERE n.node_id = human_requests.requester_node_id
14
+ `).run(e.request_id,U(),e.request_dir,e.requester_node_id,e.companion_node_id,e.idempotency_key,e.inbox_listed?1:0,e.title??j(e.file),e.subtitle??null,e.file,JSON.stringify(e.specification),e.anchor_base_sha256,e.anchor_base_bytes,e.created_at,e.created_at),s=q(t,"idempotency_key = ?",e.idempotency_key);if(s===null)throw new Error(`review binding insert did not produce a row: ${e.idempotency_key}`);return{request_id:s.request_id,won:r.changes>0}})}i(et,"commitBindingRequest");function tt(e){return q(_(),"request_id = ?",e)}i(tt,"getRequest");function nt(e){return q(_(),"inbox_ticket_id = ?",e)}i(nt,"getRequestByInboxTicket");function rt(e){let t=e;try{t=L(e)}catch{}return q(_(),"request_dir = ?",t)}i(rt,"getRequestByDirectory");function it(e){return q(_(),"companion_node_id = ? AND state <> 'binding'",e)}i(it,"getRequestByCompanion");function st(e){return q(_(),"idempotency_key = ?",e)}i(st,"getRequestByIdempotencyKey");const ve=`NOT (kind = 'page' AND EXISTS (SELECT 1 FROM node_rows n WHERE n.node_id = human_requests.requester_node_id
15
15
  AND n.run_id IS NOT NULL AND n.grantee IS NOT NULL AND n.grantee <> 'app:terminal'))`;function ot(){return T(_(),`state = 'open' AND inbox_listed = 1 AND ${ve}`,[],"created_at DESC, request_id DESC")}i(ot,"listOpenInboxRequests");function Re(e){return T(_(),"state = 'open' AND requester_node_id = ?",[e],"created_at DESC, request_id DESC")}i(Re,"openRequestsByRequester");function at(e){return Re(e).some(t=>t.kind==="review"?!0:JSON.parse(t.specification_json).delivery?.reply===!0)}i(at,"hasOpenReplyBearingRequestByRequester");function dt(){return T(_(),"state = 'open' AND inbox_listed = 1 AND requester_node_id IS NOT NULL",[],"created_at DESC, request_id DESC")}i(dt,"listOpenReplyBearingRequests");function ut(){return T(_(),"kind = 'review' AND state = 'binding'")}i(ut,"listBindingRequests");function ct(){return T(_(),"kind = 'review' AND state = 'open' AND submit_requested_at IS NOT NULL")}i(ct,"listSubmitRequestedRequests");function lt(){return T(_(),"kind = 'review' AND state = 'settled' AND projected_at IS NULL")}i(lt,"listUnprojectedReviews");function _t(e={}){const t=["1"],r=[];for(const[s,n]of Object.entries(e))n!==void 0&&(t.push(`${s} = ?`),r.push(n));return T(_(),t.join(" AND "),r)}i(_t,"listRequests");function pt(e,t){return f(r=>r.prepare("UPDATE human_requests SET state = 'open', opened_at = ?, updated_at = ? WHERE request_id = ? AND state = 'binding'").run(t,t,e).changes>0)}i(pt,"openRequest");function mt(e,t,r){return f(s=>s.prepare(`
16
16
  UPDATE human_requests SET state = 'settled', outcome = 'canceled', result_json = ?, settled_at = ?, updated_at = ?
17
17
  WHERE request_id = ? AND kind = 'review' AND state = 'binding'
@@ -25,7 +25,7 @@ var de=Object.defineProperty;var i=(e,t)=>de(e,"name",{value:t,configurable:!0})
25
25
  `).run(t.presentation_dir,t.specification_json,t.title,t.subtitle,t.inbox_listed?1:0,t.settleable?1:0,new Date().toISOString(),e).changes>0)}i(ht,"revisePageRequest");function qt(e,t){return f(r=>r.prepare(`
26
26
  UPDATE human_requests SET progress_json = ?, updated_at = ?
27
27
  WHERE inbox_ticket_id = ? AND kind = 'page' AND state = 'open' AND settleable = 1
28
- `).run(JSON.stringify({kind:"page",responses:t,savedAt:new Date().toISOString()}),new Date().toISOString(),e).changes>0)}i(qt,"writeProgress");function Nt(e,t){f(r=>r.prepare("UPDATE human_requests SET projected_at = ?, projection_error = NULL, updated_at = ? WHERE request_id = ?").run(t,t,e))}i(Nt,"markProjected");function bt(e,t){f(r=>r.prepare("UPDATE human_requests SET projection_error = ?, updated_at = ? WHERE request_id = ? AND projected_at IS NULL").run(t,new Date().toISOString(),e))}i(bt,"markProjectionError");function Tt(e,t){f(r=>r.prepare("UPDATE human_requests SET companion_retired_at = ?, updated_at = ? WHERE request_id = ? AND companion_retired_at IS NULL").run(t,t,e))}i(Tt,"markCompanionRetired");function St(e){const t=_().prepare("SELECT anchor_base_bytes, anchor_base_sha256 FROM human_requests WHERE request_id = ?").get(e);return t===void 0||t.anchor_base_bytes===null||t.anchor_base_sha256===null?null:{bytes:Buffer.from(t.anchor_base_bytes),sha256:t.anchor_base_sha256}}i(St,"readAnchorBase");function vt(e,t,r,s){e.prepare("UPDATE human_requests SET anchor_base_bytes = ?, anchor_base_sha256 = ?, updated_at = ? WHERE request_id = ?").run(r,s,new Date().toISOString(),t)}i(vt,"replaceAnchorBaseLocked");function Ae(e){if(typeof e!="object"||e===null)throw new Error("result is not an object");const t=e;return t.kind==="canceled"?{outcome:t.disposition==="dismissed"?"dismissed":"canceled",settledAt:String(t.canceledAt)}:{outcome:"answered",settledAt:String(t.completedAt)}}i(Ae,"legacyPageResult");function R(e){try{return JSON.parse(V(e,"utf8"))}catch(t){throw new Error(`corrupt required input: ${e}`,{cause:t})}}i(R,"readJson");function H(){return j(16).toString("hex")}i(H,"migrationId");function De(e){return Number(e.prepare("SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}i(De,"nextMessageSeq");function Oe(e,t,r,s){return(s==="page"?e.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
28
+ `).run(JSON.stringify({kind:"page",responses:t,savedAt:new Date().toISOString()}),new Date().toISOString(),e).changes>0)}i(qt,"writeProgress");function Nt(e,t){f(r=>r.prepare("UPDATE human_requests SET projected_at = ?, projection_error = NULL, updated_at = ? WHERE request_id = ?").run(t,t,e))}i(Nt,"markProjected");function bt(e,t){f(r=>r.prepare("UPDATE human_requests SET projection_error = ?, updated_at = ? WHERE request_id = ? AND projected_at IS NULL").run(t,new Date().toISOString(),e))}i(bt,"markProjectionError");function Tt(e,t){f(r=>r.prepare("UPDATE human_requests SET companion_retired_at = ?, updated_at = ? WHERE request_id = ? AND companion_retired_at IS NULL").run(t,t,e))}i(Tt,"markCompanionRetired");function St(e){const t=_().prepare("SELECT anchor_base_bytes, anchor_base_sha256 FROM human_requests WHERE request_id = ?").get(e);return t===void 0||t.anchor_base_bytes===null||t.anchor_base_sha256===null?null:{bytes:Buffer.from(t.anchor_base_bytes),sha256:t.anchor_base_sha256}}i(St,"readAnchorBase");function vt(e,t,r,s){e.prepare("UPDATE human_requests SET anchor_base_bytes = ?, anchor_base_sha256 = ?, updated_at = ? WHERE request_id = ?").run(r,s,new Date().toISOString(),t)}i(vt,"replaceAnchorBaseLocked");function Ae(e){if(typeof e!="object"||e===null)throw new Error("result is not an object");const t=e;return t.kind==="canceled"?{outcome:t.disposition==="dismissed"?"dismissed":"canceled",settledAt:String(t.canceledAt)}:{outcome:"answered",settledAt:String(t.completedAt)}}i(Ae,"legacyPageResult");function R(e){try{return JSON.parse(V(e,"utf8"))}catch(t){throw new Error(`corrupt required input: ${e}`,{cause:t})}}i(R,"readJson");function H(){return w(16).toString("hex")}i(H,"migrationId");function De(e){return Number(e.prepare("SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}i(De,"nextMessageSeq");function Oe(e,t,r,s){return(s==="page"?e.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
29
29
  WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.sender_node_id = ?
30
30
  AND m.disposition IN ('human-answer', 'human-canceled') LIMIT 1`).get(r,t):e.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
31
31
  WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND m.body_json LIKE ? LIMIT 1`).get(r,`%"review_id":"${t}"%`))?.delivery_id??null}i(Oe,"importedTerminalDelivery");function te(e,t,r){if(t===null||r===null)return!1;const s=e.prepare("SELECT status, final_report FROM nodes WHERE node_id = ?").get(t);return s?.status==="canceled"||r==="approved"&&s?.status==="done"&&s.final_report!==null}i(te,"companionRetirementProven");function ne(e){if(typeof e!="object"||e===null)return"no reason was given";const t=e.reason;return typeof t=="string"&&t!==""?t:"no reason was given"}i(ne,"migratedCancellationReason");function Ie(e,t){const r=e.outcome==="canceled"||e.outcome==="dismissed";return[e.kind==="review"?r?`Review ${e.requestId} was canceled \u2014 ${ne(t)}.`:`Review ${e.requestId} was approved by the user.`:r?`Human request ${e.requestId} was canceled \u2014 ${ne(t)}.`:`Human request ${e.requestId} was answered.`,...e.kind==="review"?[`The review result is at ${e.requestDir}/result.json.`]:[],`Result:
@@ -36,8 +36,8 @@ ${JSON.stringify(t,null,2)}`].join(`
36
36
  VALUES (?, ?, ?, ?, NULL, 'crtrd', 'completed', ?, NULL, ?, ?)`).run(r,De(e),H(),t.settledAt,l.split(`
37
37
  `,1)[0],JSON.stringify({body:l,result:a}),u),e.prepare(`INSERT INTO deliveries
38
38
  (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, created_at, updated_at)
39
- VALUES (?, ?, 'node_inbox', ?, 'normal', 1, 'pending', 0, ?, ?)`).run(s,r,t.requesterNodeId,o,o),s}i(Le,"createMigratedTerminalDelivery");function re(e,t){if(t.requesterNodeId===null||t.outcome===null||t.resultJson===null||t.settledAt===null)return null;const r=Oe(e,t.requestId,t.requesterNodeId,t.kind);return r!==null?r:t.deliveredAt!==null&&t.deliveredAt!==void 0?null:Le(e,{requestId:t.requestId,requesterNodeId:t.requesterNodeId,kind:t.kind,outcome:t.outcome,resultJson:t.resultJson,settledAt:t.settledAt,requestDir:t.requestDir})}i(re,"terminalDeliveryMark");const ke=d.object({sessionName:d.string().optional(),askedBy:d.string().optional(),blockedSince:d.string().optional(),profileName:d.string().optional(),nodeId:d.string().optional()}).strict(),xe=d.object({id:d.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),kind:d.string().min(1),step:d.number().int().nonnegative(),config:d.record(d.string(),d.unknown()),unvalidated:d.literal(!0).optional(),display:d.literal(!0).optional()}).strict(),je=d.object({schema:d.literal("crtr.page/v1"),dialect:d.enum(["md","html","jsx"]),title:d.string().trim().min(1),subtitle:d.string().optional(),placement:d.enum(["inline","panel"]),document:d.enum(["page.md","page.html","page.tsx"]),steps:d.number().int().positive(),slots:d.array(xe),source:ke.optional()}).strict().superRefine((e,t)=>{const r=e.dialect==="md"?"page.md":e.dialect==="html"?"page.html":"page.tsx";e.document!==r&&t.addIssue({code:"custom",path:["document"],message:"document must agree with dialect"}),e.dialect==="md"&&e.steps!==1&&t.addIssue({code:"custom",path:["steps"],message:"md pages have exactly one step"})});function we(e){if(e.source===void 0)return;const{blockedSince:t,...r}=e.source,s={...r,...t!==void 0&&d.string().datetime({offset:!0}).safeParse(t).success?{emittedAt:t}:{}};return Object.keys(s).length===0?void 0:s}i(we,"legacyPresentationSource");function Ce(e,t,r){return`export default function LegacyPage() { return <Page title={${JSON.stringify(e)}}${t===void 0?"":` subtitle={${JSON.stringify(t)}}`}><pre>{${JSON.stringify(r)}}</pre></Page>; }
40
- `}i(Ce,"legacyReplayDocument");function ie(e){return Array.isArray(e.slots)?{...e,slots:e.slots.map(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const r=t;if(r.kind!=="text"||typeof r.config!="object"||r.config===null||Array.isArray(r.config))return t;const{editable:s,...n}=r.config;return{...r,config:n}})}:e}i(ie,"withoutLegacyTextEditable");function Ue(e,t){const r=c(e,"page.json"),s=je.safeParse(t);if(!s.success)throw new Error(s.error.message);const n=s.data,o=we(n),u={placement:n.placement,inbox:!0,reply:n.source?.blockedSince!==void 0};z(ie({schema:"crtr.page/v2",dialect:"jsx",title:n.title,...n.subtitle===void 0?{}:{subtitle:n.subtitle},delivery:u,document:"page.tsx",steps:n.steps,slots:n.slots,...o===void 0?{}:{source:o}}));const a=c(e,n.document);if(!g(a))throw new Error(`corrupt required input: ${a}`);const l=V(a,"utf8"),m=qe({dialect:"jsx",document:Ce(n.title,n.subtitle,l),source:o,delivery:u});if(o!==void 0)return m;const{source:E,...y}=m.manifest;return{...m,manifest:y}}i(Ue,"migrateLegacyPage");function Rt(e){e.exec(`
39
+ VALUES (?, ?, 'node_inbox', ?, 'normal', 1, 'pending', 0, ?, ?)`).run(s,r,t.requesterNodeId,o,o),s}i(Le,"createMigratedTerminalDelivery");function re(e,t){if(t.requesterNodeId===null||t.outcome===null||t.resultJson===null||t.settledAt===null)return null;const r=Oe(e,t.requestId,t.requesterNodeId,t.kind);return r!==null?r:t.deliveredAt!==null&&t.deliveredAt!==void 0?null:Le(e,{requestId:t.requestId,requesterNodeId:t.requesterNodeId,kind:t.kind,outcome:t.outcome,resultJson:t.resultJson,settledAt:t.settledAt,requestDir:t.requestDir})}i(re,"terminalDeliveryMark");const ke=d.object({sessionName:d.string().optional(),askedBy:d.string().optional(),blockedSince:d.string().optional(),profileName:d.string().optional(),nodeId:d.string().optional()}).strict(),xe=d.object({id:d.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional(),kind:d.string().min(1),step:d.number().int().nonnegative(),config:d.record(d.string(),d.unknown()),unvalidated:d.literal(!0).optional(),display:d.literal(!0).optional()}).strict(),we=d.object({schema:d.literal("crtr.page/v1"),dialect:d.enum(["md","html","jsx"]),title:d.string().trim().min(1),subtitle:d.string().optional(),placement:d.enum(["inline","panel"]),document:d.enum(["page.md","page.html","page.tsx"]),steps:d.number().int().positive(),slots:d.array(xe),source:ke.optional()}).strict().superRefine((e,t)=>{const r=e.dialect==="md"?"page.md":e.dialect==="html"?"page.html":"page.tsx";e.document!==r&&t.addIssue({code:"custom",path:["document"],message:"document must agree with dialect"}),e.dialect==="md"&&e.steps!==1&&t.addIssue({code:"custom",path:["steps"],message:"md pages have exactly one step"})});function je(e){if(e.source===void 0)return;const{blockedSince:t,...r}=e.source,s={...r,...t!==void 0&&d.string().datetime({offset:!0}).safeParse(t).success?{emittedAt:t}:{}};return Object.keys(s).length===0?void 0:s}i(je,"legacyPresentationSource");function Ce(e,t,r){return`export default function LegacyPage() { return <Page title={${JSON.stringify(e)}}${t===void 0?"":` subtitle={${JSON.stringify(t)}}`}><pre>{${JSON.stringify(r)}}</pre></Page>; }
40
+ `}i(Ce,"legacyReplayDocument");function ie(e){return Array.isArray(e.slots)?{...e,slots:e.slots.map(t=>{if(typeof t!="object"||t===null||Array.isArray(t))return t;const r=t;if(r.kind!=="text"||typeof r.config!="object"||r.config===null||Array.isArray(r.config))return t;const{editable:s,...n}=r.config;return{...r,config:n}})}:e}i(ie,"withoutLegacyTextEditable");function Ue(e,t){const r=c(e,"page.json"),s=we.safeParse(t);if(!s.success)throw new Error(s.error.message);const n=s.data,o=je(n),u={placement:n.placement,inbox:!0,reply:n.source?.blockedSince!==void 0};z(ie({schema:"crtr.page/v2",dialect:"jsx",title:n.title,...n.subtitle===void 0?{}:{subtitle:n.subtitle},delivery:u,document:"page.tsx",steps:n.steps,slots:n.slots,...o===void 0?{}:{source:o}}));const a=c(e,n.document);if(!g(a))throw new Error(`corrupt required input: ${a}`);const l=V(a,"utf8"),m=qe({dialect:"jsx",document:Ce(n.title,n.subtitle,l),source:o,delivery:u});if(o!==void 0)return m;const{source:E,...y}=m.manifest;return{...m,manifest:y}}i(Ue,"migrateLegacyPage");function Rt(e){e.exec(`
41
41
  CREATE TABLE human_requests (
42
42
  request_id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('page','review')),
43
43
  inbox_ticket_id TEXT NOT NULL UNIQUE, request_dir TEXT NOT NULL, presentation_dir TEXT,
@@ -66,4 +66,4 @@ ${JSON.stringify(t,null,2)}`].join(`
66
66
  progress_json, feedback_json, result_json, anchor_base_sha256, anchor_base_bytes, created_at, opened_at,
67
67
  submit_requested_at, settled_at, settlement_delivery_id, action_delivery_id, projected_at, projection_error,
68
68
  companion_retired_at, updated_at
69
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);if(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'reviews'").get()!==void 0){const s=e.prepare("SELECT * FROM reviews").all();for(const n of s){const o=n.state,u=o==="approved"||o==="canceled",a=o==="canceled"&&n.result_json===null?JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:n.canceled_at,...n.cancel_reason===""||n.cancel_reason===null?{}:{reason:n.cancel_reason},...n.cancel_actor===null?{}:{actor:n.cancel_actor}}):n.result_json;if(u&&a===null)throw new Error(`corrupt required input: reviews/${n.review_id} has no terminal result`);const l=n.bridge_node_id===null?c(Q(),"reviews",n.review_id):c(b(),n.bridge_node_id),m={origin_kind:n.origin_kind,bridge_node_id:n.bridge_node_id,origin_session_file:n.origin_session_file,origin_session_id:n.origin_session_id,origin_leaf_id:n.origin_leaf_id,model_spec:n.model_spec,branch_file:n.branch_file,baseline_sha256:n.baseline_sha256,baseline_bytes:n.baseline_bytes,captured_at:n.captured_at,output_path:n.output_path},E=u?o==="approved"?"approved":"canceled":null,y=u?o==="approved"?n.approved_at:n.canceled_at:null,S=re(e,{requestId:n.review_id,requesterNodeId:n.origin_node_id,kind:"review",outcome:E,resultJson:a,settledAt:y,requestDir:l,deliveredAt:n.delivered_at}),D=te(e,n.companion_node_id,E)?y:null;t.run(n.review_id,"review",n.origin_kind==="ticket"?P(b(),w(l)):U(),l,null,n.origin_node_id,n.companion_node_id,n.idempotency_key,u?"settled":o,E,n.origin_kind==="ticket"?1:0,1,w(n.file),n.subtitle,n.file,JSON.stringify(m),null,null,null,a,n.anchor_base_sha256,n.anchor_base_bytes,n.created,n.opened_at,n.submit_requested_at,y,S,null,n.projected_at,n.projection_error,D,n.created)}e.exec("DROP TABLE reviews")}for(const s of g(b())?ce(b(),{withFileTypes:!0}):[]){if(!s.isDirectory())continue;const n=c(b(),s.name),o=c(n,"page.json"),u=c(n,"review.json");if(!g(o)){if(g(u))continue;continue}if(e.prepare("SELECT 1 FROM human_requests WHERE request_id = ?").get(s.name)!==void 0)continue;let a,l,m,E;try{const p=R(o);if(typeof p!="object"||p===null||Array.isArray(p))throw new Error("page manifest must be an object");a=p,a.schema==="crtr.page/v1"?(l=Ue(n,p),a=l.manifest):a.schema==="crtr.page/v2"&&(a=ie(a));const v=Ne.safeParse(a.delivery);if(typeof a.title!="string"||!v.success)throw new Error(v.success?"page title must be a string":v.error.message);E=v.data,m=z(a)}catch(p){const v=p instanceof Error&&p.cause instanceof Error?p.cause.message:p instanceof Error?p.message:String(p);console.warn(`skipping legacy page ${o}: ${v}`);continue}let y=L(n);l!==void 0&&(y=ee(C(s.name),l));const S=m.source,D=c(n,"response.json"),O=g(D)?R(D):null,h=O===null?null:Ae(O),se=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'deliveries'").get()===void 0?null:e.prepare("SELECT delivery_id FROM deliveries WHERE idempotency_key = ?").get(`human-action:${P(b(),s.name)}`),X=c(n,"action.json"),$=c(n,"progress.json"),k=c(n,"feedback-comments.json"),x=c(n,"reply-route.json"),N=g(k)?R(k):null;if(N!==null&&(typeof N!="object"||typeof N.companionNodeId<"u"&&typeof N.companionNodeId!="string"))throw new Error(`corrupt required input: ${k}`);const I=g(x)?R(x):null;if(I!==null&&(typeof I!="object"||typeof I.bridge_node_id!="string"))throw new Error(`corrupt required input: ${x}`);const M=I?.bridge_node_id,F=(typeof M!="string"||e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'nodes'").get()===void 0?null:e.prepare("SELECT parent FROM nodes WHERE node_id = ?").get(M))?.parent??(typeof S?.nodeId=="string"?S.nodeId:null),W=N?.companionNodeId,J=typeof S?.emittedAt=="string"?S.emittedAt:le(o).mtime.toISOString(),B=O===null?null:JSON.stringify(O),oe=re(e,{requestId:s.name,requesterNodeId:F,kind:"page",outcome:h?.outcome??null,resultJson:B,settledAt:h?.settledAt??null,requestDir:n}),ae=te(e,W??null,h?.outcome??null)?h?.settledAt??null:null,K=C(s.name);A(K,{recursive:!0,mode:448}),t.run(s.name,"page",P(b(),s.name),K,y,F,W??null,null,h===null?"open":"settled",h?.outcome??null,E.inbox?1:0,E.inbox||E.reply?1:0,m.title,m.subtitle??null,null,JSON.stringify(m),g(X)?JSON.stringify(R(X)):null,g($)&&h===null?JSON.stringify(R($)):null,N===null?null:JSON.stringify(N),B,null,null,J,null,null,h?.settledAt??null,oe,se?.delivery_id??null,null,null,ae,J)}const r=e.prepare("SELECT request_id FROM human_requests WHERE state = 'settled' AND result_json IS NULL").get();if(r!==void 0)throw new Error(`human request migration produced terminal row without result: ${r.request_id}`);if(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'review_comments'").get()!==void 0){const s=e.prepare("SELECT review_id FROM review_comments WHERE review_id NOT IN (SELECT request_id FROM human_requests WHERE kind = 'review') LIMIT 1").get();if(s!==void 0)throw new Error(`review comment has no migrated review request: ${s.review_id}`)}}i(Rt,"migrateHumanRequestsState");export{ve as NOT_OTHER_APP_QUESTION,mt as cancelBindingRequest,et as commitBindingRequest,Ze as createPageRequest,tt as getRequest,it as getRequestByCompanion,rt as getRequestByDirectory,st as getRequestByIdempotencyKey,nt as getRequestByInboxTicket,at as hasOpenReplyBearingRequestByRequester,Z as humanRequestsRoot,ut as listBindingRequests,ot as listOpenInboxRequests,dt as listOpenReplyBearingRequests,_t as listRequests,ct as listSubmitRequestedRequests,lt as listUnprojectedReviews,Tt as markCompanionRetired,Nt as markProjected,bt as markProjectionError,Rt as migrateHumanRequestsState,pt as openRequest,Re as openRequestsByRequester,Ye as presentationDir,ee as publishPageRevision,St as readAnchorBase,vt as replaceAnchorBaseLocked,C as requestDir,ft as requestSubmit,ht as revisePageRequest,gt as setSettlementDeliveryMarksLocked,yt as setSubmitNoteDeliveryLocked,Et as settleRequestLocked,qt as writeProgress};
69
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);if(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'reviews'").get()!==void 0){const s=e.prepare("SELECT * FROM reviews").all();for(const n of s){const o=n.state,u=o==="approved"||o==="canceled",a=o==="canceled"&&n.result_json===null?JSON.stringify({schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:n.canceled_at,...n.cancel_reason===""||n.cancel_reason===null?{}:{reason:n.cancel_reason},...n.cancel_actor===null?{}:{actor:n.cancel_actor}}):n.result_json;if(u&&a===null)throw new Error(`corrupt required input: reviews/${n.review_id} has no terminal result`);const l=n.bridge_node_id===null?c(Q(),"reviews",n.review_id):c(b(),n.bridge_node_id),m={origin_kind:n.origin_kind,bridge_node_id:n.bridge_node_id,origin_session_file:n.origin_session_file,origin_session_id:n.origin_session_id,origin_leaf_id:n.origin_leaf_id,model_spec:n.model_spec,branch_file:n.branch_file,baseline_sha256:n.baseline_sha256,baseline_bytes:n.baseline_bytes,captured_at:n.captured_at,output_path:n.output_path},E=u?o==="approved"?"approved":"canceled":null,y=u?o==="approved"?n.approved_at:n.canceled_at:null,S=re(e,{requestId:n.review_id,requesterNodeId:n.origin_node_id,kind:"review",outcome:E,resultJson:a,settledAt:y,requestDir:l,deliveredAt:n.delivered_at}),D=te(e,n.companion_node_id,E)?y:null;t.run(n.review_id,"review",n.origin_kind==="ticket"?P(b(),j(l)):U(),l,null,n.origin_node_id,n.companion_node_id,n.idempotency_key,u?"settled":o,E,n.origin_kind==="ticket"?1:0,1,j(n.file),n.subtitle,n.file,JSON.stringify(m),null,null,null,a,n.anchor_base_sha256,n.anchor_base_bytes,n.created,n.opened_at,n.submit_requested_at,y,S,null,n.projected_at,n.projection_error,D,n.created)}e.exec("DROP TABLE reviews")}for(const s of g(b())?ce(b(),{withFileTypes:!0}):[]){if(!s.isDirectory())continue;const n=c(b(),s.name),o=c(n,"page.json"),u=c(n,"review.json");if(!g(o)){if(g(u))continue;continue}if(e.prepare("SELECT 1 FROM human_requests WHERE request_id = ?").get(s.name)!==void 0)continue;let a,l,m,E;try{const p=R(o);if(typeof p!="object"||p===null||Array.isArray(p))throw new Error("page manifest must be an object");a=p,a.schema==="crtr.page/v1"?(l=Ue(n,p),a=l.manifest):a.schema==="crtr.page/v2"&&(a=ie(a));const v=Ne.safeParse(a.delivery);if(typeof a.title!="string"||!v.success)throw new Error(v.success?"page title must be a string":v.error.message);E=v.data,m=z(a)}catch(p){const v=p instanceof Error&&p.cause instanceof Error?p.cause.message:p instanceof Error?p.message:String(p);console.warn(`skipping legacy page ${o}: ${v}`);continue}let y=L(n);l!==void 0&&(y=ee(C(s.name),l));const S=m.source,D=c(n,"response.json"),O=g(D)?R(D):null,h=O===null?null:Ae(O),se=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'deliveries'").get()===void 0?null:e.prepare("SELECT delivery_id FROM deliveries WHERE idempotency_key = ?").get(`human-action:${P(b(),s.name)}`),X=c(n,"action.json"),$=c(n,"progress.json"),k=c(n,"feedback-comments.json"),x=c(n,"reply-route.json"),N=g(k)?R(k):null;if(N!==null&&(typeof N!="object"||typeof N.companionNodeId<"u"&&typeof N.companionNodeId!="string"))throw new Error(`corrupt required input: ${k}`);const I=g(x)?R(x):null;if(I!==null&&(typeof I!="object"||typeof I.bridge_node_id!="string"))throw new Error(`corrupt required input: ${x}`);const M=I?.bridge_node_id,F=(typeof M!="string"||e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'nodes'").get()===void 0?null:e.prepare("SELECT parent FROM nodes WHERE node_id = ?").get(M))?.parent??(typeof S?.nodeId=="string"?S.nodeId:null),W=N?.companionNodeId,J=typeof S?.emittedAt=="string"?S.emittedAt:le(o).mtime.toISOString(),B=O===null?null:JSON.stringify(O),oe=re(e,{requestId:s.name,requesterNodeId:F,kind:"page",outcome:h?.outcome??null,resultJson:B,settledAt:h?.settledAt??null,requestDir:n}),ae=te(e,W??null,h?.outcome??null)?h?.settledAt??null:null,K=C(s.name);A(K,{recursive:!0,mode:448}),t.run(s.name,"page",P(b(),s.name),K,y,F,W??null,null,h===null?"open":"settled",h?.outcome??null,E.inbox?1:0,E.inbox||E.reply?1:0,m.title,m.subtitle??null,null,JSON.stringify(m),g(X)?JSON.stringify(R(X)):null,g($)&&h===null?JSON.stringify(R($)):null,N===null?null:JSON.stringify(N),B,null,null,J,null,null,h?.settledAt??null,oe,se?.delivery_id??null,null,null,ae,J)}const r=e.prepare("SELECT request_id FROM human_requests WHERE state = 'settled' AND result_json IS NULL").get();if(r!==void 0)throw new Error(`human request migration produced terminal row without result: ${r.request_id}`);if(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'review_comments'").get()!==void 0){const s=e.prepare("SELECT review_id FROM review_comments WHERE review_id NOT IN (SELECT request_id FROM human_requests WHERE kind = 'review') LIMIT 1").get();if(s!==void 0)throw new Error(`review comment has no migrated review request: ${s.review_id}`)}}i(Rt,"migrateHumanRequestsState");export{ve as NOT_OTHER_APP_QUESTION,mt as cancelBindingRequest,et as commitBindingRequest,Ze as createPageRequest,tt as getRequest,it as getRequestByCompanion,rt as getRequestByDirectory,st as getRequestByIdempotencyKey,nt as getRequestByInboxTicket,at as hasOpenReplyBearingRequestByRequester,Z as humanRequestsRoot,ut as listBindingRequests,ot as listOpenInboxRequests,dt as listOpenReplyBearingRequests,_t as listRequests,ct as listSubmitRequestedRequests,lt as listUnprojectedReviews,Tt as markCompanionRetired,Nt as markProjected,bt as markProjectionError,Rt as migrateHumanRequestsState,pt as openRequest,Re as openRequestsByRequester,Ye as presentationDir,ee as publishPageRevision,St as readAnchorBase,vt as replaceAnchorBaseLocked,C as requestDir,ft as requestSubmit,ht as revisePageRequest,gt as setSettlementDeliveryMarksLocked,yt as setSubmitNoteDeliveryLocked,Et as settleRequestLocked,qt as writeProgress};
@@ -1,2 +1,2 @@
1
- var v=Object.defineProperty;var o=(e,t)=>v(e,"name",{value:t,configurable:!0});const i=o(e=>String.fromCodePoint(e),"cp"),u={identity:i(62144),state:i(61713),place:i(61563),graph:i(61920),artifacts:i(61914),paths:i(61686),cron:i(61463),job:i(61459),log:i(61728),section:i(61842),raw:i(61729),empty:i(61875)},y={active:{glyph:"\u25CF",tone:"good"},idle:{glyph:"\u25CB",tone:"warn"},done:{glyph:"\u2713",tone:"accent"},dead:{glyph:"\u2717",tone:"bad"},canceled:{glyph:"\u2298",tone:"dim"}};function w(e){return y[e]??{glyph:"\u25C6",tone:"plain"}}o(w,"statusVisual");function D(e){return e.map(t=>({cron:t,nextAt:t.fire_at,cadence:t.recur===null||t.recur==="none"?"one-shot":t.recur,target:t.sink??t.anchor_node??"daemon"})).sort((t,n)=>t.nextAt!==n.nextAt?t.nextAt.localeCompare(n.nextAt):t.cron.cron_id.localeCompare(n.cron.cron_id))}o(D,"scheduledItems");function M(e){const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;const n=Math.floor(t/60);return n<60?`${n}m ${String(t%60).padStart(2,"0")}s`:`${Math.floor(n/60)}h ${String(n%60).padStart(2,"0")}m`}o(M,"elapsed");function F(e){return e>=60*6e4?"bad":e>=15*6e4?"warn":"good"}o(F,"jobTone");function S(e,t=Date.now()){const n=Date.parse(e.started_at);return Number.isFinite(n)?t-n:e.elapsed_ms}o(S,"jobElapsedMs");function C(e,t=Date.now()){return M(S(e,t))}o(C,"jobElapsed");function A(e,t=60){const n=(e.split(`
2
- `)[0]??"").replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}o(A,"commandCell");function L(e,t=60){return A(e.purpose??e.command,t)}o(L,"jobLabel");function T(e,t=Date.now()){if(e===null)return"\u2014";const n=Date.parse(e);if(!Number.isFinite(n))return e;const c=n-t;if(c<=0)return"due now";const r=Math.ceil(c/6e4);if(r<60)return`in ${r}m`;const a=Math.floor(r/60);return a<24?`in ${a}h${r%60?` ${r%60}m`:""}`:`in ${Math.floor(a/24)}d${a%24?` ${a%24}h`:""}`}o(T,"relativeTime");function j(e,t=Date.now()){if(typeof e!="string"||e==="")return"\u2014";const n=Date.parse(e);if(!Number.isFinite(n))return String(e);const c=Math.max(0,Math.floor((t-n)/1e3));if(c<60)return`${c}s ago`;const r=Math.floor(c/60);if(r<60)return`${r}m ago`;const a=Math.floor(r/60);if(a<24)return`${a}h ago`;const s=Math.floor(a/24);return s<30?`${s}d ago`:`${Math.floor(s/30)}mo ago`}o(j,"ago");function d(e,t=process.env.HOME??""){const n=l(e);return t!==""&&n.startsWith(`${t}/`)?`~${n.slice(t.length)}`:n}o(d,"shortPath");function N(e){const t=Number(e);return Number.isFinite(t)?t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)}k`:`${(t/1e6).toFixed(1)}M`:l(e)}o(N,"compactCount");function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}o(b,"neighbors");function $(e){if(e.length===0)return"\u2014";const t=e.slice(0,3).map(n=>n.name??n.node_id??"?");return e.length>3?`${t.join(", ")} +${e.length-3}`:t.join(", ")}o($,"neighborLine");function E(e){const t=m(e?.node),n=m(e?.paths),c=m(e?.artifacts),r=l(t.status),a=w(r),s=l(t.intent),h=l(t.waiting_for),g=b(e?.managers),x=b(e?.reports),f=Number(e?.pending_crons??0);return[{icon:u.identity,title:"identity",fields:[{label:"name",value:l(t.name),tone:"accent"},{label:"id",value:l(t.node_id),tone:"dim"},{label:"role",value:_(t.kind,t.mode,t.lifecycle)},{label:"model",value:l(t.model??t.model_override),tone:t.model??t.model_override?"plain":"dim"}]},{icon:u.state,title:"state",fields:[{label:"status",value:r,tone:a.tone,glyph:a.glyph},{label:"intent",value:s,tone:s==="\u2014"?"dim":"warn"},{label:"waiting on",value:h,tone:h==="\u2014"?"dim":"warn"},{label:"context",value:`${N(t.context_tokens)} tokens \xB7 ${l(t.cycles)} cycle(s)`},{label:"created",value:`${j(t.created)}`,tone:"dim"}]},{icon:u.place,title:"place",fields:[{label:"workspace",value:d(t.cwd)},{label:"profile",value:l(t.profile_id),tone:"dim"},{label:"host",value:_(t.host_kind,t.pi_pid?`pid ${String(t.pi_pid)}`:null),tone:"dim"}]},{icon:u.graph,title:"graph",fields:[{label:"managers",value:$(g),tone:g.length===0?"dim":"plain"},{label:"reports",value:$(x),tone:x.length===0?"dim":"plain"},{label:"parent",value:l(t.parent),tone:"dim"}]},{icon:u.artifacts,title:"output",fields:[{label:"artifacts",value:`${p(c.doc)} doc \xB7 ${p(c.report)} report \xB7 ${p(c.roadmap)} roadmap`},{label:"crons",value:f===0?"none armed":`${f} armed`,tone:f===0?"dim":"accent"}]},{icon:u.paths,title:"paths",fields:[{label:"context",value:d(n.context_dir),tone:"dim"},{label:"reports",value:d(n.reports_dir),tone:"dim"},{label:"session",value:d(n.session_file??t.pi_session_file),tone:"dim"}]}]}o(E,"overviewGroups");function p(e){const t=Number(e??0);return Number.isFinite(t)?String(t):"0"}o(p,"count");function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}o(m,"record");function l(e){return e==null||e===""?"\u2014":String(e)}o(l,"value");function _(...e){return e.map(l).filter(t=>t!=="\u2014").join(" \xB7 ")||"\u2014"}o(_,"join");export{u as ICON,j as ago,A as commandCell,N as compactCount,M as elapsed,C as jobElapsed,S as jobElapsedMs,L as jobLabel,F as jobTone,E as overviewGroups,m as record,T as relativeTime,D as scheduledItems,d as shortPath,w as statusVisual,l as value};
1
+ var y=Object.defineProperty;var o=(e,t)=>y(e,"name",{value:t,configurable:!0});const i=o(e=>String.fromCodePoint(e),"cp"),u={identity:i(62144),state:i(61713),place:i(61563),graph:i(61920),artifacts:i(61914),paths:i(61686),cron:i(61463),job:i(61459),log:i(61728),section:i(61842),raw:i(61729),empty:i(61875)},v={active:{glyph:"\u25CF",tone:"good"},idle:{glyph:"\u25CB",tone:"warn"},done:{glyph:"\u2713",tone:"accent"},dead:{glyph:"\u2717",tone:"bad"},canceled:{glyph:"\u2298",tone:"dim"}};function w(e){return v[e]??{glyph:"\u25C6",tone:"plain"}}o(w,"statusVisual");function D(e){return e.map(t=>({cron:t,nextAt:t.fire_at,cadence:t.recur===null||t.recur==="none"?"one-shot":t.recur,target:t.sink??t.anchor_node??"daemon"})).sort((t,n)=>t.nextAt!==n.nextAt?t.nextAt.localeCompare(n.nextAt):t.cron.cron_id.localeCompare(n.cron.cron_id))}o(D,"scheduledItems");function M(e){const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;const n=Math.floor(t/60);return n<60?`${n}m ${String(t%60).padStart(2,"0")}s`:`${Math.floor(n/60)}h ${String(n%60).padStart(2,"0")}m`}o(M,"elapsed");function F(e){return e>=60*6e4?"bad":e>=15*6e4?"warn":"good"}o(F,"jobTone");function S(e,t=Date.now()){const n=Date.parse(e.started_at);return Number.isFinite(n)?t-n:e.elapsed_ms}o(S,"jobElapsedMs");function C(e,t=Date.now()){return M(S(e,t))}o(C,"jobElapsed");function A(e,t=60){const n=(e.split(`
2
+ `)[0]??"").replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}o(A,"commandCell");function L(e,t=60){return A(e.purpose??e.command,t)}o(L,"jobLabel");function T(e,t=Date.now()){if(e===null)return"\u2014";const n=Date.parse(e);if(!Number.isFinite(n))return e;const c=n-t;if(c<=0)return"due now";const r=Math.ceil(c/6e4);if(r<60)return`in ${r}m`;const a=Math.floor(r/60);return a<24?`in ${a}h${r%60?` ${r%60}m`:""}`:`in ${Math.floor(a/24)}d${a%24?` ${a%24}h`:""}`}o(T,"relativeTime");function j(e,t=Date.now()){if(typeof e!="string"||e==="")return"\u2014";const n=Date.parse(e);if(!Number.isFinite(n))return String(e);const c=Math.max(0,Math.floor((t-n)/1e3));if(c<60)return`${c}s ago`;const r=Math.floor(c/60);if(r<60)return`${r}m ago`;const a=Math.floor(r/60);if(a<24)return`${a}h ago`;const s=Math.floor(a/24);return s<30?`${s}d ago`:`${Math.floor(s/30)}mo ago`}o(j,"ago");function d(e,t=process.env.HOME??""){const n=l(e);return t!==""&&n.startsWith(`${t}/`)?`~${n.slice(t.length)}`:n}o(d,"shortPath");function N(e){const t=Number(e);return Number.isFinite(t)?t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(t<1e4?1:0)}k`:`${(t/1e6).toFixed(1)}M`:l(e)}o(N,"compactCount");function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null):[]}o(b,"neighbors");function $(e){if(e.length===0)return"\u2014";const t=e.slice(0,3).map(n=>n.name??n.node_id??"?");return e.length>3?`${t.join(", ")} +${e.length-3}`:t.join(", ")}o($,"neighborLine");function E(e){const t=m(e?.node),n=m(e?.paths),c=m(e?.artifacts),r=l(t.status),a=w(r),s=l(t.intent),h=l(t.waiting_for),g=b(e?.managers),x=b(e?.reports),f=Number(e?.pending_crons??0);return[{icon:u.identity,title:"identity",fields:[{label:"name",value:l(t.name),tone:"accent"},{label:"id",value:l(t.node_id),tone:"dim"},{label:"role",value:_(t.kind,t.mode,t.lifecycle)},{label:"model",value:l(t.model??t.model_override),tone:t.model??t.model_override?"plain":"dim"}]},{icon:u.state,title:"state",fields:[{label:"status",value:r,tone:a.tone,glyph:a.glyph},{label:"intent",value:s,tone:s==="\u2014"?"dim":"warn"},{label:"waiting on",value:h,tone:h==="\u2014"?"dim":"warn"},{label:"context",value:`${N(t.context_tokens)} tokens \xB7 ${l(t.cycles)} cycle(s)`},{label:"created",value:`${j(t.created)}`,tone:"dim"}]},{icon:u.place,title:"place",fields:[{label:"workspace",value:d(t.cwd)},{label:"profile",value:l(t.profile_id),tone:"dim"},{label:"host",value:_(t.host_kind,t.pi_pid?`pid ${String(t.pi_pid)}`:null),tone:"dim"}]},{icon:u.graph,title:"graph",fields:[{label:"managers",value:$(g),tone:g.length===0?"dim":"plain"},{label:"reports",value:$(x),tone:x.length===0?"dim":"plain"},{label:"parent",value:l(t.parent),tone:"dim"}]},{icon:u.artifacts,title:"output",fields:[{label:"artifacts",value:`${p(c.doc)} doc \xB7 ${p(c.report)} report \xB7 ${p(c.roadmap)} roadmap`},{label:"crons",value:f===0?"none armed":`${f} armed`,tone:f===0?"dim":"accent"}]},{icon:u.paths,title:"paths",fields:[{label:"context",value:d(n.context_dir),tone:"dim"},{label:"session",value:d(n.session_file??t.pi_session_file),tone:"dim"}]}]}o(E,"overviewGroups");function p(e){const t=Number(e??0);return Number.isFinite(t)?String(t):"0"}o(p,"count");function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}o(m,"record");function l(e){return e==null||e===""?"\u2014":String(e)}o(l,"value");function _(...e){return e.map(l).filter(t=>t!=="\u2014").join(" \xB7 ")||"\u2014"}o(_,"join");export{u as ICON,j as ago,A as commandCell,N as compactCount,M as elapsed,C as jobElapsed,S as jobElapsedMs,L as jobLabel,F as jobTone,E as overviewGroups,m as record,T as relativeTime,D as scheduledItems,d as shortPath,w as statusVisual,l as value};
package/dist/core/io.js CHANGED
@@ -1,7 +1,7 @@
1
- var S=Object.defineProperty;var n=(e,t)=>S(e,"name",{value:t,configurable:!0});import{appendFileSync as w,statSync as E}from"node:fs";import{CrtrError as a}from"./errors.js";import{ExitCode as c}from"../types.js";import{PREVIEW_RESULT_PATH_ENV as m}from"./preview-result-path.js";import{renderError as b}from"./render.js";import{ApiError as T}from"../api/index.js";let f=!1,i;const _=256*1024;function W(e){const t=process.env[m];i=t===void 0||t===""?void 0:{path:e,jsonl:[]}}n(W,"beginPreview");function d(e){const t=process.env[m];if(t===void 0||t==="")return;const s=`${JSON.stringify({path:i?.path??"",...e})}
2
- `;try{if((E(t,{throwIfNoEntry:!1})?.size??0)+Buffer.byteLength(s,"utf8")>_)return;w(t,s,"utf8")}catch{}}n(d,"publishPreview");function $(e){i!==void 0&&(e!=null?d({result:e}):(i.jsonl.length>0||i.error!==void 0)&&d({...i.jsonl.length>0?{jsonl:i.jsonl}:{},...i.error===void 0?{}:{error:i.error}}))}n($,"publishPreviewResult");function y(e){i?.jsonl.push(e)}n(y,"recordPreviewLine");function B(e){try{const t=JSON.parse(e);t!==null&&typeof t=="object"&&!Array.isArray(t)&&y(t)}catch{}}n(B,"recordPreviewJsonLine");function F(e){i!==void 0&&(i.error=e)}n(F,"recordPreviewError");function G(e){f=e}n(G,"setJsonOutput");function q(){return f}n(q,"isJsonOutput");class h extends a{static{n(this,"InputError")}payload;constructor(t,s=c.USAGE){super(t.error,t.message,s,{...t}),this.name="InputError",this.payload=t}}async function D(){if(process.stdin.isTTY)return"";const e=[];for await(const t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}n(D,"readStdinRaw");async function K(e=200){return process.stdin.isTTY?"":await new Promise(t=>{const s=[];let o=!1;const r=n(()=>{o||(o=!0,clearTimeout(g),process.stdin.removeListener("data",u),process.stdin.removeListener("end",p),process.stdin.removeListener("error",l),process.stdin.pause(),t(Buffer.concat(s).toString("utf8")))},"finish"),u=n(x=>s.push(x),"onData"),p=n(()=>r(),"onEnd"),l=n(()=>r(),"onError"),g=setTimeout(r,e);process.stdin.on("data",u),process.stdin.on("end",p),process.stdin.on("error",l),process.stdin.resume()})}n(K,"peekStdinRaw");function V(e){process.stdout.write(JSON.stringify(e,null,2)+`
1
+ var x=Object.defineProperty;var n=(e,t)=>x(e,"name",{value:t,configurable:!0});import{appendFileSync as w,statSync as E}from"node:fs";import{CrtrError as a}from"./errors.js";import{ExitCode as c}from"../types.js";import{PREVIEW_RESULT_PATH_ENV as m}from"./preview-result-path.js";import{renderError as b}from"./render.js";import{ApiError as T}from"../api/index.js";let d=!1,u;const _=256*1024;function k(e){const t=process.env[m];u=t===void 0||t===""?void 0:{path:e,jsonl:[]}}n(k,"beginPreview");function f(e){const t=process.env[m];if(t===void 0||t==="")return;const s=`${JSON.stringify({path:u?.path??"",...e})}
2
+ `;try{if((E(t,{throwIfNoEntry:!1})?.size??0)+Buffer.byteLength(s,"utf8")>_)return;w(t,s,"utf8")}catch{}}n(f,"publishPreview");function W(e){u!==void 0&&(e!=null?f({result:e}):(u.jsonl.length>0||u.error!==void 0)&&f({...u.jsonl.length>0?{jsonl:u.jsonl}:{},...u.error===void 0?{}:{error:u.error}}))}n(W,"publishPreviewResult");function y(e){u?.jsonl.push(e)}n(y,"recordPreviewLine");function B(e){try{const t=JSON.parse(e);t!==null&&typeof t=="object"&&!Array.isArray(t)&&y(t)}catch{}}n(B,"recordPreviewJsonLine");function F(e){u!==void 0&&(u.error=e)}n(F,"recordPreviewError");function G(e){d=e}n(G,"setJsonOutput");function q(){return d}n(q,"isJsonOutput");class h extends a{static{n(this,"InputError")}payload;constructor(t,s=c.USAGE){super(t.error,t.message,s,{...t}),this.name="InputError",this.payload=t}}async function D(){if(process.stdin.isTTY)return"";const e=[];for await(const t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}n(D,"readStdinRaw");async function K(e=200){return process.stdin.isTTY?"":await new Promise(t=>{const s=[];let o=!1;const r=n(()=>{o||(o=!0,clearTimeout(g),process.stdin.removeListener("data",i),process.stdin.removeListener("end",p),process.stdin.removeListener("error",l),process.stdin.pause(),t(Buffer.concat(s).toString("utf8")))},"finish"),i=n(S=>s.push(S),"onData"),p=n(()=>r(),"onEnd"),l=n(()=>r(),"onError"),g=setTimeout(r,e);process.stdin.on("data",i),process.stdin.on("end",p),process.stdin.on("error",l),process.stdin.resume()})}n(K,"peekStdinRaw");function V(e){process.stdout.write(JSON.stringify(e,null,2)+`
3
3
  `)}n(V,"emit");function Y(e){y(e),process.stdout.write(JSON.stringify(e)+`
4
- `)}n(Y,"emitLine");function M(e){return new Promise(t=>{let s=!1;const o=n(u=>{u.code==="EPIPE"&&r(!1)},"onErr"),r=n(u=>{s||(s=!0,process.stdout.off("error",o),t(u))},"finish");process.stdout.on("error",o);try{process.stdout.write(e,u=>r(u==null))}catch{r(!1)}})}n(M,"writeStdout");function z(e){process.stderr.write(e+`
5
- `)}n(z,"diag");function O(e){if(e instanceof h)return e.payload;const t=e.details!==void 0?e.details:{},s=t.primaryCompleted===!0&&t.result!==null&&typeof t.result=="object"&&!Array.isArray(t.result)?N(t.result):void 0,o=t.next!==void 0?t.next:"Inspect the error and adjust the call. See -h for the schema.",r={error:e.code,message:e.message,received:t.received,field:t.field,...typeof t.http_status=="number"?{http_status:t.http_status}:{}};return s===void 0?{...r,next:o}:{...r,primaryCompleted:!0,result:s,next:o}}n(O,"payloadOf");function N(e){const t=new WeakSet;try{const s=JSON.stringify(e,(o,r)=>{if(typeof r=="bigint")return{$crtrType:"bigint",value:r.toString()};if(typeof r=="number"&&!Number.isFinite(r))return{$crtrType:"number",value:String(r)};if(typeof r>"u"||typeof r=="function"||typeof r=="symbol")return{$crtrType:typeof r};if(r!==null&&typeof r=="object"){if(t.has(r))return{$crtrType:"circular"};t.add(r)}return r});if(s!==void 0){const o=JSON.parse(s);if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}return{$crtrType:"unavailable",message:"The completed primary result could not be represented as JSON."}}n(N,"jsonSafeResult");const P={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable",503:"daemon_unavailable"};function R(e,t){if(e.code==="daemon_restarting")return new a("daemon_restarting",e.message,c.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(e.code==="layout_migration_required")return new a("layout_migration_required",e.message,c.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(e.status===503||e.code==="daemon_unavailable")return new a("daemon_unavailable",e.message,c.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});const s=e.details,o=s&&typeof s.error=="string"&&typeof s.message=="string"&&typeof s.next=="string"?s:{error:P[e.status]??e.code,message:e.message,next:t??(e.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":e.status===404?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new h(o,A(o.error,e.status))}n(R,"apiErrorToCliError");function A(e,t){return e==="not_found"||t===404?c.NOT_FOUND:e==="ambiguous"?c.AMBIGUOUS:c.USAGE}n(A,"exitForCliCode");function j(e){if(e instanceof T){j(R(e));return}if(e instanceof a){const o=O(e);i!==void 0&&d({error:o});const r=f?JSON.stringify(o,null,2):b(o);process.stdout.write(r+`
4
+ `)}n(Y,"emitLine");function M(e){return new Promise(t=>{let s=!1;const o=n(i=>{i.code==="EPIPE"&&r(!1)},"onErr"),r=n(i=>{s||(s=!0,process.stdout.off("error",o),t(i))},"finish");process.stdout.on("error",o);try{process.stdout.write(e,i=>r(i==null))}catch{r(!1)}})}n(M,"writeStdout");function z(e){process.stderr.write(e+`
5
+ `)}n(z,"diag");function O(e){if(e instanceof h)return e.payload;const t=e.details!==void 0?e.details:{},s=t.primaryCompleted===!0&&t.result!==null&&typeof t.result=="object"&&!Array.isArray(t.result)?N(t.result):void 0,o=t.next!==void 0?t.next:"Inspect the error and adjust the call. See -h for the schema.",r={error:e.code,message:e.message,received:t.received,field:t.field,...typeof t.http_status=="number"?{http_status:t.http_status}:{}};return s===void 0?{...r,next:o}:{...r,primaryCompleted:!0,result:s,next:o}}n(O,"payloadOf");function N(e){const t=new WeakSet;try{const s=JSON.stringify(e,(o,r)=>{if(typeof r=="bigint")return{$crtrType:"bigint",value:r.toString()};if(typeof r=="number"&&!Number.isFinite(r))return{$crtrType:"number",value:String(r)};if(typeof r>"u"||typeof r=="function"||typeof r=="symbol")return{$crtrType:typeof r};if(r!==null&&typeof r=="object"){if(t.has(r))return{$crtrType:"circular"};t.add(r)}return r});if(s!==void 0){const o=JSON.parse(s);if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}return{$crtrType:"unavailable",message:"The completed primary result could not be represented as JSON."}}n(N,"jsonSafeResult");const A={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable",503:"daemon_unavailable"};function P(e,t){if(e.code==="daemon_restarting")return new a("daemon_restarting",e.message,c.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(e.code==="layout_migration_required")return new a("layout_migration_required",e.message,c.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(e.status===503||e.code==="daemon_unavailable")return new a("daemon_unavailable",e.message,c.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});const s=e.details,o=Array.isArray(s?.violations)?s.violations.map(i=>`${String(i.field)} ${String(i.problem)}${i.received!==void 0?` (received ${JSON.stringify(i.received)})`:""}`):[],r=s&&typeof s.error=="string"&&typeof s.message=="string"&&typeof s.next=="string"?s:{error:A[e.status]??e.code,message:o.length>0?`${e.message}: ${o.join("; ")}`:e.message,next:t??(e.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":e.status===404?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new h(r,R(r.error,e.status))}n(P,"apiErrorToCliError");function R(e,t){return e==="not_found"||t===404?c.NOT_FOUND:e==="ambiguous"?c.AMBIGUOUS:c.USAGE}n(R,"exitForCliCode");function j(e){if(e instanceof T){j(P(e));return}if(e instanceof a){const o=O(e);u!==void 0&&f({error:o});const r=d?JSON.stringify(o,null,2):b(o);process.stdout.write(r+`
6
6
  `),process.exitCode=e.exitCode;return}const t=e,s=t!=null&&typeof t.message=="string"?t.message:String(e);process.stderr.write(JSON.stringify({error:"internal",message:s,next:"This is a crtr bug, not a bad call. Retry; if it persists, report it."},null,2)+`
7
- `),process.exitCode=c.GENERAL}n(j,"handle");export{h as InputError,_ as PREVIEW_RESULT_MAX_BYTES,R as apiErrorToCliError,W as beginPreview,z as diag,V as emit,Y as emitLine,j as handle,q as isJsonOutput,K as peekStdinRaw,$ as publishPreviewResult,D as readStdinRaw,F as recordPreviewError,B as recordPreviewJsonLine,y as recordPreviewLine,G as setJsonOutput,M as writeStdout};
7
+ `),process.exitCode=c.GENERAL}n(j,"handle");export{h as InputError,_ as PREVIEW_RESULT_MAX_BYTES,P as apiErrorToCliError,k as beginPreview,z as diag,V as emit,Y as emitLine,j as handle,q as isJsonOutput,K as peekStdinRaw,W as publishPreviewResult,D as readStdinRaw,F as recordPreviewError,B as recordPreviewJsonLine,y as recordPreviewLine,G as setJsonOutput,M as writeStdout};
@@ -5,11 +5,34 @@ export interface LayoutMigration {
5
5
  moved: number;
6
6
  /** Exactly the filesystem operations that changed a source path. */
7
7
  changes: string[];
8
+ /** One line per leftover the migration resolved itself (a dry run lists what it would do). */
9
+ resolutions: string[];
10
+ /** Old stored path prefix → new path, rewritten as text in migrated markdown bodies. */
11
+ bodyPaths: Array<[string, string]>;
8
12
  /** Credential sources that did not exist; legitimate when the old volume never held one. */
9
13
  absentCredentials: string[];
14
+ dryRun: boolean;
10
15
  }
16
+ export declare function isJunkFile(name: string): boolean;
17
+ /** Where a leftover the new layout has no place for is kept: `runtime/set-aside/<kind>/<name>`, never overwriting. */
18
+ export declare function setAsidePath(migration: LayoutMigration, kind: string, name: string): string;
19
+ /** Move a leftover aside (a rename; never a copy). */
20
+ export declare function setAside(from: string, kind: string, migration: LayoutMigration, name?: string): string;
21
+ /**
22
+ * What to do with a destination that already exists before a move. A file is
23
+ * renamed atomically, so a file present at both paths was never written by
24
+ * this migration: an identical copy drops the source, an empty file is
25
+ * removed, and anything else is kept aside under `runtime/set-aside/replaced/`.
26
+ */
27
+ export type Claim = {
28
+ action: 'merge' | 'drop-source' | 'remove-destination' | 'set-aside-destination';
29
+ line?: string;
30
+ };
31
+ export declare function claim(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): Claim;
11
32
  /** Rename within the volume; merge an existing directory on interrupted runs, never overwrite a file. */
12
- export declare function movePath(from: string, to: string, migration: LayoutMigration): void;
33
+ export declare function movePath(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): void;
34
+ /** Dry-run lines for a move: the claims the real run would make, without touching anything. */
35
+ export declare function previewMove(from: string, to: string, migration: LayoutMigration, wholeDirectory?: boolean): void;
13
36
  export declare function sameFile(from: string, to: string): boolean;
14
37
  export declare function daemonAnswers(socketPath: string): Promise<boolean>;
15
38
  export declare function migrateLayout(dryRun: boolean): Promise<LayoutMigration | null>;