@mostra/runtime 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/dist/bin.js +4178 -310
  2. package/dist/bin.js.map +1 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/{instance-FExcyENK.js → instance-CBUlOmzG.js} +1892 -85
  6. package/dist/instance-CBUlOmzG.js.map +1 -0
  7. package/dist/reference/cli.md +1432 -0
  8. package/dist/reference/diagnostics.json +1579 -0
  9. package/dist/reference/errors/MOSTRA_A11Y_MINOR.md +23 -0
  10. package/dist/reference/errors/MOSTRA_A11Y_SERIOUS.md +23 -0
  11. package/dist/reference/errors/MOSTRA_ACTION_CANCELLED.md +23 -0
  12. package/dist/reference/errors/MOSTRA_ACTION_EVENT_INVALID.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ACTION_EXPORT_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_ACTION_INTERRUPTED.md +23 -0
  15. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  16. package/dist/reference/errors/MOSTRA_ACTION_RUN_NOT_FOUND.md +23 -0
  17. package/dist/reference/errors/MOSTRA_ACTION_THREW.md +23 -0
  18. package/dist/reference/errors/MOSTRA_ACTION_TOO_LARGE.md +23 -0
  19. package/dist/reference/errors/MOSTRA_ACTION_UNKNOWN_FUNCTION.md +23 -0
  20. package/dist/reference/errors/MOSTRA_ACTION_UNSERIALIZABLE.md +23 -0
  21. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_ARTIFACT_DIR_NOT_EMPTY.md +23 -0
  23. package/dist/reference/errors/MOSTRA_ARTIFACT_ENTRY_AMBIGUOUS.md +23 -0
  24. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  25. package/dist/reference/errors/MOSTRA_ARTIFACT_NOT_FOUND.md +23 -0
  26. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_ENTRY.md +23 -0
  27. package/dist/reference/errors/MOSTRA_ARTIFACT_NO_PAGE.md +23 -0
  28. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  29. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  30. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_MISSING.md +23 -0
  31. package/dist/reference/errors/MOSTRA_ARTIFACT_SOURCE_UNREADABLE.md +23 -0
  32. package/dist/reference/errors/MOSTRA_ARTIFACT_TEMPLATE_UNKNOWN.md +23 -0
  33. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_COLLECTED.md +23 -0
  34. package/dist/reference/errors/MOSTRA_ARTIFACT_VERSION_NOT_FOUND.md +23 -0
  35. package/dist/reference/errors/MOSTRA_BUILD_CRASHED.md +23 -0
  36. package/dist/reference/errors/MOSTRA_BUILD_FAILED.md +23 -0
  37. package/dist/reference/errors/MOSTRA_BUILD_TIMEOUT.md +23 -0
  38. package/dist/reference/errors/MOSTRA_BUILD_UNRESOLVED.md +23 -0
  39. package/dist/reference/errors/MOSTRA_CLI_CONFIG_UNWRITABLE.md +23 -0
  40. package/dist/reference/errors/MOSTRA_CLI_UNKNOWN_COMMAND.md +23 -0
  41. package/dist/reference/errors/MOSTRA_CLI_USAGE.md +23 -0
  42. package/dist/reference/errors/MOSTRA_CONSOLE_ERROR.md +23 -0
  43. package/dist/reference/errors/MOSTRA_CONSOLE_WARNING.md +23 -0
  44. package/dist/reference/errors/MOSTRA_DEP_INSTALL_FAILED.md +23 -0
  45. package/dist/reference/errors/MOSTRA_DEP_MISSING.md +23 -0
  46. package/dist/reference/errors/MOSTRA_DEP_NOT_FOUND.md +23 -0
  47. package/dist/reference/errors/MOSTRA_DEP_OFFLINE.md +23 -0
  48. package/dist/reference/errors/MOSTRA_DEP_SPEC_INVALID.md +23 -0
  49. package/dist/reference/errors/MOSTRA_DEP_TIMEOUT.md +23 -0
  50. package/dist/reference/errors/MOSTRA_DEP_WARM_CONFLICT.md +23 -0
  51. package/dist/reference/errors/MOSTRA_ENV_BIND_FAILED.md +23 -0
  52. package/dist/reference/errors/MOSTRA_ENV_BROWSER_MISSING.md +23 -0
  53. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_DOWNLOAD_FAILED.md +23 -0
  54. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_INVALID.md +23 -0
  55. package/dist/reference/errors/MOSTRA_ENV_BUNDLE_UNAVAILABLE.md +23 -0
  56. package/dist/reference/errors/MOSTRA_ENV_HELPER_MISSING.md +23 -0
  57. package/dist/reference/errors/MOSTRA_ENV_NODE_UNSUPPORTED.md +23 -0
  58. package/dist/reference/errors/MOSTRA_ENV_PORT_TAKEN.md +23 -0
  59. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  60. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_MISSING.md +23 -0
  61. package/dist/reference/errors/MOSTRA_ENV_SERVICE_FAILED.md +23 -0
  62. package/dist/reference/errors/MOSTRA_ENV_SHELL_MISSING.md +23 -0
  63. package/dist/reference/errors/MOSTRA_ENV_WARM_MISSING.md +23 -0
  64. package/dist/reference/errors/MOSTRA_FIELD_CONFLICT.md +23 -0
  65. package/dist/reference/errors/MOSTRA_FIELD_DUPLICATE_ID.md +23 -0
  66. package/dist/reference/errors/MOSTRA_FIELD_ID_INVALID.md +23 -0
  67. package/dist/reference/errors/MOSTRA_FIELD_ID_UNSTABLE.md +23 -0
  68. package/dist/reference/errors/MOSTRA_FIELD_MUTATION_ID_REUSED.md +23 -0
  69. package/dist/reference/errors/MOSTRA_FIELD_SHARED.md +23 -0
  70. package/dist/reference/errors/MOSTRA_FIELD_TOO_LARGE.md +23 -0
  71. package/dist/reference/errors/MOSTRA_FIELD_UNBOUND.md +23 -0
  72. package/dist/reference/errors/MOSTRA_HOME_DISK_FULL.md +23 -0
  73. package/dist/reference/errors/MOSTRA_HOME_GC_INCOMPLETE.md +23 -0
  74. package/dist/reference/errors/MOSTRA_HOME_GONE.md +23 -0
  75. package/dist/reference/errors/MOSTRA_HOME_INTEGRITY.md +23 -0
  76. package/dist/reference/errors/MOSTRA_HOME_LEDGER_UNREADABLE.md +23 -0
  77. package/dist/reference/errors/MOSTRA_HOME_LOCKED.md +23 -0
  78. package/dist/reference/errors/MOSTRA_HOME_MISMATCH.md +23 -0
  79. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  80. package/dist/reference/errors/MOSTRA_HOME_NOT_ALWAYS_ON.md +23 -0
  81. package/dist/reference/errors/MOSTRA_HOME_NOT_OWNED.md +23 -0
  82. package/dist/reference/errors/MOSTRA_HOME_SOCKET_TOO_LONG.md +23 -0
  83. package/dist/reference/errors/MOSTRA_HOME_TOO_NEW.md +23 -0
  84. package/dist/reference/errors/MOSTRA_HOST_CONNECTION_CLOSED.md +23 -0
  85. package/dist/reference/errors/MOSTRA_HOST_CURSOR_COMPACTED.md +23 -0
  86. package/dist/reference/errors/MOSTRA_HOST_IDENTITY_UNAVAILABLE.md +23 -0
  87. package/dist/reference/errors/MOSTRA_HOST_INITIALIZE_ORDER.md +23 -0
  88. package/dist/reference/errors/MOSTRA_HOST_INTERNAL_ERROR.md +23 -0
  89. package/dist/reference/errors/MOSTRA_HOST_INVALID_PARAMS.md +23 -0
  90. package/dist/reference/errors/MOSTRA_HOST_MALFORMED.md +23 -0
  91. package/dist/reference/errors/MOSTRA_HOST_MESSAGE_TOO_LARGE.md +23 -0
  92. package/dist/reference/errors/MOSTRA_HOST_METHOD_UNKNOWN.md +23 -0
  93. package/dist/reference/errors/MOSTRA_HOST_NOTIFICATION_UNSUPPORTED.md +23 -0
  94. package/dist/reference/errors/MOSTRA_HOST_PORT_UNSUPPORTED.md +23 -0
  95. package/dist/reference/errors/MOSTRA_HOST_REQUEST_ID_REUSED.md +23 -0
  96. package/dist/reference/errors/MOSTRA_HOST_REVISION_UNSUPPORTED.md +23 -0
  97. package/dist/reference/errors/MOSTRA_HOST_SHUTDOWN_REFUSED.md +23 -0
  98. package/dist/reference/errors/MOSTRA_HOST_SUBSCRIPTION_UNKNOWN.md +23 -0
  99. package/dist/reference/errors/MOSTRA_HOST_TIMEOUT.md +23 -0
  100. package/dist/reference/errors/MOSTRA_HYGIENE_CONTENT_TYPE.md +23 -0
  101. package/dist/reference/errors/MOSTRA_HYGIENE_CSRF_MISSING.md +23 -0
  102. package/dist/reference/errors/MOSTRA_HYGIENE_FRAME_SESSION.md +23 -0
  103. package/dist/reference/errors/MOSTRA_HYGIENE_HEADERS_TOO_LARGE.md +23 -0
  104. package/dist/reference/errors/MOSTRA_HYGIENE_HOST_REFUSED.md +23 -0
  105. package/dist/reference/errors/MOSTRA_HYGIENE_NOT_SERVED.md +23 -0
  106. package/dist/reference/errors/MOSTRA_HYGIENE_ORIGIN_REFUSED.md +23 -0
  107. package/dist/reference/errors/MOSTRA_HYGIENE_RATE_LIMITED.md +23 -0
  108. package/dist/reference/errors/MOSTRA_HYGIENE_REQUEST_MALFORMED.md +23 -0
  109. package/dist/reference/errors/MOSTRA_HYGIENE_SCOPE_DENIED.md +23 -0
  110. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_CONFLICT.md +23 -0
  111. package/dist/reference/errors/MOSTRA_HYGIENE_SESSION_MISSING.md +23 -0
  112. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_INVALID.md +23 -0
  113. package/dist/reference/errors/MOSTRA_HYGIENE_TOKEN_REVOKED.md +23 -0
  114. package/dist/reference/errors/MOSTRA_LIVE_SOURCE_FAILED.md +23 -0
  115. package/dist/reference/errors/MOSTRA_LIVE_TOO_LARGE.md +23 -0
  116. package/dist/reference/errors/MOSTRA_MANIFEST_INVALID.md +23 -0
  117. package/dist/reference/errors/MOSTRA_MANIFEST_NOT_LITERAL.md +23 -0
  118. package/dist/reference/errors/MOSTRA_MANIFEST_UNKNOWN_KEY.md +23 -0
  119. package/dist/reference/errors/MOSTRA_NETWORK_EXTERNAL_FAILED.md +23 -0
  120. package/dist/reference/errors/MOSTRA_NETWORK_REQUEST_FAILED.md +23 -0
  121. package/dist/reference/errors/MOSTRA_PLATFORM_UNSUPPORTED.md +23 -0
  122. package/dist/reference/errors/MOSTRA_PUBLISH_ID_CONFLICT.md +23 -0
  123. package/dist/reference/errors/MOSTRA_PUBLISH_SOURCE_CHANGED.md +23 -0
  124. package/dist/reference/errors/MOSTRA_PUBLISH_VERIFY_FAILED.md +23 -0
  125. package/dist/reference/errors/MOSTRA_REGRESSION_ACTION_REMOVED.md +23 -0
  126. package/dist/reference/errors/MOSTRA_REGRESSION_ARIA.md +23 -0
  127. package/dist/reference/errors/MOSTRA_REGRESSION_FIELD_REMOVED.md +23 -0
  128. package/dist/reference/errors/MOSTRA_REGRESSION_LIVE_REMOVED.md +23 -0
  129. package/dist/reference/errors/MOSTRA_REGRESSION_PAGE_REMOVED.md +23 -0
  130. package/dist/reference/errors/MOSTRA_REGRESSION_PIXELS.md +23 -0
  131. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  132. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  133. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  134. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  135. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  136. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  137. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  138. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  139. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  140. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  141. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  142. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  143. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  144. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  145. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  146. package/dist/reference/errors/MOSTRA_RUNTIME_BLANK.md +23 -0
  147. package/dist/reference/errors/MOSTRA_RUNTIME_NOT_READY.md +23 -0
  148. package/dist/reference/errors/MOSTRA_RUNTIME_PAGE_ERROR.md +23 -0
  149. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_CRASHED.md +23 -0
  150. package/dist/reference/errors/MOSTRA_RUNTIME_WORKER_PARKED.md +23 -0
  151. package/dist/reference/errors/MOSTRA_SECRET_MISSING.md +23 -0
  152. package/dist/reference/errors/MOSTRA_SHARE_NOT_ENABLED.md +23 -0
  153. package/dist/reference/errors/MOSTRA_SHARE_NOT_FOUND.md +23 -0
  154. package/dist/reference/errors/MOSTRA_SHARE_PORTS_EXHAUSTED.md +23 -0
  155. package/dist/reference/errors/MOSTRA_SHARE_TOOL_MISSING.md +23 -0
  156. package/dist/reference/errors/MOSTRA_SHARE_TOOL_NOT_READY.md +23 -0
  157. package/dist/reference/errors/MOSTRA_SHARE_TTL_INVALID.md +23 -0
  158. package/dist/reference/errors/MOSTRA_SHARE_TUNNEL_FAILED.md +23 -0
  159. package/dist/reference/errors/MOSTRA_SMOKE_BUDGET.md +23 -0
  160. package/dist/reference/errors/MOSTRA_SMOKE_NO_EFFECT.md +23 -0
  161. package/dist/reference/errors/MOSTRA_SUBMIT_ALREADY.md +23 -0
  162. package/dist/reference/errors/MOSTRA_SUBMIT_BLOCKED.md +23 -0
  163. package/dist/reference/errors/MOSTRA_SUBMIT_CHANNEL_DENIED.md +23 -0
  164. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +23 -0
  165. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  166. package/dist/reference/errors/MOSTRA_SUBMIT_POLICY_NONE.md +23 -0
  167. package/dist/reference/errors/MOSTRA_SUBMIT_REVISION_MOVED.md +23 -0
  168. package/dist/reference/errors/MOSTRA_SUBMIT_SIGNAL_INVALID.md +23 -0
  169. package/dist/reference/errors/MOSTRA_SUBMIT_VIEW_INVALID.md +23 -0
  170. package/dist/reference/errors/MOSTRA_TARGET_UNAVAILABLE.md +23 -0
  171. package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
  172. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
  173. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
  174. package/dist/reference/errors/MOSTRA_TYPE_ERROR.md +23 -0
  175. package/dist/reference/errors/MOSTRA_TYPE_UNTYPED_PACKAGE.md +23 -0
  176. package/dist/reference/errors/MOSTRA_VERIFY_ACTION_SKIPPED.md +23 -0
  177. package/dist/reference/errors/MOSTRA_VERIFY_BASELINE_MISSING.md +23 -0
  178. package/dist/reference/errors/MOSTRA_VERIFY_CRASHED.md +23 -0
  179. package/dist/reference/errors/MOSTRA_VERIFY_LIVE_FAILED.md +23 -0
  180. package/dist/reference/errors/MOSTRA_VERIFY_NO_BASELINE.md +23 -0
  181. package/dist/reference/errors/MOSTRA_VERIFY_SECRET_MISSING.md +23 -0
  182. package/dist/reference/errors/MOSTRA_VERIFY_SKIP_CONSEQUENCE.md +23 -0
  183. package/dist/reference/errors/MOSTRA_VERIFY_TIMEOUT.md +23 -0
  184. package/dist/reference/self-hosting.md +130 -0
  185. package/dist/reference/telemetry.md +84 -0
  186. package/dist/skill/SKILL.md +124 -0
  187. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  188. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  189. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  190. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  191. package/dist/skill/assets/examples/decision/styles.css +125 -0
  192. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  193. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  194. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  195. package/dist/skill/assets/studio.css +125 -0
  196. package/dist/skill/references/answers.md +219 -0
  197. package/dist/skill/references/design.md +154 -0
  198. package/dist/skill/references/libraries.md +167 -0
  199. package/dist/skill/references/long-lived.md +148 -0
  200. package/dist/skill/references/mcp.md +68 -0
  201. package/dist/skill/references/page.md +131 -0
  202. package/dist/skill/references/server.md +146 -0
  203. package/dist/skill/references/sharing.md +123 -0
  204. package/dist/skill/references/teams.md +78 -0
  205. package/dist/skill/references/verify.md +71 -0
  206. package/package.json +10 -5
  207. package/src/gateway/actions.ts +20 -0
  208. package/src/gateway/browser.ts +128 -1
  209. package/src/gateway/capabilities.ts +8 -0
  210. package/src/gateway/http.ts +12 -1
  211. package/src/gateway/index.ts +210 -6
  212. package/src/gateway/listener.ts +31 -6
  213. package/src/gateway/routes.ts +8 -0
  214. package/src/gateway/team.ts +181 -0
  215. package/src/gc/index.ts +5 -0
  216. package/src/instance/index.ts +22 -2
  217. package/src/interaction/ephemeral.ts +21 -0
  218. package/src/interaction/events.ts +17 -0
  219. package/src/interaction/index.ts +325 -20
  220. package/src/interaction/pause.ts +106 -0
  221. package/src/interaction/roster.ts +585 -0
  222. package/src/interaction/submissions.ts +42 -1
  223. package/src/interaction/team.ts +426 -0
  224. package/src/interaction/viewers.ts +34 -1
  225. package/src/interaction/wait.ts +150 -0
  226. package/src/ledger/index.ts +20 -1
  227. package/src/ledger/migrations.ts +86 -0
  228. package/src/link/author.ts +215 -0
  229. package/src/link/hosted.ts +51 -4
  230. package/src/link/http.ts +6 -1
  231. package/src/link/index.ts +3 -1
  232. package/src/link/manager.ts +169 -35
  233. package/src/protocol-server/client.ts +53 -0
  234. package/src/protocol-server/index.ts +1 -1
  235. package/src/server/api.ts +514 -72
  236. package/src/server/auth.ts +600 -74
  237. package/src/server/authorize.ts +816 -0
  238. package/src/server/clients.ts +235 -0
  239. package/src/server/config.ts +7 -0
  240. package/src/server/data.ts +59 -1
  241. package/src/server/directory.ts +91 -0
  242. package/src/server/feed.ts +277 -0
  243. package/src/server/handle.ts +172 -0
  244. package/src/server/hosted-pages.ts +532 -0
  245. package/src/server/hosted.ts +551 -18
  246. package/src/server/index.ts +353 -61
  247. package/src/server/mcp.ts +330 -0
  248. package/src/server/metering.ts +156 -0
  249. package/src/server/oauth-clients.ts +510 -0
  250. package/src/server/operator.ts +557 -0
  251. package/src/server/providers.ts +284 -0
  252. package/src/server/remove.ts +148 -0
  253. package/src/server/routing.ts +275 -0
  254. package/src/share/index.ts +50 -2
  255. package/src/verify/index.ts +7 -0
  256. package/src/verify/runner.ts +27 -2
  257. package/dist/instance-FExcyENK.js.map +0 -1
@@ -0,0 +1,426 @@
1
+ /**
2
+ * Team traffic to pages (D168; CO-03, CO-04, CO-07): each view's roster as it may see it, and who
3
+ * is present with the cursors and selections they share. Nothing here is stored (D47): presence
4
+ * lives in this process's memory under short leases, and both reach pages only as ephemeral
5
+ * messages on their streams and polls, each view's under the artifact's visibility policy.
6
+ *
7
+ * - **Respondents.** A view that reads its roster (`respondents`) follows it for a minute; when the
8
+ * interaction core says an artifact's respondents may have changed, every following view is sent
9
+ * its roster again, at most every {@link RESPONDENTS_SETTLE_MS} per artifact, and only when it
10
+ * differs from what that view last got.
11
+ * - **Presence.** A view that posts presence is present for {@link PRESENCE_LEASE_MS}; what it
12
+ * shares replaces what it shared before. Each view may post {@link PRESENCE_RATE} updates a second
13
+ * (more is refused, `MOSTRA_TEAM_PRESENCE_RATE_LIMITED`), and an artifact's present views are sent
14
+ * who is present at most every {@link PRESENCE_FANOUT_MS}, so many fast cursors cost each reader a
15
+ * bounded rate of messages.
16
+ */
17
+ import type {
18
+ PresencePeer,
19
+ PresenceRequest,
20
+ PresenceState,
21
+ RosterForPage,
22
+ TeamVisibility,
23
+ } from "@mostra/protocol";
24
+ import type { EphemeralBus } from "./ephemeral.ts";
25
+ import type { RosterViewer } from "./roster.ts";
26
+
27
+ /** How long a page stays present without posting again; pages post every 10 s. */
28
+ export const PRESENCE_LEASE_MS = 30_000;
29
+
30
+ /** The most presence updates one view may post in a second (a burst of as many). */
31
+ export const PRESENCE_RATE = 20;
32
+
33
+ /** The shortest time between two presence messages to one artifact's pages. */
34
+ export const PRESENCE_FANOUT_MS = 50;
35
+
36
+ /** How long a view follows its roster after it read it; pages read again every 20 s. */
37
+ export const RESPONDENTS_LEASE_MS = 60_000;
38
+
39
+ /** The shortest time between two roster messages to one artifact's pages. */
40
+ export const RESPONDENTS_SETTLE_MS = 100;
41
+
42
+ /** The most present viewers a page is told of by name; more are counted. */
43
+ export const PRESENCE_PEERS_MAX = 200;
44
+
45
+ /** What team traffic reads of the interaction core. */
46
+ export interface TeamSource {
47
+ visibility(artifactId: string): TeamVisibility;
48
+ isOwner(viewerId: string): boolean;
49
+ peer(artifactId: string, viewerId: string): { readonly key: string } & RosterViewer;
50
+ rosterForPage(page: { readonly artifactId: string; readonly viewerId: string }): RosterForPage;
51
+ rostersForPages(artifactId: string, viewerIds: readonly string[]): RosterForPage[];
52
+ onTeam(listener: (artifactId: string) => void): () => void;
53
+ }
54
+
55
+ /** One view's presence. */
56
+ interface Present {
57
+ readonly artifactId: string;
58
+ readonly viewId: string;
59
+ readonly viewerId: string;
60
+ cursor?: { readonly x: number; readonly y: number };
61
+ selection?: { readonly element?: string; readonly start?: number; readonly end?: number };
62
+ at: number;
63
+ until: number;
64
+ /** The presence this view last got, so it hears only a change of what it may see. */
65
+ last?: string;
66
+ }
67
+
68
+ /**
69
+ * A view's token bucket: the posts it may still make now. It outlives the view's presence (a
70
+ * leave keeps it), so leaving and joining again never refills it; it goes once unused for a lease.
71
+ */
72
+ interface Bucket {
73
+ tokens: number;
74
+ refilled: number;
75
+ /** The highest `seq` the view posted with, so an older post that arrives later changes nothing. */
76
+ seq?: number;
77
+ }
78
+
79
+ /** A view that follows its roster. */
80
+ interface Following {
81
+ readonly artifactId: string;
82
+ readonly viewerId: string;
83
+ until: number;
84
+ last?: string;
85
+ }
86
+
87
+ /** The answer to a presence post: the state, or how long to wait. */
88
+ export type PresenceAnswer =
89
+ | { readonly state: PresenceState }
90
+ | { readonly limited: true; readonly retryAfterMs: number };
91
+
92
+ /** Team traffic for one gateway. */
93
+ export interface TeamTraffic {
94
+ /** A view's presence post (CO-04): joins, shares, or leaves. */
95
+ presence(
96
+ page: { readonly artifactId: string; readonly viewerId: string },
97
+ request: PresenceRequest,
98
+ ): PresenceAnswer;
99
+ /** A view reads its roster (CO-03) and follows it for a minute. */
100
+ respondents(
101
+ page: { readonly artifactId: string; readonly viewerId: string },
102
+ viewId: string,
103
+ ): RosterForPage;
104
+ /** How many views are present now, across artifacts. */
105
+ presentCount(): number;
106
+ /** Stops the timers. */
107
+ close(): void;
108
+ }
109
+
110
+ /** Creates team traffic over a bus. */
111
+ export function createTeamTraffic(options: {
112
+ readonly bus: EphemeralBus;
113
+ readonly source: TeamSource;
114
+ readonly now?: () => number;
115
+ readonly log?: { error(event: string, fields: Record<string, unknown>): void };
116
+ }): TeamTraffic {
117
+ const { bus, source } = options;
118
+ const now = options.now ?? Date.now;
119
+ const present = new Map<string, Present>();
120
+ /** Each artifact's present views, so a fan-out reads only its own artifact's (Opus review 9). */
121
+ const presentOn = new Map<string, Set<string>>();
122
+ const put = (entry: Present): void => {
123
+ present.set(entry.viewId, entry);
124
+ let views = presentOn.get(entry.artifactId);
125
+ if (!views) {
126
+ views = new Set();
127
+ presentOn.set(entry.artifactId, views);
128
+ }
129
+ views.add(entry.viewId);
130
+ };
131
+ const drop = (viewId: string): void => {
132
+ const entry = present.get(viewId);
133
+ if (!entry) return;
134
+ present.delete(viewId);
135
+ const views = presentOn.get(entry.artifactId);
136
+ views?.delete(viewId);
137
+ if (views?.size === 0) presentOn.delete(entry.artifactId);
138
+ };
139
+ const presentFor = function* (artifactId: string): Generator<Present> {
140
+ for (const viewId of presentOn.get(artifactId) ?? []) {
141
+ const entry = present.get(viewId);
142
+ if (entry) yield entry;
143
+ }
144
+ };
145
+ const buckets = new Map<string, Bucket>();
146
+ const following = new Map<string, Following>();
147
+ const fanout = new Map<string, ReturnType<typeof setTimeout>>();
148
+ const settle = new Map<string, ReturnType<typeof setTimeout>>();
149
+
150
+ /** Lookups for one fan-out: each viewer's peer, the owner check and the visibility, read once. */
151
+ const memo = (artifactId: string) => {
152
+ const peers = new Map<string, { readonly key: string } & RosterViewer>();
153
+ const owners = new Map<string, boolean>();
154
+ let visibility: TeamVisibility | undefined;
155
+ return {
156
+ visibility: () => (visibility ??= source.visibility(artifactId)),
157
+ isOwner: (viewerId: string) => {
158
+ let owner = owners.get(viewerId);
159
+ if (owner === undefined) {
160
+ owner = source.isOwner(viewerId);
161
+ owners.set(viewerId, owner);
162
+ }
163
+ return owner;
164
+ },
165
+ peer: (viewerId: string) => {
166
+ let peer = peers.get(viewerId);
167
+ if (!peer) {
168
+ peer = source.peer(artifactId, viewerId);
169
+ peers.set(viewerId, peer);
170
+ }
171
+ return peer;
172
+ },
173
+ };
174
+ };
175
+
176
+ /** Who is present on an artifact, as one viewer may see it. */
177
+ const stateFor = (
178
+ artifactId: string,
179
+ viewerId: string,
180
+ lookups: ReturnType<typeof memo> = memo(artifactId),
181
+ ): PresenceState => {
182
+ const visibility = lookups.visibility();
183
+ const sees: TeamVisibility = lookups.isOwner(viewerId) ? "names" : visibility;
184
+ const at = now();
185
+ // One entry per viewer: their most recent view's cursor and selection.
186
+ const byViewer = new Map<string, Present>();
187
+ for (const entry of presentFor(artifactId)) {
188
+ if (entry.until <= at) continue;
189
+ const kept = byViewer.get(entry.viewerId);
190
+ if (!kept || kept.at < entry.at) byViewer.set(entry.viewerId, entry);
191
+ }
192
+ const peerOf = (entry: Present): PresencePeer => {
193
+ const peer = lookups.peer(entry.viewerId);
194
+ return {
195
+ key: peer.key,
196
+ self: entry.viewerId === viewerId,
197
+ kind: peer.kind,
198
+ ...(peer.name !== undefined ? { name: peer.name } : {}),
199
+ ...(peer.verified !== undefined ? { verified: peer.verified } : {}),
200
+ ...(entry.cursor ? { cursor: entry.cursor } : {}),
201
+ ...(entry.selection ? { selection: entry.selection } : {}),
202
+ at: new Date(entry.at).toISOString(),
203
+ };
204
+ };
205
+ const own = byViewer.get(viewerId);
206
+ const others = [...byViewer.values()].filter((entry) => entry.viewerId !== viewerId);
207
+ const peers: PresencePeer[] = own ? [peerOf(own)] : [];
208
+ if (sees === "names") {
209
+ others.sort((a, b) => b.at - a.at);
210
+ for (const entry of others.slice(0, PRESENCE_PEERS_MAX)) peers.push(peerOf(entry));
211
+ }
212
+ return {
213
+ visibility,
214
+ peers,
215
+ ...(sees !== "private" ? { others: others.length } : {}),
216
+ };
217
+ };
218
+
219
+ /**
220
+ * Sends each present view of an artifact what it may see now, when that differs from what it
221
+ * last got: a view under `private` sees only itself, so others coming, moving and going send it
222
+ * nothing (Opus review 2), and under `counts` only a change of the count does.
223
+ */
224
+ const fanOut = (artifactId: string): void => {
225
+ fanout.delete(artifactId);
226
+ const at = now();
227
+ const lookups = memo(artifactId);
228
+ for (const entry of presentFor(artifactId)) {
229
+ if (entry.until <= at) continue;
230
+ try {
231
+ const presence = stateFor(artifactId, entry.viewerId, lookups);
232
+ const text = JSON.stringify(presence);
233
+ if (text === entry.last) continue;
234
+ entry.last = text;
235
+ bus.send(artifactId, entry.viewId, { kind: "presence", presence });
236
+ } catch (error) {
237
+ options.log?.error("team.presence_failed", { error });
238
+ }
239
+ }
240
+ };
241
+
242
+ /** Schedules the artifact's next presence message, at most every {@link PRESENCE_FANOUT_MS}. */
243
+ const changedPresence = (artifactId: string): void => {
244
+ if (fanout.has(artifactId)) return;
245
+ const timer = setTimeout(() => fanOut(artifactId), PRESENCE_FANOUT_MS);
246
+ timer.unref?.();
247
+ fanout.set(artifactId, timer);
248
+ };
249
+
250
+ /** Sends each following view its roster when it changed, from one read for all of them. */
251
+ const sendRosters = (artifactId: string): void => {
252
+ settle.delete(artifactId);
253
+ const at = now();
254
+ const views: [string, Following][] = [];
255
+ for (const [viewId, entry] of following) {
256
+ if (entry.artifactId !== artifactId) continue;
257
+ if (entry.until <= at) following.delete(viewId);
258
+ else views.push([viewId, entry]);
259
+ }
260
+ if (views.length === 0) return;
261
+ let rosters: RosterForPage[];
262
+ try {
263
+ rosters = source.rostersForPages(
264
+ artifactId,
265
+ views.map(([, entry]) => entry.viewerId),
266
+ );
267
+ } catch (error) {
268
+ options.log?.error("team.respondents_failed", { error });
269
+ return;
270
+ }
271
+ views.forEach(([viewId, entry], index) => {
272
+ const roster = rosters[index];
273
+ if (!roster) return;
274
+ const text = JSON.stringify(roster);
275
+ if (text === entry.last) return;
276
+ entry.last = text;
277
+ try {
278
+ bus.send(artifactId, viewId, { kind: "respondents", respondents: roster });
279
+ } catch (error) {
280
+ options.log?.error("team.respondents_failed", { error });
281
+ }
282
+ });
283
+ };
284
+
285
+ const stopTeam = source.onTeam((artifactId) => {
286
+ let any = false;
287
+ for (const entry of following.values()) {
288
+ if (entry.artifactId === artifactId) {
289
+ any = true;
290
+ break;
291
+ }
292
+ }
293
+ if (!any || settle.has(artifactId)) return;
294
+ const timer = setTimeout(() => sendRosters(artifactId), RESPONDENTS_SETTLE_MS);
295
+ timer.unref?.();
296
+ settle.set(artifactId, timer);
297
+ });
298
+
299
+ // Expired presence ends, and the artifact's pages hear who left.
300
+ const sweep = setInterval(() => {
301
+ const at = now();
302
+ const left = new Set<string>();
303
+ for (const [viewId, entry] of present) {
304
+ if (entry.until <= at) {
305
+ drop(viewId);
306
+ left.add(entry.artifactId);
307
+ }
308
+ }
309
+ for (const [viewId, entry] of following) if (entry.until <= at) following.delete(viewId);
310
+ for (const [viewId, bucket] of buckets) {
311
+ if (bucket.refilled + PRESENCE_LEASE_MS <= at) buckets.delete(viewId);
312
+ }
313
+ for (const artifactId of left) changedPresence(artifactId);
314
+ }, 1_000);
315
+ sweep.unref?.();
316
+
317
+ return {
318
+ presence(page, request) {
319
+ const at = now();
320
+ const viewId = request.viewId;
321
+ let entry = present.get(viewId);
322
+ if (entry && (entry.artifactId !== page.artifactId || entry.viewerId !== page.viewerId)) {
323
+ drop(viewId);
324
+ entry = undefined;
325
+ }
326
+ // Posts of one page can arrive out of order (a cursor update in flight when the page left):
327
+ // one older than the newest the view sent changes nothing, so a leave is never undone by an
328
+ // update that overtook it (Opus review 7). The count lives in the view's bucket, which
329
+ // outlives its presence by a lease.
330
+ const known = buckets.get(viewId);
331
+ const stale =
332
+ request.seq !== undefined && known?.seq !== undefined && request.seq <= known.seq;
333
+ if (request.seq !== undefined && !stale) {
334
+ const remembered = known ?? { tokens: PRESENCE_RATE, refilled: at };
335
+ remembered.seq = request.seq;
336
+ buckets.set(viewId, remembered);
337
+ }
338
+ // A present view's leave is always honored: it removes what the others see, and a page sends
339
+ // it as it goes, however fast it moved before.
340
+ if (request.leave === true && entry && !stale) {
341
+ drop(viewId);
342
+ changedPresence(page.artifactId);
343
+ return { state: stateFor(page.artifactId, page.viewerId) };
344
+ }
345
+ // Every other post takes a token (a leave of a view that isn't present too):
346
+ // PRESENCE_RATE a second, in bursts of as many, from a bucket a leave never refills.
347
+ const bucket = buckets.get(viewId) ?? { tokens: PRESENCE_RATE, refilled: at };
348
+ bucket.tokens = Math.min(
349
+ PRESENCE_RATE,
350
+ bucket.tokens + ((at - bucket.refilled) / 1000) * PRESENCE_RATE,
351
+ );
352
+ bucket.refilled = at;
353
+ buckets.set(viewId, bucket);
354
+ if (bucket.tokens < 1) {
355
+ return {
356
+ limited: true,
357
+ retryAfterMs: Math.ceil(((1 - bucket.tokens) / PRESENCE_RATE) * 1000),
358
+ };
359
+ }
360
+ bucket.tokens -= 1;
361
+ // A stale post takes its token like any, so sending old counts never escapes the rate.
362
+ if (stale || request.leave === true)
363
+ return { state: stateFor(page.artifactId, page.viewerId) };
364
+ if (!entry) {
365
+ entry = {
366
+ artifactId: page.artifactId,
367
+ viewId,
368
+ viewerId: page.viewerId,
369
+ at,
370
+ until: at + PRESENCE_LEASE_MS,
371
+ };
372
+ put(entry);
373
+ }
374
+ if (request.cursor !== undefined) {
375
+ if (request.cursor === null) delete entry.cursor;
376
+ else entry.cursor = { x: request.cursor.x, y: request.cursor.y };
377
+ }
378
+ if (request.selection !== undefined) {
379
+ if (request.selection === null) delete entry.selection;
380
+ else
381
+ entry.selection = {
382
+ ...(request.selection.element !== undefined
383
+ ? { element: request.selection.element }
384
+ : {}),
385
+ ...(request.selection.start !== undefined ? { start: request.selection.start } : {}),
386
+ ...(request.selection.end !== undefined ? { end: request.selection.end } : {}),
387
+ };
388
+ }
389
+ entry.at = at;
390
+ entry.until = at + PRESENCE_LEASE_MS;
391
+ changedPresence(page.artifactId);
392
+ // The answer is what the view sees now: the fan-out sends it again only once that changes.
393
+ const state = stateFor(page.artifactId, page.viewerId);
394
+ entry.last = JSON.stringify(state);
395
+ return { state };
396
+ },
397
+ respondents(page, viewId) {
398
+ const roster = source.rosterForPage(page);
399
+ following.set(viewId, {
400
+ artifactId: page.artifactId,
401
+ viewerId: page.viewerId,
402
+ until: now() + RESPONDENTS_LEASE_MS,
403
+ last: JSON.stringify(roster),
404
+ });
405
+ return roster;
406
+ },
407
+ presentCount() {
408
+ const at = now();
409
+ let count = 0;
410
+ for (const entry of present.values()) if (entry.until > at) count += 1;
411
+ return count;
412
+ },
413
+ close() {
414
+ clearInterval(sweep);
415
+ present.clear();
416
+ presentOn.clear();
417
+ buckets.clear();
418
+ following.clear();
419
+ stopTeam();
420
+ for (const timer of fanout.values()) clearTimeout(timer);
421
+ for (const timer of settle.values()) clearTimeout(timer);
422
+ fanout.clear();
423
+ settle.clear();
424
+ },
425
+ };
426
+ }
@@ -57,6 +57,9 @@ function viewerOf(row: ViewerRow): Viewer {
57
57
  ...(row.kind === "token" || row.kind === "host" || row.kind === "tailnet"
58
58
  ? { ref: row.external_ref }
59
59
  : {}),
60
+ // A hosted account's name is its identity provider's; an anonymous viewer's, their own.
61
+ ...(row.kind === "account" ? { verified: true } : {}),
62
+ ...(row.kind === "anonymous" ? { verified: false } : {}),
60
63
  };
61
64
  }
62
65
 
@@ -110,7 +113,37 @@ export function viewerForLink(db: LedgerDb, tokenId: string, name: string): stri
110
113
  return viewerByRef(db, "token", { ref: `link:${tokenId}`, name });
111
114
  }
112
115
 
113
- function viewerByRef(db: LedgerDb, kind: "token" | "host" | "tailnet", spec: ViewerSpec): string {
116
+ /**
117
+ * A signed-in person on a hosted link minted without a viewer (D165 item 8): one viewer of kind
118
+ * `account` per account, named as its identity provider verified it.
119
+ */
120
+ export function viewerForAccount(db: LedgerDb, accountId: string, name?: string): string {
121
+ return viewerByRef(db, "account", { ref: accountId, ...(name !== undefined ? { name } : {}) });
122
+ }
123
+
124
+ /**
125
+ * A person who isn't signed in on a hosted link minted without a viewer (D165 item 8): one viewer
126
+ * of kind `anonymous` per browser and route, by the route's derived key
127
+ * (`HMAC-SHA-256(browser secret, routeId)`), never the shell's raw secret. A name they choose is
128
+ * set apart, unverified ({@link nameAnonymous}).
129
+ */
130
+ export function viewerForAnonymous(db: LedgerDb, key: string): string {
131
+ return viewerByRef(db, "anonymous", { ref: key });
132
+ }
133
+
134
+ /** Sets the self-chosen, unverified name of an anonymous viewer; any other viewer is left alone. */
135
+ export function nameAnonymous(db: LedgerDb, viewerId: string, name: string | null): boolean {
136
+ return (
137
+ db.run("UPDATE viewer SET name = ? WHERE id = ? AND kind = 'anonymous'", name, viewerId)
138
+ .changes > 0
139
+ );
140
+ }
141
+
142
+ function viewerByRef(
143
+ db: LedgerDb,
144
+ kind: "token" | "host" | "tailnet" | "account" | "anonymous",
145
+ spec: ViewerSpec,
146
+ ): string {
114
147
  const found = db.get<ViewerRow>(
115
148
  "SELECT * FROM viewer WHERE kind = ? AND external_ref = ?",
116
149
  kind,
@@ -61,6 +61,153 @@ function submissionEvent(db: LedgerDb, row: SubmissionRow): EventRecord {
61
61
  };
62
62
  }
63
63
 
64
+ /**
65
+ * The latest roster event at or before `upTo` (`roster.changed` or `roster.completed`), or the
66
+ * roster's state a compaction summary kept for the events it replaced (DATA_MODEL §4).
67
+ */
68
+ function latestRosterState(
69
+ db: LedgerDb,
70
+ artifactId: string,
71
+ upTo: number,
72
+ ): { readonly complete: boolean; readonly completed?: EventRecord } | undefined {
73
+ const row = db.get<EventRow>(
74
+ "SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type IN ('roster.changed', 'roster.completed', ?) ORDER BY cursor DESC LIMIT 1",
75
+ artifactId,
76
+ upTo,
77
+ COMPACTED,
78
+ );
79
+ if (!row) return undefined;
80
+ const payload = JSON.parse(row.payload_json) as Record<string, unknown>;
81
+ if (row.type === COMPACTED) {
82
+ const kept = payload["roster"] as
83
+ | { readonly complete: boolean; readonly completed?: EventRecord }
84
+ | undefined;
85
+ return kept;
86
+ }
87
+ const lastCompleted = (): EventRecord | undefined => {
88
+ const completed = db.get<EventRow>(
89
+ "SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type = 'roster.completed' ORDER BY cursor DESC LIMIT 1",
90
+ artifactId,
91
+ upTo,
92
+ );
93
+ if (completed) return eventRecord(completed);
94
+ const summary = db.get<EventRow>(
95
+ `SELECT * FROM event WHERE artifact_id = ? AND cursor <= ? AND type = '${COMPACTED}' ORDER BY cursor DESC LIMIT 1`,
96
+ artifactId,
97
+ upTo,
98
+ );
99
+ if (!summary) return undefined;
100
+ return (JSON.parse(summary.payload_json) as { roster?: { completed?: EventRecord } }).roster
101
+ ?.completed;
102
+ };
103
+ if (row.type === "roster.completed") return { complete: true, completed: eventRecord(row) };
104
+ if (payload["complete"] !== true) return { complete: false };
105
+ const completed = lastCompleted();
106
+ return completed ? { complete: true, completed } : { complete: true };
107
+ }
108
+
109
+ /**
110
+ * `submitted:all` and `submitted:<N>` (D168, CO-02), under `once` per-viewer and `epochs`:
111
+ * - `submitted:all` is the roster's completion. Under `once` per-viewer without an explicit
112
+ * cursor it is level-triggered: the roster is complete now (its latest event says so), and the
113
+ * latest `roster.completed` answers. Otherwise it is the first `roster.completed` after the
114
+ * cursor, so an agent waits for each next completion (a roster that grew, an `epochs` round).
115
+ * It is read from durable events only, so an owner instance answers it for a hosted artifact
116
+ * from the events it follows.
117
+ * - `submitted:<N>` counts submissions: under `once` per-viewer without an explicit cursor all of
118
+ * them, otherwise those after the cursor; the N-th one's `submission.created` answers.
119
+ * Under `once` per-artifact (one submission in all) only `submitted:1` can ever hold:
120
+ * `MOSTRA_TEAM_ROSTER_POLICY` for the rest; under `none`, `MOSTRA_SUBMIT_POLICY_NONE`.
121
+ */
122
+ function checkTeamCondition(
123
+ db: LedgerDb,
124
+ artifactId: string,
125
+ until: string,
126
+ after: number,
127
+ upTo: number,
128
+ explicitAfter: boolean,
129
+ ): { readonly event: EventRecord } | { readonly cursor: number } {
130
+ const artifact = db.get<{ policy_json: string | null }>(
131
+ "SELECT policy_json FROM artifact WHERE id = ?",
132
+ artifactId,
133
+ );
134
+ const policy = storedPolicy(artifact?.policy_json ?? null);
135
+ if (policy.policy === "none") {
136
+ throw new RpcError(
137
+ createDiagnostic("MOSTRA_SUBMIT_POLICY_NONE", {
138
+ message:
139
+ "This artifact's submission policy is none: nothing will be submitted to wait for.",
140
+ }),
141
+ );
142
+ }
143
+ const count = until === "submitted:all" ? undefined : Number(until.slice("submitted:".length));
144
+ if (count !== undefined && (!Number.isSafeInteger(count) || count < 1 || count > 10_000)) {
145
+ throw new RpcError(
146
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
147
+ message: "submitted:<N> takes a number of submissions from 1 to 10000.",
148
+ }),
149
+ -32602,
150
+ );
151
+ }
152
+ const perArtifact = policy.policy === "once" && policy.scope !== "per-viewer";
153
+ if (perArtifact && count !== 1) {
154
+ throw new RpcError(
155
+ createDiagnostic("MOSTRA_TEAM_ROSTER_POLICY", {
156
+ message: `This artifact takes one submission in all (once, per-artifact), so ${until} could never hold.`,
157
+ }),
158
+ );
159
+ }
160
+ const level = policy.policy === "once" && !explicitAfter;
161
+ if (count !== undefined) {
162
+ const from = level ? 0 : after;
163
+ if (!level) checkCompaction(db, { artifacts: [artifactId] }, after);
164
+ const row = db.get<SubmissionRow>(
165
+ "SELECT * FROM submission WHERE artifact_id = ? AND position > ? AND position <= ? ORDER BY position LIMIT 1 OFFSET ?",
166
+ artifactId,
167
+ from,
168
+ upTo,
169
+ count - 1,
170
+ );
171
+ if (row) return { event: submissionEvent(db, row) };
172
+ return { cursor: Math.max(upTo, after) };
173
+ }
174
+ if (level) {
175
+ const state = latestRosterState(db, artifactId, upTo);
176
+ if (state?.complete && state.completed) {
177
+ return heldHere(db, state.completed) ? { event: state.completed } : { cursor: after };
178
+ }
179
+ return { cursor: Math.max(upTo, after) };
180
+ }
181
+ checkCompaction(db, { artifacts: [artifactId] }, after);
182
+ const completed = db.get<EventRow>(
183
+ "SELECT * FROM event WHERE artifact_id = ? AND cursor > ? AND cursor <= ? AND type = 'roster.completed' ORDER BY cursor LIMIT 1",
184
+ artifactId,
185
+ after,
186
+ upTo,
187
+ );
188
+ if (!completed) return { cursor: Math.max(upTo, after) };
189
+ const event = eventRecord(completed);
190
+ // Not yet: the newest cursor examined stays before the completion, so the next wait finds it.
191
+ return heldHere(db, event) ? { event } : { cursor: Math.max(after, completed.cursor - 1) };
192
+ }
193
+
194
+ /**
195
+ * Whether this home holds every submission a completion names. A local home always does (they
196
+ * commit together); an owner instance copies a hosted `roster.completed` through its follow, while
197
+ * the submissions arrive by delivery, so a wait answers only once the last one is imported and
198
+ * `results` holds every answer the completion counts (J14). The import's commit wakes the wait.
199
+ */
200
+ function heldHere(db: LedgerDb, completed: EventRecord): boolean {
201
+ const named = completed.payload["submissions"];
202
+ if (!Array.isArray(named)) return true;
203
+ for (const entry of named) {
204
+ const id = (entry as { submissionId?: unknown } | null)?.submissionId;
205
+ if (typeof id !== "string" || id === "") continue;
206
+ if (!db.get("SELECT 1 FROM submission WHERE id = ?", id)) return false;
207
+ }
208
+ return true;
209
+ }
210
+
64
211
  /**
65
212
  * Checks a condition once, inside the caller's read transaction: the event that satisfies it, or
66
213
  * the newest cursor examined. Throws `MOSTRA_SUBMIT_POLICY_NONE` for `submitted` on an artifact
@@ -83,6 +230,9 @@ export function checkCondition(
83
230
  ...params,
84
231
  );
85
232
  let found: EventRow | undefined;
233
+ if (until === "submitted:all" || /^submitted:[0-9]+$/.test(until)) {
234
+ return checkTeamCondition(db, artifactId, until, after, upTo, explicitAfter);
235
+ }
86
236
  if (until === "submitted") {
87
237
  const artifact = db.get<{ policy_json: string | null }>(
88
238
  "SELECT policy_json FROM artifact WHERE id = ?",
@@ -29,7 +29,7 @@ export {
29
29
  recordResult,
30
30
  requestKey,
31
31
  } from "./requests.ts";
32
- export type { LedgerDb } from "./types.ts";
32
+ export type { LedgerDb, MigrationDb, SqlValue } from "./types.ts";
33
33
 
34
34
  /** The ledger's file name inside `<home>/store`. */
35
35
  export const LEDGER_FILE = "ledger.sqlite";
@@ -81,6 +81,13 @@ export interface Ledger {
81
81
  * `MOSTRA_HOME_DISK_FULL`; a removed ledger throws `MOSTRA_HOME_GONE`. Nothing partial commits.
82
82
  */
83
83
  write<T>(fn: (db: LedgerDb) => T): T;
84
+ /**
85
+ * Runs `fn` in one write transaction that may also drop and create triggers: the one path past
86
+ * the write-once triggers, for a remote server operator's explicit removal of an artifact
87
+ * (`ServerHandle.remove`, DATA_MODEL §7.5), which recreates every trigger it dropped before it
88
+ * commits. Nothing else calls it.
89
+ */
90
+ removal<T>(fn: (db: MigrationDb) => T): T;
84
91
  /** Runs `fn` in one read transaction, so it sees a single consistent state. */
85
92
  read<T>(fn: (db: LedgerDb) => T): T;
86
93
  /**
@@ -444,6 +451,18 @@ function wrap(
444
451
  }
445
452
  return result;
446
453
  },
454
+ removal<T>(fn: (db: MigrationDb) => T): T {
455
+ assertInPlace();
456
+ const result = guarded(() => db.transaction(() => fn(target)).immediate());
457
+ for (const listener of listeners) {
458
+ try {
459
+ listener();
460
+ } catch {
461
+ // A listener's failure is its own; the commit stands.
462
+ }
463
+ }
464
+ return result;
465
+ },
447
466
  onCommit(listener) {
448
467
  listeners.add(listener);
449
468
  return () => listeners.delete(listener);