@eloxiv/cli 0.0.0-stage → 0.1.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 (294) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/AgentSkills.d.ts +51 -0
  4. package/dist/AgentSkills.d.ts.map +1 -0
  5. package/dist/AgentSkills.js +264 -0
  6. package/dist/AgentSkills.js.map +1 -0
  7. package/dist/AgentWeb.d.ts +83 -0
  8. package/dist/AgentWeb.d.ts.map +1 -0
  9. package/dist/AgentWeb.js +436 -0
  10. package/dist/AgentWeb.js.map +1 -0
  11. package/dist/App.d.ts +213 -0
  12. package/dist/App.d.ts.map +1 -0
  13. package/dist/App.js +357 -0
  14. package/dist/App.js.map +1 -0
  15. package/dist/Blueprint.d.ts +47 -0
  16. package/dist/Blueprint.d.ts.map +1 -0
  17. package/dist/Blueprint.js +241 -0
  18. package/dist/Blueprint.js.map +1 -0
  19. package/dist/Brand.d.ts +42 -0
  20. package/dist/Brand.d.ts.map +1 -0
  21. package/dist/Brand.js +370 -0
  22. package/dist/Brand.js.map +1 -0
  23. package/dist/Changelog.d.ts +22 -0
  24. package/dist/Changelog.d.ts.map +1 -0
  25. package/dist/Changelog.js +117 -0
  26. package/dist/Changelog.js.map +1 -0
  27. package/dist/Cli.d.ts +17 -0
  28. package/dist/Cli.d.ts.map +1 -0
  29. package/dist/Cli.js +810 -0
  30. package/dist/Cli.js.map +1 -0
  31. package/dist/DbAdmin.d.ts +18 -0
  32. package/dist/DbAdmin.d.ts.map +1 -0
  33. package/dist/DbAdmin.js +91 -0
  34. package/dist/DbAdmin.js.map +1 -0
  35. package/dist/Dependencies.d.ts +53 -0
  36. package/dist/Dependencies.d.ts.map +1 -0
  37. package/dist/Dependencies.js +132 -0
  38. package/dist/Dependencies.js.map +1 -0
  39. package/dist/Deploy.d.ts +39 -0
  40. package/dist/Deploy.d.ts.map +1 -0
  41. package/dist/Deploy.js +458 -0
  42. package/dist/Deploy.js.map +1 -0
  43. package/dist/Docs.d.ts +71 -0
  44. package/dist/Docs.d.ts.map +1 -0
  45. package/dist/Docs.js +240 -0
  46. package/dist/Docs.js.map +1 -0
  47. package/dist/Doctor.d.ts +56 -0
  48. package/dist/Doctor.d.ts.map +1 -0
  49. package/dist/Doctor.js +368 -0
  50. package/dist/Doctor.js.map +1 -0
  51. package/dist/Dossier.d.ts +23 -0
  52. package/dist/Dossier.d.ts.map +1 -0
  53. package/dist/Dossier.js +92 -0
  54. package/dist/Dossier.js.map +1 -0
  55. package/dist/Emit.d.ts +26 -0
  56. package/dist/Emit.d.ts.map +1 -0
  57. package/dist/Emit.js +51 -0
  58. package/dist/Emit.js.map +1 -0
  59. package/dist/Errors.d.ts +26 -0
  60. package/dist/Errors.d.ts.map +1 -0
  61. package/dist/Errors.js +17 -0
  62. package/dist/Errors.js.map +1 -0
  63. package/dist/Evals.d.ts +52 -0
  64. package/dist/Evals.d.ts.map +1 -0
  65. package/dist/Evals.js +126 -0
  66. package/dist/Evals.js.map +1 -0
  67. package/dist/Files.d.ts +47 -0
  68. package/dist/Files.d.ts.map +1 -0
  69. package/dist/Files.js +145 -0
  70. package/dist/Files.js.map +1 -0
  71. package/dist/Generate.d.ts +80 -0
  72. package/dist/Generate.d.ts.map +1 -0
  73. package/dist/Generate.js +310 -0
  74. package/dist/Generate.js.map +1 -0
  75. package/dist/Guards.d.ts +45 -0
  76. package/dist/Guards.d.ts.map +1 -0
  77. package/dist/Guards.js +530 -0
  78. package/dist/Guards.js.map +1 -0
  79. package/dist/Inspect.d.ts +125 -0
  80. package/dist/Inspect.d.ts.map +1 -0
  81. package/dist/Inspect.js +270 -0
  82. package/dist/Inspect.js.map +1 -0
  83. package/dist/Keychain.d.ts +57 -0
  84. package/dist/Keychain.d.ts.map +1 -0
  85. package/dist/Keychain.js +73 -0
  86. package/dist/Keychain.js.map +1 -0
  87. package/dist/Lock.d.ts +13 -0
  88. package/dist/Lock.d.ts.map +1 -0
  89. package/dist/Lock.js +145 -0
  90. package/dist/Lock.js.map +1 -0
  91. package/dist/Mcp.d.ts +91 -0
  92. package/dist/Mcp.d.ts.map +1 -0
  93. package/dist/Mcp.js +128 -0
  94. package/dist/Mcp.js.map +1 -0
  95. package/dist/Merge.d.ts +18 -0
  96. package/dist/Merge.d.ts.map +1 -0
  97. package/dist/Merge.js +43 -0
  98. package/dist/Merge.js.map +1 -0
  99. package/dist/Migrate.d.ts +78 -0
  100. package/dist/Migrate.d.ts.map +1 -0
  101. package/dist/Migrate.js +288 -0
  102. package/dist/Migrate.js.map +1 -0
  103. package/dist/Plugins.d.ts +36 -0
  104. package/dist/Plugins.d.ts.map +1 -0
  105. package/dist/Plugins.js +304 -0
  106. package/dist/Plugins.js.map +1 -0
  107. package/dist/Postgres.d.ts +73 -0
  108. package/dist/Postgres.d.ts.map +1 -0
  109. package/dist/Postgres.js +294 -0
  110. package/dist/Postgres.js.map +1 -0
  111. package/dist/Publish.d.ts +23 -0
  112. package/dist/Publish.d.ts.map +1 -0
  113. package/dist/Publish.js +59 -0
  114. package/dist/Publish.js.map +1 -0
  115. package/dist/Registry.d.ts +539 -0
  116. package/dist/Registry.d.ts.map +1 -0
  117. package/dist/Registry.js +340 -0
  118. package/dist/Registry.js.map +1 -0
  119. package/dist/Remote.d.ts +90 -0
  120. package/dist/Remote.d.ts.map +1 -0
  121. package/dist/Remote.js +1006 -0
  122. package/dist/Remote.js.map +1 -0
  123. package/dist/Run.d.ts +120 -0
  124. package/dist/Run.d.ts.map +1 -0
  125. package/dist/Run.js +477 -0
  126. package/dist/Run.js.map +1 -0
  127. package/dist/SyncGen.d.ts +118 -0
  128. package/dist/SyncGen.d.ts.map +1 -0
  129. package/dist/SyncGen.js +392 -0
  130. package/dist/SyncGen.js.map +1 -0
  131. package/dist/Update.d.ts +301 -0
  132. package/dist/Update.d.ts.map +1 -0
  133. package/dist/Update.js +627 -0
  134. package/dist/Update.js.map +1 -0
  135. package/dist/bin.d.ts +3 -0
  136. package/dist/bin.d.ts.map +1 -0
  137. package/dist/bin.js +42 -0
  138. package/dist/bin.js.map +1 -0
  139. package/dist/docs/backlog.md +56 -0
  140. package/dist/docs/ci.md +277 -0
  141. package/dist/docs/cli.md +696 -0
  142. package/dist/docs/connectors/google.md +115 -0
  143. package/dist/docs/connectors/http-openapi.md +7 -0
  144. package/dist/docs/connectors/mcp.md +8 -0
  145. package/dist/docs/connectors/microsoft-graph.md +75 -0
  146. package/dist/docs/connectors/openai.md +25 -0
  147. package/dist/docs/connectors/slack.md +162 -0
  148. package/dist/docs/connectors/workos.md +39 -0
  149. package/dist/docs/contracts/README.md +173 -0
  150. package/dist/docs/contracts/action-consent.md +92 -0
  151. package/dist/docs/contracts/action-registry.md +85 -0
  152. package/dist/docs/contracts/actor.md +100 -0
  153. package/dist/docs/contracts/agent-resources.md +90 -0
  154. package/dist/docs/contracts/agent-runtime.md +257 -0
  155. package/dist/docs/contracts/approvals.md +126 -0
  156. package/dist/docs/contracts/audit.md +75 -0
  157. package/dist/docs/contracts/auth-provider.md +74 -0
  158. package/dist/docs/contracts/calendar-provider.md +46 -0
  159. package/dist/docs/contracts/client-sdk.md +245 -0
  160. package/dist/docs/contracts/collab-document.md +151 -0
  161. package/dist/docs/contracts/command.md +44 -0
  162. package/dist/docs/contracts/connections.md +235 -0
  163. package/dist/docs/contracts/context-accounting.md +50 -0
  164. package/dist/docs/contracts/daemon.md +243 -0
  165. package/dist/docs/contracts/db-tx.md +53 -0
  166. package/dist/docs/contracts/delegation.md +68 -0
  167. package/dist/docs/contracts/device-control.md +103 -0
  168. package/dist/docs/contracts/directory-provider.md +36 -0
  169. package/dist/docs/contracts/directory.md +161 -0
  170. package/dist/docs/contracts/document-source.md +33 -0
  171. package/dist/docs/contracts/files.md +115 -0
  172. package/dist/docs/contracts/flags.md +83 -0
  173. package/dist/docs/contracts/host.md +68 -0
  174. package/dist/docs/contracts/http-api.md +43 -0
  175. package/dist/docs/contracts/ingestion.md +130 -0
  176. package/dist/docs/contracts/ingress.md +141 -0
  177. package/dist/docs/contracts/invocation.md +260 -0
  178. package/dist/docs/contracts/local-client.md +108 -0
  179. package/dist/docs/contracts/locale.md +56 -0
  180. package/dist/docs/contracts/machine-identity.md +117 -0
  181. package/dist/docs/contracts/mail-provider.md +49 -0
  182. package/dist/docs/contracts/memory.md +53 -0
  183. package/dist/docs/contracts/messaging.md +40 -0
  184. package/dist/docs/contracts/metering.md +139 -0
  185. package/dist/docs/contracts/model-provider.md +84 -0
  186. package/dist/docs/contracts/module-manifest.md +213 -0
  187. package/dist/docs/contracts/notification-channel.md +90 -0
  188. package/dist/docs/contracts/notifications.md +123 -0
  189. package/dist/docs/contracts/outbox.md +80 -0
  190. package/dist/docs/contracts/privacy.md +110 -0
  191. package/dist/docs/contracts/progress.md +52 -0
  192. package/dist/docs/contracts/query-surface.md +108 -0
  193. package/dist/docs/contracts/readiness.md +63 -0
  194. package/dist/docs/contracts/release.md +142 -0
  195. package/dist/docs/contracts/result-rendering.md +61 -0
  196. package/dist/docs/contracts/sandbox.md +186 -0
  197. package/dist/docs/contracts/scheduler.md +148 -0
  198. package/dist/docs/contracts/screen-context.md +81 -0
  199. package/dist/docs/contracts/search.md +120 -0
  200. package/dist/docs/contracts/secrets.md +74 -0
  201. package/dist/docs/contracts/settings.md +109 -0
  202. package/dist/docs/contracts/sharing.md +77 -0
  203. package/dist/docs/contracts/slot.md +48 -0
  204. package/dist/docs/contracts/space.md +67 -0
  205. package/dist/docs/contracts/storage-adapter.md +45 -0
  206. package/dist/docs/contracts/storage-backend.md +56 -0
  207. package/dist/docs/contracts/sync.md +213 -0
  208. package/dist/docs/contracts/telemetry.md +80 -0
  209. package/dist/docs/contracts/theme-tokens.md +50 -0
  210. package/dist/docs/contracts/tool-source.md +58 -0
  211. package/dist/docs/contracts/versioning.md +99 -0
  212. package/dist/docs/contracts/view.md +65 -0
  213. package/dist/docs/contracts/work-items.md +99 -0
  214. package/dist/docs/contracts/workflow.md +82 -0
  215. package/dist/docs/decisions.md +163 -0
  216. package/dist/docs/example-app.md +192 -0
  217. package/dist/docs/getting-started.md +927 -0
  218. package/dist/docs/goal.md +54 -0
  219. package/dist/docs/parity.md +29 -0
  220. package/dist/docs/performance.md +129 -0
  221. package/dist/docs/registry/README.md +74 -0
  222. package/dist/docs/registry/app.md +38 -0
  223. package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
  224. package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
  225. package/dist/docs/registry/calendar.md +35 -0
  226. package/dist/docs/registry/chat-ui-foldkit.md +30 -0
  227. package/dist/docs/registry/desktop-rune.md +49 -0
  228. package/dist/docs/registry/desktop.md +32 -0
  229. package/dist/docs/registry/eloxiv-action.md +25 -0
  230. package/dist/docs/registry/eloxiv-connector.md +25 -0
  231. package/dist/docs/registry/eloxiv-module.md +25 -0
  232. package/dist/docs/registry/eloxiv-policy.md +25 -0
  233. package/dist/docs/registry/eloxiv-view.md +25 -0
  234. package/dist/docs/registry/hello-ui-foldkit.md +29 -0
  235. package/dist/docs/registry/hello.md +39 -0
  236. package/dist/docs/registry/home-ui-foldkit.md +27 -0
  237. package/dist/docs/registry/home.md +29 -0
  238. package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
  239. package/dist/docs/registry/mail-ui-foldkit.md +27 -0
  240. package/dist/docs/registry/mail.md +34 -0
  241. package/dist/docs/registry/meeting-prep.md +26 -0
  242. package/dist/docs/registry/members-ui-foldkit.md +28 -0
  243. package/dist/docs/registry/mobile.md +37 -0
  244. package/dist/docs/registry/notes-ui-foldkit.md +27 -0
  245. package/dist/docs/registry/notes.md +26 -0
  246. package/dist/docs/registry/people-ui-foldkit.md +28 -0
  247. package/dist/docs/registry/people.md +38 -0
  248. package/dist/docs/registry/shell-foldkit.md +34 -0
  249. package/dist/docs/registry/theme.md +25 -0
  250. package/dist/docs/registry/ui-conformance.md +30 -0
  251. package/dist/docs/release.md +100 -0
  252. package/dist/docs/scaffold.md +826 -0
  253. package/dist/docs/security/threat-model.md +299 -0
  254. package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
  255. package/dist/index.d.ts +8 -0
  256. package/dist/index.d.ts.map +1 -0
  257. package/dist/index.js +8 -0
  258. package/dist/index.js.map +1 -0
  259. package/package.json +48 -3
  260. package/src/AgentSkills.ts +329 -0
  261. package/src/AgentWeb.ts +507 -0
  262. package/src/App.ts +435 -0
  263. package/src/Blueprint.ts +276 -0
  264. package/src/Brand.ts +415 -0
  265. package/src/Changelog.ts +136 -0
  266. package/src/Cli.ts +1458 -0
  267. package/src/DbAdmin.ts +115 -0
  268. package/src/Dependencies.ts +170 -0
  269. package/src/Deploy.ts +563 -0
  270. package/src/Docs.ts +309 -0
  271. package/src/Doctor.ts +424 -0
  272. package/src/Dossier.ts +148 -0
  273. package/src/Emit.ts +68 -0
  274. package/src/Errors.ts +18 -0
  275. package/src/Evals.ts +153 -0
  276. package/src/Files.ts +152 -0
  277. package/src/Generate.ts +402 -0
  278. package/src/Guards.ts +541 -0
  279. package/src/Inspect.ts +358 -0
  280. package/src/Keychain.ts +107 -0
  281. package/src/Lock.ts +174 -0
  282. package/src/Mcp.ts +159 -0
  283. package/src/Merge.ts +70 -0
  284. package/src/Migrate.ts +331 -0
  285. package/src/Plugins.ts +347 -0
  286. package/src/Postgres.ts +353 -0
  287. package/src/Publish.ts +64 -0
  288. package/src/Registry.ts +405 -0
  289. package/src/Remote.ts +1158 -0
  290. package/src/Run.ts +541 -0
  291. package/src/SyncGen.ts +570 -0
  292. package/src/Update.ts +873 -0
  293. package/src/bin.ts +46 -0
  294. package/src/index.ts +7 -0
@@ -0,0 +1,213 @@
1
+ # ModuleManifest
2
+
3
+ Kind: kernel service. Version 1.6.0 (1.1.0: entities publish their storage, sync, unique keys and relationships; 1.2.0: actions publish their optimistic effect; 1.3.0: entities publish their collaborative documents, `collab`; 1.4.0: actions publish `consentEachCall` and the capability operations they declare, `connections`; 1.5.0: actions publish `exposure` when a surface does not offer them; 1.6.0: actions publish `title`, what people see them called (one line, at most 80 characters), and an optimistic effect may be `custom`, the module's own prediction). Schema: [`packages/contracts/schema/contracts/ModuleManifest.json`](../../packages/contracts/schema/contracts/ModuleManifest.json). Source: [`packages/contracts/src/Module.ts`](../../packages/contracts/src/Module.ts), [`Manifest.ts`](../../packages/contracts/src/Manifest.ts), [`contracts/ModuleManifest.ts`](../../packages/contracts/src/contracts/ModuleManifest.ts).
4
+
5
+ ## Purpose
6
+
7
+ A module manifest is the declarative description of a module: what it stores, what it lets callers do, what it emits, and how it plugs into the rest of an app. It is data, written as Effect Schema in TypeScript and published as JSON Schema, so tools in any language can read a module without running its code.
8
+
9
+ An implementation of this contract does two things with manifests: it **emits** each one as language-neutral JSON, and it **loads** an app's manifests together, refusing to start the app if any declaration is wrong. The Eloxiv kernel loads manifests when it builds its registry at startup.
10
+
11
+ ## What a manifest declares
12
+
13
+ Declare a module with `defineModuleContract` (`@eloxiv/contracts`). Every declaration id is namespaced by the module: `<module>.<name>`, where the name is lower camel or kebab case (`hello.defaultVisibility`, `hello.greeting-panel`).
14
+
15
+ | Field | Declares |
16
+ | --- | --- |
17
+ | `entities` | Records the module stores, each over its Drizzle table (see [Entities](#entities)): Cedar type, table (in the module's own schema), primary key, row schema, columns, each field's storage (column, transport type, nullability, enum), the policy attributes the compiler may use, and what syncs. |
18
+ | `actions` | What callers can do: `title`, what people see the action called (a short verb phrase, "Send an email", shown in consent and approval prompts, notifications and chat cards; `defineAction({ title })`, one line of at most 80 characters (`ACTION_TITLE_MAX`; `defineAction` throws on a longer title or one with a line break or control character), or when omitted the action's readable name, `readableActionName`: the local part in words, sentence-cased, with the module in parentheses, `mail.send` is "Send (mail)", never the raw id; a manifest from before 1.6.0 has none and is read the same way), input and output schemas, the entity it `writes`, its `target`, further entities it `actsOn`, `organisationWide`, `bestEffort`, hints, and `consent` (an agent acting for a person needs their consent for each call; defaults to `hints.destructive`, see [ActionConsent](action-consent.md); `"each-call"`: no remembered permission covers a call), `connections`, the capability operations its handler may call through its Connections (an external one only scheduled, and only with consent; see [Invocation](invocation.md#external-effects)), `optimistic`: the change a client's replica predicts before the server answers, declared or the module's own (see [Optimistic effects](#optimistic-effects)), and `exposure`: the surfaces that offer it (`agent`, `mcp`, `api`, each true by default; see [ActionRegistry](action-registry.md#exposure)). An action's policy reaches only the tables of the entities it declares (`writes`, `target`, `actsOn`): on every other table it grants nothing, so an action declaring none reads only what `read` allows. `organisationWide: true` lets its policy leave the resource unconstrained; the kernel then confines it to records of the acting organisation. An action hinted `readOnly` runs its handler where the database refuses writes. The Cedar actions `read` and `share` are the kernel's own (reading records; who may share them, see [Sharing](sharing.md)): no module action may be named `<module>.read` or `<module>.share`. |
19
+ | `events` | What the module emits through the outbox, with payload schemas. An event may name the record it is about (`defineEvent(type, payload, { record: { entity, id } })`: one of the module's entities and the payload field holding its id); only such events can start members' event automations, and each automation sees one only while its owner may read that record ([Scheduler](scheduler.md#event-automations)). |
20
+ | `permissions` | The **permission vocabulary**: named permissions an organisation grants through roles (see [Directory](directory.md)). Each names the module's actions (or `read`) whose policy tests it. Policies test them as `principal.permissions.contains("<id>")`. |
21
+ | `settings` | Scoped values: `scope` is `user`, `org`, `app` or `module`; `schema` is the value's schema; `default` is the encoded (JSON) default. Read by key ([Settings](settings.md)). A schema marked sensitive is refused: secrets never go in settings. |
22
+ | `flags` | Feature flags: a `description` and a boolean `default` ([Flags](flags.md)). |
23
+ | `skills` | Agent skill documents the module ships: `content` is `{ text }` or `{ path }`, a path relative to the module's directory; optional `evals: { path }`, the skill's eval cases (a `SkillEvals` JSON file; see [AgentRuntime](agent-runtime.md), "Evals"); optional `audience`: `runtime`, `development` (for coding agents and tooling building the app; never given to the app's agent) or `both` (the default). Skills are the agent's app-scope resources ([AgentResources](agent-resources.md)). |
24
+ | `views` | Named shell views: `title`, `route` (unique across the app), and what it `shows`: one of the module's entities or one of its published query views. No UI code. |
25
+ | `slots` | Named extension points the module exposes; each `accepts` views or commands. |
26
+ | `contributions` | Views or commands this module contributes to a slot of any installed module. In the shell, a screen names the slots it shows: a contributed view whose screen is installed appears beside it as a panel, a contributed view command as a link (hello's screen shows `hello.greetingPanel`, to which notes contributes `notes.notes`). |
27
+ | `commands` | Palette commands: `run` is `{ action }` (any installed action) or `{ view }` (any installed view). |
28
+ | `workItemSources` | How the module feeds the unified inbox (decision 3): the `entity`, the field holding the item's `title`, the `state` (a field whose values map to `open`, `waiting` or `done`, or a constant state), the `assignee` field (or `null`) and the `link` view. |
29
+ | `entityResolvers` | Keyed by entity name: how another module turns a reference `{ module, entity, id }` into a title (the `title` field) and a link (a view), through the entity's read policy and never by reading the module's tables. |
30
+ | `queryViews` | Published query views (decision 6): one plain `SELECT` over the module's own tables, the `entity` whose read policy filters each row, and the `row` schema (one field per output column, which must include the entity's primary-key column; a field's `description` annotation describes the column to the agent). On the query surface ([QuerySurface](query-surface.md)) the view `<module>.<view>` is the relation `<module>_<view>`. |
31
+ | `dataSubjects` | The Privacy contract's declarations, by entity: `{ fields, erase }` (the fields holding a person's user id; erasure `delete`, `anonymise` with fixed values, or `retain` with a reason; optional `export`) or `{ none: reason }` for an entity about nobody. Checked here: the entity exists, its fields exist and are not the primary key, it has one organisation attribute, an anonymisation covers every subject field. Completeness (every entity declared) is enforced when the kernel's privacy module is installed. |
32
+ | `toolGroups` | Agent tool groups (`<module>.<name>`): a `description` and the module's own `actions` in it. Every action is also in its module's group (the module's name). An app disables groups for agents with `KernelApp.agentTools.disabledGroups`: their actions are hidden from every agent and refused to every agent-originated call, on every surface ([Invocation](invocation.md#reach)). Emitted as declared. |
33
+ | `approvalRules` | Business approval rules ([Approvals](approvals.md)): the `action` (any installed action), a declarative condition on its input (`when`), who may approve (`approvers`: a permission, role or group), `quorum`, `allowSelfApproval` and `expiresAfterMs`. Emitted with their defaults filled in. |
34
+
35
+ `jobs` (Scheduler) is added to the manifest by the Scheduler contract.
36
+
37
+ ## Entities
38
+
39
+ Decision 9: **a module declares each field once, in its Drizzle table.** An entity is a thin layer over that table, defined with `defineEntity` from `@eloxiv/contracts/drizzle` (the TypeScript authoring entry point; the root `@eloxiv/contracts` stays free of Drizzle, and what the manifest publishes is the language-neutral `EntityContract` below). It references the table's **column objects**, never column-name strings:
40
+
41
+ ```ts
42
+ // schema.ts: the fields, once (drizzle-kit generates the migrations from it)
43
+ export const greeting = pgSchema("hello").table("greeting", {
44
+ id: text("id").primaryKey(),
45
+ orgId: text("org_id").notNull(),
46
+ ownerId: text("owner_id").notNull(),
47
+ visibility: text("visibility", { enum: ["private", "org"] }).notNull().default("org"),
48
+ createdAt: timestamp("created_at", { withTimezone: true, mode: "string" }).notNull().defaultNow(),
49
+ })
50
+
51
+ // contract.ts: what policy and sync need, by reference
52
+ export const greeting = defineEntity(tables.greeting, {
53
+ name: "greeting",
54
+ cedarType: "Hello::Greeting",
55
+ policyAttributes: {
56
+ owner: { column: tables.greeting.ownerId, entity: "Eloxiv::User" },
57
+ org: { column: tables.greeting.orgId, entity: "Eloxiv::Org" },
58
+ visibility: { column: tables.greeting.visibility }, // a String: the column's type
59
+ sharedWith: { sharing: "read" },
60
+ },
61
+ // sync: false | { name?: "...", omit?: [tables.greeting.someColumn] } (default: every column syncs)
62
+ // relations: greetingRelations (Drizzle relations, for related())
63
+ // primaryKey: tables.greeting.id (default: the table's one-column key)
64
+ })
65
+ ```
66
+
67
+ Everything else is derived from the table: the Postgres location (the table's `pgSchema`), the primary key, each field's database column, its transport type (`string`, `number`, `boolean`, `json`; a timestamp is epoch milliseconds, as sync delivers it), its nullability (`notNull` absent) and enum values, the row schema (`Schema.NullOr` for a nullable field, `Schema.Literals` for an enum) and from it the entity's JSON Schema in the manifest. A column policy attribute's Cedar type is the column's (a string column is a `String`, an integer column a `Long`, a boolean a `Boolean`) or the entity type it names. A column that belongs to another table is refused when the entity is defined. Cedar and sync compare strings exactly, so a policy attribute is never stored where PostgreSQL compares otherwise: a `character(n)` (padded) or `uuid` (read in any case or spelling) column as a policy attribute is refused where policies are validated (`policyScopeProblems`, at the kernel's start and a MAKE install), and setup refuses a policy attribute's column under a non-deterministic collation; store such attributes as `text`.
68
+
69
+ The published entity (`moduleToJson`) carries `table`, `primaryKey`, `columns`, `policyAttributes` and `row` (JSON Schema) as before, plus `storage` (per field: `column`, `type` (`null` when the type is not on the [sync type allowlist](sync.md#sync-types)), `nullable`, `enum` (an enum array's labels too), `sqlType` (an enum as `schema.name`, Drizzle's bare `char()` as `character(1)`), `guard` (the range check sync needs for the type: `safe-integer`, `finite-double`, `instant`, `instant-ms`, `date`, `json-doubles` or `plain-array`, see [Sync types](sync.md#sync-types)), `generated` for a generated column, which never syncs), `sync` (`false`, or the Zero table's `name` and synced `fields`), `uniqueKeys` (field names) and `relationships` (the Drizzle relations it names: `one` with its `fields`, `references` and `relationName`, `many` with the table it is the other side of and its `relationName`, which pairs it with its `one`). A Cedar attribute's type does not depend on sync: an exact 64-bit integer (`bigint({ mode: "bigint" })`) is a `Long` whether or not it syncs. A sync name must be a JavaScript identifier the kernel does not reserve (`shareGrant`, `eloxivSyncOrg`, ...). Action inputs and outputs, events and query-view rows stay their own Effect Schemas: they rarely match a table's shape.
70
+
71
+ **Setup checks the table against the database** its migrations built (`entityColumnProblems`): a missing table, another primary key, a field whose column is missing, has another Postgres type than the table declares (compared by type OID and modifier, so exactly: an integer for a timestamp, `jsonb` for a `text[]`, a timestamp without a time zone for one with, `varchar(20)` for `varchar(10)`, a domain or a same-named type of another schema for the declared one), admits NULL where the table declares `notNull`, or is a Postgres enum with a value the table does not declare stops setup, so the row schema, the manifest and sync never promise what the database does not hold. The database may have columns the table does not declare; Eloxiv does not see them.
72
+
73
+ ### Writing a module
74
+
75
+ A module is a directory under `modules/<name>/` (registry items are laid out exactly as they land in an app):
76
+
77
+ | File | Holds |
78
+ | --- | --- |
79
+ | `schema.ts` | The Drizzle tables, in `pgSchema("<name>")`: the only declaration of the module's fields. `drizzle.config.ts` and `drizzle-kit generate` write `migrations/` from it |
80
+ | `contract.ts` | `defineModuleContract`: entities (`defineEntity` over the tables), actions and events with their own Effect Schemas, and the other declarations above |
81
+ | `server.ts` | `defineModule(contract, { policy, migrationsDir, handlers })` from `@eloxiv/kernel` |
82
+ | `policy.cedar` | The Cedar policy: actions and `read` (and `share` for entities with sharing attributes) |
83
+ | `sync.gen.ts` | Generated by `eloxiv generate`: the module's Zero tables, its schema, `zql` and `defineQuery`. Do not edit |
84
+ | `sync.ts` | Only the named queries, over `sync.gen.ts`'s `zql`; imports nothing from `@rocicorp/zero` |
85
+
86
+ After changing `schema.ts` or an entity: `drizzle-kit generate` (the migration), then `eloxiv generate` (the sync tables and the app's composition). UI for the module is a separate item (`<name>-ui-foldkit`): a screen in the web shell that reads the replica and writes optimistically through the Foldkit adapter, `@eloxiv/client/foldkit` ([ClientSDK](client-sdk.md#ui-bindings)). A module the app writes itself is listed in `eloxiv.json` ([the app's own modules](../cli.md#the-apps-own-modules)); [Getting started](../getting-started.md#5-a-module-of-your-own) builds one. The [Sync](sync.md#generated-tables) contract describes what the generated tables hold.
87
+
88
+ ## Optimistic effects
89
+
90
+ An action may declare the change it predicts on a client's replica (decision "Data"; criterion 6), with the builders `optimistic` exports from `@eloxiv/contracts`. The declaration is derived from the action's own `writes` and `target`:
91
+
92
+ | Effect | Predicts | Declares |
93
+ | --- | --- | --- |
94
+ | `optimistic.insert({ key, values })` | a new record of the `writes` entity | `key`: the input field naming the record's key (the primary key is `recordKey` of it, [Invocation](invocation.md)); `values`: every synced field but the primary key that cannot be empty |
95
+ | `optimistic.update({ set })` | the `target` record (or each one of a target set) with these fields set | `set`: fields of the target's entity |
96
+ | `optimistic.delete()` | the `target` record (or each one) removed | |
97
+ | `optimistic.custom()` | whatever the module's own prediction writes: several rows, a computed field, a counter, a move between parents | nothing more; the module's `predictions.ts` exports a function named like the action, which may write only the synced tables of the entities the action declares (`writes`, `target`, `actsOn`) ([Sync](sync.md#custom-predictions)) |
98
+
99
+ A field's value is `optimistic.input(field, fallback?)` (the input field's encoded value), `optimistic.actor("userId" \| "orgId")`, `optimistic.now()` (epoch milliseconds, as sync carries instants) or `optimistic.value(json)`.
100
+
101
+ ```ts
102
+ export const greet = defineAction({
103
+ name: "hello.greet",
104
+ input: Schema.Struct({ message: Schema.String, visibility: Schema.optional(Visibility), key: Schema.optional(Schema.String) }),
105
+ output: Schema.Struct({ id: Schema.String, message: Schema.String, visibility: Visibility }),
106
+ writes: "greeting",
107
+ optimistic: optimistic.insert({
108
+ key: "key",
109
+ values: {
110
+ orgId: optimistic.actor("orgId"),
111
+ ownerId: optimistic.actor("userId"),
112
+ message: optimistic.input("message"),
113
+ visibility: optimistic.input("visibility", "org"),
114
+ createdAt: optimistic.now(),
115
+ },
116
+ }),
117
+ })
118
+ ```
119
+
120
+ `load` refuses an effect that cannot predict what it says (`optimisticProblems`): an insert without `writes` or an update or delete without `target`; an entity that does not sync; a field it sets that the entity does not sync, or its primary key; an insert that leaves out a field that cannot be empty; an input field the input does not have; `now()` for a field that is not a number; a custom prediction for an action that declares no entity, or only entities that do not sync; a read-only action. `eloxiv generate` writes each module's mutators from these declarations into its `sync.gen.ts` ([Sync](sync.md#optimistic-writes)), wiring in the module's own prediction for a custom one ([Sync](sync.md#custom-predictions)); the prediction runs only on the replica. The server runs the action's handler, as for any call, and the replica keeps the server's answer.
121
+
122
+ ## App configuration
123
+
124
+ What an app's own server code needs from the deployment (an endpoint, a switch, a key for a service of its own) is declared once, beside its modules, with `defineAppConfig` (`@eloxiv/kernel`) and given to the kernel as `KernelApp.config`:
125
+
126
+ ```ts
127
+ export const config = defineAppConfig({
128
+ searchUrl: { description: "the search service's URL", schema: Schema.String, env: ["APP_SEARCH_URL", "SEARCH_URL"] },
129
+ pageSize: { description: "a number", schema: Schema.FiniteFromString, env: ["APP_PAGE_SIZE"], default: 25 },
130
+ searchKey: { description: "the search service's key", schema: Schema.String, env: ["APP_SEARCH_KEY"], secret: true },
131
+ })
132
+ // in app code: const { searchUrl, pageSize, searchKey } = yield* appConfig(config)
133
+ ```
134
+
135
+ - Each field is read from the first of its variables that is set (non-empty), so a renamed variable keeps working under its old name as an alias; its schema decodes the string; with none set it takes its default, and a field without a default is required. Two fields may not read the same variable.
136
+ - It is resolved once, as the kernel starts. A required field not set, or a value its schema refuses, stops the start with every problem at once, each naming the field and its variables, never a value. A `secret` field's value is `Redacted`.
137
+ - App code reads the values with `appConfig(definition)` (the `AppConfig` service), typed by the declaration; asking with another definition than the app was started with is a defect. `resolveAppConfig(definition, env)` resolves without a kernel (for a script or a test) and also says where each value came from (`sources`: a variable, the default, or missing).
138
+ - The kernel's own configuration (`ELOXIV_*`) is separate. Modules' scoped values are [Settings](settings.md), declared in their manifests; the app's configuration is the deployment's, not changed at run time.
139
+
140
+ `packages/kernel/test/app-config.test.ts` proves aliases, defaults, decoding, redaction, the problems that stop a start and typed access.
141
+
142
+ ## Operations
143
+
144
+ ### `emit`
145
+
146
+ Input `{ module }`, output the module's `ModuleManifest` document. In TypeScript this is `moduleToJson(contract)`. Every schema-typed field (action input, output and result, event payloads, entity rows, setting schemas, query-view rows) is a JSON Schema (draft 2020-12) document. A published query view also gives `view`, the database view the kernel creates for it (`<schema>.qv_<name>`). Unknown keys are allowed, so later declarations extend the document compatibly.
147
+
148
+ ### `load`
149
+
150
+ Input: the manifests of every module of one app. Output: the loaded module names, or the error `InvalidManifest` with `problems`, every problem found, each naming the module and the declaration. In the kernel this is `Registry.layer(modules)`; a refusal stops the kernel at startup with a message such as:
151
+
152
+ ```
153
+ InvalidManifest: The app's module manifests are invalid:
154
+ - notes: contribution notes.besideGreetings contributes to slot hello.toolbar, which does not exist
155
+ - hello: query view hello.greetings is not a plain SELECT over schema hello: it reads notes.note, outside the module's schema hello
156
+ ```
157
+
158
+ The kernel also refuses an app's durable work before setup or any service starts (`checkApp`, the same `InvalidManifest` listing every problem together with the manifest problems above): workflow names (the kernel's built-ins, the app's and its modules') must be unique, and every event trigger (the app's, and its modules' namespaced `<module>.<id>`) must have a unique id, start a workflow the app defines and listen for an event type an installed module declares. A module's workflows are named `<module>.<name>`, and its triggers and ingress sources start only its own workflows: a module's work runs, and reports progress, as its module.
159
+
160
+ The checks (`manifestProblems` in `@eloxiv/contracts`, plus the kernel's own):
161
+
162
+ - module names, Cedar namespaces, entity types, tables, action names and view routes are unique across the app;
163
+ - a module's name is a lower-case identifier of at most 52 characters (its database roles, `eloxiv_mod_<name>` and `eloxiv_own_<name>`, stay within PostgreSQL's 63 bytes), and not `eloxiv`, `eloxiv_*` or `pg_*`; in the kernel, its schema (by default its name) is one no other module uses, never PostgreSQL's (`pg_*`, `information_schema`), `public`, Better Auth's `auth` or the kernel's (`eloxiv`, `eloxiv_*`; only the kernel's own modules have `eloxiv_<name>`), nor zero-cache's (`<app id>` and `<app id>_<n>` for the app id zero-cache runs with, `ELOXIV_ZERO_APP_ID`, default `zero`; setup refuses an app id that names the kernel's schemas, `auth`, `public` or PostgreSQL's, where zero-cache would put its own objects), and every entity's table is in it ([Release](release.md), guarantee 2);
164
+ - every declaration id is namespaced by its module;
165
+ - every reference resolves: an action's `writes`, `target` and `actsOn` entities, a permission's actions, a view's entity or query view, a contribution's slot, view or command (and the slot accepts that kind), a command's action or view, a work-item source's entity, fields and view, a resolver's entity, field and view, a query view's entity;
166
+ - a best-effort action has a target and the completion fields in its output; an organisation-wide action declares an entity;
167
+ - no policy reaches further than its action's declared entities (kernel): for every action, on each entity it declares, for `read` on every entity, and for `share` on every entity with a sharing attribute, the compiled filter must tie every record it admits to the actor, through the actor's organisation (`resource.org == principal.org`), a user field equal to the actor (`resource.owner == principal`), a sharing grant to the actor, or a grant to one named user (`principal == Eloxiv::User::"x"`). A filter that some record of another organisation, owned by someone else and shared with no one, could satisfy (an unconstrained resource, or one constrained only by group, role or permission tests, by membership of a group a record names, or by literals) is refused, unless the action is `organisationWide`, which needs the entity to have an organisation column;
168
+ - an approval rule applies to an installed action, its comparisons are well formed (`gt`, `gte`, `lt`, `lte` against numbers, `in` against a list, `exists` against a boolean, non-empty field paths) and its id is namespaced; the kernel also requires the inbox modules when there are rules or consent-marked actions, and refuses rules on the decisions themselves (`approvals.*`, `consent.*`);
169
+ - a setting's scope is known, its default is JSON that decodes against its schema, and its schema is not marked sensitive (annotated `sensitive: true` or `writeOnly: true`, a `password` format, or an Effect `Redacted`, anywhere inside it);
170
+ - a flag has a description and a boolean default;
171
+ - every published query view's relation on the query surface (`<module>_<view>`) is unique across the app and does not start with `pg_`; no module is named `eloxiv` (the kernel's own name);
172
+ - a skill has exactly one of text or path, and a path (and its evals path) stays inside the module's directory; the kernel also checks the file exists; its `audience`, if given, is `runtime`, `development` or `both`;
173
+ - every entity's table is in the module's own schema (kernel);
174
+ - every action has a handler (kernel);
175
+ - every permission a policy tests with `principal.permissions.contains(...)` is declared by some module or the kernel (kernel);
176
+ - the policies validate against the Cedar schema generated from the manifests, in strict mode (kernel);
177
+ - a job (the Scheduler contract's `jobs`) has a description, a cron or interval schedule the scheduler can evaluate (kernel), a known catch-up policy and the `system` identity, and invokes an installed action with input that action decodes;
178
+ - the ids durable work is recorded under are unique (kernel): module names, subscription ids (which may not start with `trigger:`), and job ids (non-empty, no `:`);
179
+ - a published query view is one plain `SELECT` over the module's schema: one statement, no comments, no `WITH`, `INTO`, `FOR` (locking) or data-changing keyword, every table written as `<schema>.<table>` in the module's schema (including comma joins and subqueries), subqueries only as `(SELECT ...)` or `(VALUES ...)`, no schema-qualified or quoted function names and no functions with side effects or that run SQL from text (`set_config`, `pg_*`, `nextval`, `query_to_xml`, ...). This lexical check is only a first filter and is conservative: it refuses some valid SQL (`IS DISTINCT FROM`, `EXTRACT(x FROM y)`, `SUBSTRING(x FOR n)`) rather than risk accepting something unsafe. Setup then checks what the created view really calls (see Guarantees). Its row must include the entity's primary-key column.
180
+
181
+ ## Records
182
+
183
+ All in the published schema's `types`: `ModuleManifest`, `Entity`, `Action`, `Event`, `Permission`, `Setting`, `Flag`, `Skill`, `View`, `Slot`, `Contribution`, `Command`, `WorkItemSource`, `EntityResolver`, `QueryView`, `ApprovalRule`.
184
+
185
+ ## Errors
186
+
187
+ `InvalidManifest { problems: string[] }` from `load`. `emit` does not fail.
188
+
189
+ ## Guarantees
190
+
191
+ - An app whose manifests have any problem does not start: the kernel never serves a registry with a dangling reference.
192
+ - The JSON a manifest emits decodes against the published `ModuleManifest` schema.
193
+ - Published query views are created by setup as `security_invoker` views owned by the module's owner role, readable (`SELECT` only) by its runtime role, so the tables' row-level security, including the entity's read policy, applies to every reader. Setup checks Postgres's own record of each view as well: it may read only tables of the module's schema (including the entity's table; never another view, a materialised view or a foreign table, whose own query or source this check does not see) and must return exactly the declared columns; every value it produces or reads (each expression's result, every column it reads and the fields of every row type) must be of an allowed type: a built-in on the type allowlist (booleans, text, numbers, dates and times, `uuid`, `json`, `jsonb`, `bytea` and their arrays), `record` or `unknown`, or an enum or table row type of the module's schema, made only of allowed types, that no cast involves. Postgres converts values by type where the query tree shows no call (`to_json` and `to_jsonb` use a cast to `json` for a type that is not built in; `format`, `||` and record and array output call each element's output function), so a module type with a cast of its own could otherwise run the module's code; domains (whose checks run on conversion), ranges, other schemas' types and other composite types are refused. Every callable in the view's stored query tree (`pg_rewrite`, where quoted, schema-qualified and upper-case names, casts, operators, `IN`, `IS DISTINCT FROM`, sorting and grouping, and calls inside subqueries and CTEs are all resolved to the function they run) must be on an allowlist: `pg_catalog` functions that are immutable or stable and named on a list of side-effect-free built-ins (comparison, string, numeric, date and time, JSON and array helpers, aggregates, window functions), built-in casts between allowed types, `pg_catalog` operators whose functions are immutable or stable built-ins, and text coercions to allowed types. Anything else is refused, including every `pg_catalog` function not on the list (`set_config`, `current_setting`, `query_to_xml` and the other SQL-from-text functions, `pg_*` administration functions), volatile functions, functions and operators outside `pg_catalog`, and XML, SQL/JSON, domain-coercion, sequence, table-sample and row-locking nodes. Any failure stops setup ([`QueryViewCheck.ts`](../../packages/kernel/src/db/QueryViewCheck.ts)). Independently of views, setup refuses a module whose migrations leave a cast to or from a type of its schema, or through one of its functions (Postgres would run it wherever it converts such a value, including inside the kernel's own functions: the write log runs `to_jsonb` on every written row), a foreign table, a base type with its own input and output functions, or default privileges. A module's migrations run on a session that logs in as its owner role, so they cannot gain any privilege beyond it; setup's checks run again on its own session, which no migration touched, and read the catalogue by qualified names with `pg_temp` last on the search path (see [Release](release.md), guarantee 2). Views are dropped before module migrations run and created again after hardening, so migrations can change the tables they read.
194
+ - Views are read in a read-only scope: `QueryViews.read` (the kernel's reader for callers) and a handler's `ctx.queryView` select as the module's runtime role inside a savepoint where the transaction is read-only, rolled back afterwards, so even an allowlisted function cannot write and any setting a read changed is undone. A handler that selects from a view with plain SQL in a read-write action runs in the action's transaction; the setup allowlist is what keeps the view free of side effects there.
195
+
196
+ ## Implementing it
197
+
198
+ Another implementation (for example a manifest checker in another language, or a different kernel) reads manifests in the JSON form above and applies the checks listed under `load`. It must refuse each class of invalid manifest the conformance kit exercises and accept the kit's valid app.
199
+
200
+ ## Running the conformance kit
201
+
202
+ ```ts
203
+ import { moduleManifestConformance } from "@eloxiv/testing/conformance/ModuleManifest"
204
+
205
+ moduleManifestConformance({
206
+ // Resolve if the app is accepted; reject with an error naming the problem if it is refused.
207
+ load: async (modules) => { /* build your registry from `modules` */ },
208
+ // The module's manifest as JSON.
209
+ emit: (module) => moduleToJson(module.contract),
210
+ })
211
+ ```
212
+
213
+ The kit supplies a valid two-module app that uses every declaration and one mutation of it per class of invalid manifest, and checks each refusal names what is wrong. The kernel runs it in [`packages/testing/test/conformance-manifest.test.ts`](../../packages/testing/test/conformance-manifest.test.ts).
@@ -0,0 +1,90 @@
1
+ # NotificationChannel
2
+
3
+ How a notification reaches a person outside the app: a channel delivers one rendered message to one recipient and says whether a failure is worth retrying. [Notifications](notifications.md) decides which channels a notification goes to, records every attempt in the delivery log and retries through the outbox.
4
+
5
+ - Kind: kernel service. Version 1.1.0 (1.1.0: the kernel's push channel over APNs and FCM; `PushMessage` gains the notification's organisation, id, category, record link and an optional decision; `ChannelError.retryAfterMs`).
6
+ - Schema: [`packages/contracts/schema/contracts/NotificationChannel.json`](../../packages/contracts/schema/contracts/NotificationChannel.json) (source [`NotificationChannel.ts`](../../packages/contracts/src/contracts/NotificationChannel.ts)).
7
+ - Implementation: `NotificationChannelImpl` and `emailChannel` in [`packages/kernel/src/Notifications.ts`](../../packages/kernel/src/Notifications.ts); the SMTP client in [`notifications/Smtp.ts`](../../packages/kernel/src/notifications/Smtp.ts); the push channel in [`notifications/Push.ts`](../../packages/kernel/src/notifications/Push.ts) over the APNs and FCM clients in [`notifications/Providers.ts`](../../packages/kernel/src/notifications/Providers.ts).
8
+ - Kit: `@eloxiv/testing/conformance/NotificationChannel` ([source](../../packages/testing/src/conformance/NotificationChannel.ts)): `emailChannelConformance`, run by [`packages/testing/test/notification-channel.test.ts`](../../packages/testing/test/notification-channel.test.ts) against a real SMTP server on a local port, and `pushConformance` ([source](../../packages/testing/src/conformance/Push.ts)), run by [`packages/testing/test/push.test.ts`](../../packages/testing/test/push.test.ts) against the APNs and FCM protocol fakes ([`ApnsFake.ts`](../../packages/testing/src/fakes/ApnsFake.ts), [`FcmFake.ts`](../../packages/testing/src/fakes/FcmFake.ts)).
9
+
10
+ ## Kinds
11
+
12
+ | Kind | Provided by | Message |
13
+ | --- | --- | --- |
14
+ | `in-app` | the notification record itself (no delivery) | the `Notification` |
15
+ | `email` | the kernel, over SMTP (`ELOXIV_SMTP_URL`) | `EmailMessage`: `messageId`, `from`, `to`, `subject`, `text`, `html`, `unsubscribeUrl`, `headers` |
16
+ | `push` | the kernel, over APNs and FCM HTTP v1 (`ELOXIV_APNS_*`, `ELOXIV_FCM_*`), to the installations people register ([Notifications](notifications.md#push)) | `PushMessage`: `messageId`, `userId`, `orgId`, `notificationId`, `category`, `title`, `body`, `url`, `link` (a [View](view.md) `DeepLink` or null), `decision?` (`kind`, `requestId`, `verdicts`, `expiresAt`) |
17
+ | `chat` | Messaging (contract only) | `ChatMessage`: `messageId`, `destination`, `text`, `url` |
18
+
19
+ A host registers a channel with `KernelOptions.channels` (`{ kind, deliver }`); a registered `email` or `push` channel replaces the kernel's. Only the kernel's push channel mints decision tokens.
20
+
21
+ ## Operation
22
+
23
+ ### `deliver`
24
+
25
+ | | |
26
+ | --- | --- |
27
+ | Input | `ChannelMessage` (one of the kinds above) |
28
+ | Output | `Delivered`: `providerId` (the server's queue id, a push ticket), or null |
29
+ | Errors | `ChannelError`: `channel`, `retryable`, `message`, `retryAfterMs?` (the provider's `Retry-After`) |
30
+
31
+ Succeeds once the channel accepted the message (for push: at least one installation accepted it and none waits for a retry). The same `messageId` may be delivered again after a crash; channels pass it on (`Message-ID` for email, `apns-id` for APNs) so the receiving side can drop duplicates. A retryable failure with `retryAfterMs` is retried no sooner than that, counted from the outbox's clock after the attempt (the outbox's backoff or the advice, whichever is later; at most a day). The push channel computes it from the time each provider allowed, read when its answer arrived, never shortened; when a provider asks one installation to wait longer than a day, the push channel ends that installation's send (`failed`, saying so) rather than send before the provider allows, and the delivery is decided by the other installations' answers (an acceptance still counts; with none, a permanent failure).
32
+
33
+ ## The email channel
34
+
35
+ One SMTP connection per message: greeting, `EHLO`, optional `AUTH PLAIN`, `MAIL FROM`, `RCPT TO`, `DATA` (dot-stuffed, CRLF), `QUIT`, over TCP (`smtp://`) or implicit TLS (`smtps://`). The message is MIME: `From`, `To`, `Subject` (RFC 2047 encoded when not ASCII), `Date`, `Message-ID`, `List-Unsubscribe` and `List-Unsubscribe-Post` when there is an unsubscribe URL, the message's extra headers, and a base64 `text/plain` part (with a `text/html` alternative when there is HTML).
36
+
37
+ Failures: a connection that cannot be made, a timeout or a 4xx reply is retryable; a 5xx reply (a refused recipient, a rejected message) is permanent; a message of another kind is permanent.
38
+
39
+ Nothing a caller supplies reaches the protocol or the header block unchecked; what fails a check is refused, permanently, before any connection is made:
40
+
41
+ - **Envelope addresses** (the `From` and `To` addresses, also given as `Name <address>`) must be RFC 5321 mailboxes: printable ASCII only (no CR, LF, NUL or other controls; no SMTPUTF8), a dot-string or quoted-string local part of at most 64 octets, a domain of valid labels (at most 63 octets each, 255 in all) or an IPv4/IPv6 address literal, and at most 254 octets in all. A display name with controls is refused; one with specials is quoted, a non-ASCII one encoded.
42
+ - **Extra headers** need RFC 5322 field names (printable ASCII without `:`) and may not add a header the channel writes itself (`From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Sender`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Content-Type`, `Content-Transfer-Encoding`). Values lose line breaks (to spaces) and other controls; non-ASCII values and subjects are RFC 2047 encoded words of at most 75 characters, folded, and no line exceeds 998 characters. The `Message-ID` must be printable ASCII without `<`, `>` or spaces.
43
+ - **Bodies** are base64, so their content never reaches the protocol; the DATA section is dot-stuffed with CRLF endings. The `EHLO` name must be a domain; `AUTH PLAIN` credentials are base64.
44
+
45
+ ## The push channel
46
+
47
+ Installed when the deployment configures a provider: APNs with `ELOXIV_APNS_KEY` (the `.p8` key's PEM; `\n` in a one-line value is read as a line break), `ELOXIV_APNS_KEY_ID` and `ELOXIV_APNS_TEAM_ID` (optionally `ELOXIV_APNS_ENDPOINT`, default `https://api.push.apple.com`, and `ELOXIV_APNS_SANDBOX_ENDPOINT` for installations registered as `sandbox`, default `https://api.sandbox.push.apple.com`); FCM with `ELOXIV_FCM_SERVICE_ACCOUNT` (the service account's JSON key; optionally `ELOXIV_FCM_PROJECT_ID`, default the key's `project_id`, `ELOXIV_FCM_ENDPOINT` and `ELOXIV_FCM_TOKEN_ENDPOINT`). Or `KernelConfig.push` (`{ apns?, fcm? }`; `apns.ca` trusts a further CA, for a test or a proxy). A provider without configuration is not installed: installations of it are skipped and logged.
48
+
49
+ One `deliver` sends the notification to every live installation of the recipient (registered from a session still in force, its token not reported dead), up to four at a time. Each send is claimed just before it goes out, in a transaction of its own that reads the installation again: still the recipient's, the same registration (`generation`), its session valid and not revoked, the recipient still a member of the notification's organisation. It records the attempt (`sending`) and the decision token's hash, bound to that session and generation. A send that no longer stands is skipped: a device signed out, reassigned to another person, or registered again while the delivery waited gets nothing. What a provider has accepted is past the kernel's reach. Neither client follows a redirect (a redirect is a configuration failure, retried); concurrent sends share one provider-token signing (APNs) or access-token exchange (FCM).
50
+
51
+ - **APNs**: HTTP/2 over TLS (`node:http2`), one connection per endpoint, reused; a GOAWAY, an error or a closed connection opens a new one. `POST /3/device/<token>` with `authorization: bearer <provider token>` (ES256 JWT: `kid` the key id, `iss` the team id, `iat`; reused for 50 minutes, signed again sooner when APNs says it expired), `apns-topic` (the installation's app id), `apns-push-type: alert`, `apns-priority: 10`, `apns-id` (a UUID derived from the delivery and installation, the same on every retry), `apns-collapse-id` (the notification's id). Body: `{ aps: { alert: { title, body }, category? }, eloxiv: { notificationId, orgId, userId, installationId, category, link, decision? } }`; `aps.category` is `eloxiv.decision` when a decision is offered.
52
+ - **FCM HTTP v1**: `POST /v1/projects/<project>/messages:send` with an access token the service account's RS256 assertion (`iss` the account, `scope` `https://www.googleapis.com/auth/firebase.messaging`, `aud` the token endpoint, an hour at most) is exchanged for (`grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer`), kept until a minute before it expires. Body: a data-only message at high priority, `{ message: { token, android: { priority: "high" }, data: { tag, title, message, body, channelId, categoryId?, eloxiv } } }`, in the fields expo-notifications reads from a data message (its custom-provider format), so the app draws the notification itself, also in the background, with the decision category's Approve and Reject buttons (a `notification` message is drawn by the system tray, without buttons): `title`, `message` (the text), `body` (`{ "eloxiv": <the same object> }` as JSON, which becomes the notification's data in the app), `channelId` (`default`, the Android channel the registry's Expo host makes), `categoryId` (`eloxiv.decision`, only when a decision is offered) and `eloxiv` (the same object, JSON, for a receiver that reads the data as it comes). Every value is a string. The notification's id is its `tag` (expo-notifications' notification identifier: a copy sent again, after an uncertain answer, replaces the one still shown). There is no `collapse_key`: FCM keeps at most four collapse keys per device while it is offline, so a key per notification would drop distinct requests.
53
+
54
+ Both payloads' `eloxiv` names the recipient (`userId`) and the installation it was sent to (`installationId`, the app's own id as it registered), so the app opens or decides it only for that person signed in on that install. `eloxiv.decision` is `{ kind, requestId, verdicts, token? }`. `token` is sent to **APNs installations only**: an FCM payload's data reaches the posted Android notification's extras (readable by apps with notification access) and debug logs, so an Android app's Approve and Reject open the app, which decides through the person's own session; no token is minted for an FCM installation. An APNs installation's token is its single-use token for the notification's decision (an HMAC of the delivery, the installation and its registration's generation under the deployment's secret, so a retry to the same registration sends the same one; stored only as its SHA-256), redeemed at `POST /api/notifications/decide` ([Notifications](notifications.md#decisions-from-a-notification)). Only the kernel's own approval and consent producers offer a decision, and its title and body come from the request (`Approval needed: <title>`, `<requester> asked for your approval.`; `Your agent wants to: <title>`, where `<title>` is what people see the action called, as recorded with the request when the call was held; "Open the app to review the details."), never from what a notification's sender wrote. The body is at most 1,000 characters; a consent request's body is the fixed text "Open the app to review the details." (never the call's input). Each provider payload is fitted to 4,096 bytes of JSON: the body is shortened first (whole characters), then the title; when no text fits, the link and then the category are left out and the text fitted again; a payload that still does not fit is never sent (that installation's send is refused, the reason recorded); a record id longer than a `DeepLink`'s 500 characters gets no link.
55
+
56
+ Each installation's answer is recorded at once, on a connection of its own (`eloxiv.push_delivery`: `sending` before the request, then `sent`, `failed`, `retrying` or `uncertain`, attempts, the reason). A retry of the delivery sends only to installations with no state, or with `retrying`, `uncertain` or `sending` (the answer was lost, or the process stopped mid-send). It never sends to one that accepted (`sent`) or was refused for good (`failed`):
57
+
58
+ | Answer | Classified | Effect |
59
+ | --- | --- | --- |
60
+ | APNs `200`; FCM `200` naming the message completely (`projects/<p>/messages/<id>`) | accepted | the provider's id (`apns-id`, the message `name`) |
61
+ | APNs `410`, `400 BadDeviceToken`/`DeviceTokenNotForTopic`; FCM's structured `UNREGISTERED` with its `404` | dead token | only the registration that was sent (the same generation) is invalidated; after an APNs `410` only if its `timestamp` is newer than that registration (written by the clock after its lock waits, a first registration too); an answer with no usable date (FCM's, an APNs `410` without a `timestamp` or with a malformed one) only while that registration is unwritten since it was sent (registered again, even unchanged, it stays) |
62
+ | APNs `403` (provider token), FCM `401` (whatever its body) or `403` other than `SENDER_ID_MISMATCH`, the token endpoint refusing | the deployment's credentials | retryable (a new provider or access token next time), after the token endpoint's `Retry-After`; the device is not blamed |
63
+ | `429`, `5xx`, a connection that could not be made, GOAWAY | throttling, outage | retryable, after `Retry-After`; an FCM `429` without one after a minute (FCM's minimum back-off); read from the status and headers, whatever the body |
64
+ | a timeout or a stream lost after the request was sent; FCM `200` not naming a message | uncertain | retried: sent again, at least once |
65
+ | an FCM answer that is not FCM's structured error (a wrong endpoint's or a proxy's page, a generic `404`), FCM's structured `404` naming no device (`UNREGISTERED`), a redirect | endpoint or protocol failure | retryable; the installation stays active |
66
+ | any other `4xx` (a refused payload, `SENDER_ID_MISMATCH`, `INVALID_ARGUMENT`) | refused | permanent for that installation, not invalidated |
67
+
68
+ An answer sent again after it was lost is a second copy for the provider: APNs collapses copies with the same `apns-collapse-id` (the notification's id); an FCM copy replaces a visible one by its `tag`, and a client that presents notifications itself drops a `notificationId` it already showed (a copy the person already dismissed can show again while the app is in the background). The delivery then fails retryably while any installation is to be retried, no sooner than the latest time a provider allowed. It succeeds when at least one installation accepted, in this attempt or an earlier one (also if the others are gone by the retry). It fails permanently when the recipient has no installation, none uses a configured provider, or every one refused it. What the records keep is the kernel's own text: a provider's documented code (APNs's `reason`, FCM's `FcmError` code or status) or the HTTP status alone, never the provider's free-form text or a transport's or the database's message. Nothing a message or log carries includes a device token or a credential.
69
+
70
+ ## Records
71
+
72
+ `ChannelKind`, `EmailMessage`, `DecisionVerdict` (`approve`, `reject`), `DecisionKind` (`approval`, `consent`), `PushDecision`, `PushMessage`, `ChatMessage`, `ChannelMessage`, `Delivered`, `ChannelError`, and the delivery log's `DeliveryRecord` (`id`, `orgId`, `notificationId`, `recipientId`, `channel`, `address`, `status` (`pending`, `sent`, `failed`, `suppressed`), `attempts`, `lastError`, `providerId`, `createdAt`, `sentAt`).
73
+
74
+ ## How an implementation is checked
75
+
76
+ `emailChannelConformance(start)` takes a subject that delivers through the channel to an SMTP server it controls: a message arrives with its envelope, every header (including a non-ASCII subject), and both bodies intact; a text-only message keeps lines that start with a dot and has no unsubscribe header; a temporary failure (451) is retryable and the retry arrives; a refused recipient (550) is permanent; an unreachable server is retryable; a push message given to the email channel is refused, permanently.
77
+
78
+ The kernel runs it in `packages/testing/test/notification-channel.test.ts` with [`startSmtpSink`](../../packages/testing/src/SmtpSink.ts), a real SMTP server over `node:net` (on Bun and Node).
79
+
80
+ `pushConformance(start)` (also exported from the NotificationChannel kit) takes a kernel subject whose push channel points at the APNs fake (a real `node:http2` TLS server with a certificate from an in-memory test CA, verifying each provider token's ES256 signature, key id, team and age, the topic and the payload's size) and the FCM fake (verifying the service account's RS256 assertion and issuing access tokens; `messages:send` with FCM's structured errors). It checks, besides the installations ([Notifications](notifications.md)): the APNs payload and headers exactly, with the record's link chosen from the installed views and none when no view shows it, one provider token for several sends; the FCM message (data-only, high priority, no collapse key, expo-notifications' fields, `data.eloxiv` and `data.body`, the recipient and installation) and the decision category on a consent push, one access token; push added to a person's channels without replacing them (`setPreference` with `add`); a consent request's input never in the payload; a retry after a `503` and a `500` sends again only to the installation that failed (the other got one copy); a `429` with `Retry-After: 2` is retried no sooner than two seconds later; APNs `500`/`503` and FCM `429` retried, the device not blamed; APNs `ExpiredProviderToken` and revoked FCM access tokens retried with new credentials; dead tokens (APNs `410`, FCM `UNREGISTERED`) invalidate their installations, which get nothing more; an installation whose token changed while APNs answered for the old one is not invalidated; a refused payload fails only that installation, without invalidating it, and is not sent to it again while another installation retries; an earlier acceptance stands when the other installations are gone by the retry; a provider asking one installation to wait longer than a day fails only that installation, and another's acceptance delivers; a GOAWAY moves the next request to a new connection. It also checks that each send is recorded (`sending`) before the provider answers; that an installation signed out while earlier sends of the delivery waited gets nothing, nor does a recipient who left the organisation before a retry; that a `Retry-After` counts from when a slow answer arrived, and the token endpoint's is honoured; that a provider's free-form text naming a device token reaches no record; that an APNs `410` older than the registration, about a first registration whose write waited for a lock (dated after the verdict), or about a registration the app corrected meanwhile, invalidates nothing, nor does one without a usable `timestamp` about a registration made again meanwhile; that a payload is fitted to 4 KiB and an over-long record id gets no link; that many people registering one token at once all succeed and one row holds it; and that a 4,096-character token registers. Run by `packages/testing/test/push.test.ts` on Bun and Node. The clients alone are checked by `packages/testing/test/push-providers.test.ts`: no redirect is followed (the OAuth assertion and the message never reach the redirect's target), an FCM page that is not FCM's answer neither invalidates nor counts as accepted, an FCM quota refusal waits a minute (a plain `429` too) and a plain `503` keeps its `Retry-After`, a `401` of any body fetches a new access token, only a complete message name is accepted and a `404` naming no device is retried, provider codes are recorded only as the kernel's constants, concurrent first sends share one credential, and a payload whose category alone passes 4 KiB is sent without it (one that cannot fit is not sent). These are protocol fakes, not Apple's or Google's services.
81
+
82
+ ## Not yet guaranteed
83
+
84
+ - **STARTTLS** is not supported (use `smtps://` or a local relay); only `AUTH PLAIN`.
85
+ - Chat has no implementation in the kernel; its kit will run against Messaging's.
86
+ - Push is proven against protocol fakes; delivery through Apple's and Google's services with real credentials is the deployment's to check. Web Push (a browser's subscription) has no sender: the push channel delivers to APNs and FCM installations only.
87
+ - Payloads are fitted to 4,096 bytes of the payload's JSON, which is at least what either provider counts (FCM counts keys and values only).
88
+ - A send whose answer was lost is sent again (at least once): deduplicated by APNs's collapse id; an FCM copy replaces a visible one by its tag, and clients that present notifications themselves drop a repeat (a copy dismissed in the background can show again).
89
+ - Android gets no decision token: its Approve and Reject open the app, which decides through the person's session. One-press decisions from the lock screen are iOS only.
90
+ - One connection per message (no pooling).
@@ -0,0 +1,123 @@
1
+ # Notifications
2
+
3
+ Durable notifications per recipient: in-app records each person reads, marks and dismisses (synced to their replica), delivered through channels ([NotificationChannel](notification-channel.md)) by category, according to each person's preferences, with retries and a delivery log. System email uses registered templates with variables, per-organisation overrides, preview, a one-click unsubscribe link and suppression.
4
+
5
+ - Kind: kernel service. Version 1.3.0 (1.1.0: the `list`, `count` and `notify` actions, a person's own notifications read and sent from any surface; 1.2.0: push installations (`registerInstallation`, `unregisterInstallation`), push delivery through the kernel's channel, and decisions from a notification (`decide`); 1.3.0: the kernel's consent and approval texts name the action by its title (`Your agent wants to: <title>`, `Approval needed: <title>`; `approvals.decided` leads with the outcome, `{{status}}: {{action}}`, and never shows an error tag), in-app, by push and in email, where `{{action}}` is now the title and `{{actionName}}` the id; the push installation actions are offered on no agent surface).
6
+ - Schema: [`packages/contracts/schema/contracts/Notifications.json`](../../packages/contracts/schema/contracts/Notifications.json) (source [`Notifications.ts`](../../packages/contracts/src/contracts/Notifications.ts)).
7
+ - Implementation: [`packages/kernel/src/Notifications.ts`](../../packages/kernel/src/Notifications.ts); the kernel-provided `notifications` module ([`inbox/notifications.ts`](../../packages/kernel/src/inbox/notifications.ts), schema `eloxiv_notifications`).
8
+ - Kit: `@eloxiv/testing/conformance/Notifications` ([source](../../packages/testing/src/conformance/Notifications.ts)), run by [`packages/testing/test/notifications.test.ts`](../../packages/testing/test/notifications.test.ts) with email delivered to a real SMTP server the test starts ([`SmtpSink.ts`](../../packages/testing/src/SmtpSink.ts)); push installations and delivery by `pushConformance` ([`Push.ts`](../../packages/testing/src/conformance/Push.ts), run by [`push.test.ts`](../../packages/testing/test/push.test.ts)); decisions by `decisionTokenConformance` ([`DecisionTokens.ts`](../../packages/testing/src/conformance/DecisionTokens.ts), run by [`decision-tokens.test.ts`](../../packages/testing/test/decision-tokens.test.ts)), both against APNs and FCM protocol fakes.
9
+
10
+ ## Sending
11
+
12
+ From a handler (`ctx.notify.send`, applied with the call's transaction), a subscriber (`ctx.notify.send`, with its delivery), or kernel code (`Notifications.send`):
13
+
14
+ ```ts
15
+ yield* ctx.notify.send({
16
+ recipients: [ownerId], // members of the organisation
17
+ category: "purchases.ordered", // preferences are per category
18
+ title: "Order placed",
19
+ body: `Your order for ${amount} was placed.`,
20
+ link: { module: "purchases", entity: "order", id },
21
+ email: { template: "purchases.receipt", variables: { item, amount } },
22
+ key: `ordered:${id}`, // one notification per (key, recipient)
23
+ })
24
+ ```
25
+
26
+ ## Operations
27
+
28
+ | Operation | Input | Output | Errors |
29
+ | --- | --- | --- | --- |
30
+ | `send` | `SendNotification` | `ids` | `InvalidInput` (a recipient is not a member), `UnknownTemplate` |
31
+ | `list` | action `notifications.list`: `unreadOnly?`, `category?`, `limit?` (1 to 200, default 50) | `notifications`: the caller's own in the organisation they act in, newest first, dismissed ones left out | the standard error set |
32
+ | `count` | action `notifications.count`: `category?` | `unread`: the caller's unread, undismissed notifications | the standard error set |
33
+ | `notify` | action `notifications.notify`: `title`, `body`, `recipients?` (default: the caller), `category?` (default `message`), `link?`, `email?` | `recipients` | `Forbidden` (another recipient without `notifications.send`), `InvalidInput` (a recipient who is not a member) |
34
+ | `markRead` | action `notifications.markRead`: `id` | `id` | the standard error set |
35
+ | `markUnread` | action `notifications.markUnread`: `id` | `id` | the standard error set |
36
+ | `dismiss` | action `notifications.dismiss`: `id` | `id` | the standard error set |
37
+ | `setPreference` | action `notifications.setPreference`: `category`, `channels`, optional `add` (`true`: the channels are added to the person's current ones, email when they never chose, in one write, instead of replacing them) | `id` | the standard error set |
38
+ | `setEmailTemplate` | action `notifications.setEmailTemplate`: `template`, `subject`, `text`, optional `html` (needs `notifications.manage`) | `id` | the standard error set |
39
+ | `preview` | `orgId`, `template`, `variables` | `RenderedEmail` | `UnknownTemplate` |
40
+ | `unsubscribe` | `token` (the link `GET`/`POST /notifications/unsubscribe?token=...`) | `category` | `InvalidInput` |
41
+ | `registerInstallation` | action `notifications.registerInstallation`: `installationId` (a UUID), `provider` (`apns`, `fcm`), `token`, `appId`, `environment?` (`production`, `sandbox`; APNs only, default `production`) | `installationId` | `Forbidden` (anything but the person's own signed-in session), the standard error set |
42
+ | `unregisterInstallation` | action `notifications.unregisterInstallation`: `installationId` | `installationId` | the standard error set |
43
+ | `decide` | `POST /api/notifications/decide { token, verdict }` (not an action) | `DecideResult`: `kind`, `requestId`, `verdict`, `status`, `replayed` | `InvalidDecision` (400), `DecisionExpired` (410), the action's refusal (`Forbidden` 403, `InvalidInput` 409), `RateLimited` (429), `ActionFailed` (503: nothing was decided, try again) |
44
+ | `deliveries` | `orgId`, `notificationId` | the delivery log | none |
45
+
46
+ The actions belong to the kernel-provided `notifications` module: on every surface, authorised by its policy (a notification's recipient alone marks it; a person sets their own preferences; `notifications.manage` overrides templates and reads the delivery log and suppression list of the organisation), and audited.
47
+
48
+ `notifications.notify` is how a person or their agent sends one (an agent's reminder, the result of unattended work): to oneself always, to other members of the organisation only with the `notifications.send` permission. It is sent with the call (idempotent on the call), delivered like any other, and as system email (the `notifications.message` template) only when `email` is true and the recipient's preferences include email.
49
+
50
+ ## Delivery
51
+
52
+ `send` writes, in one transaction: one notification per recipient (the durable in-app record; with a `key`, a second send for the same recipient is skipped), and for every other channel the recipient's preference for the category names (default: `email`), a delivery in the delivery log plus an outbox event `notifications.deliver`. The kernel delivers each event through its channel (a kernel reaction run by the outbox dispatcher, see [Outbox](outbox.md)):
53
+
54
+ - accepted: the delivery is `sent`, with the provider's id and the attempt count;
55
+ - a retryable failure (a 4xx SMTP reply, an unreachable server): the delivery fails, so the outbox retries it with backoff, up to 8 attempts, then records it `failed`;
56
+ - a permanent failure (a 5xx reply, a refused recipient): recorded `failed` at once;
57
+ - an address suppressed for the category (or all categories): recorded `suppressed`, never sent.
58
+
59
+ Delivery is at least once: a kernel that dies after the server accepted a message and before the delivery was recorded sends it again, with the same `Message-ID` (`<delivery id>@eloxiv`), so mail systems can drop the duplicate.
60
+
61
+ In-app is always kept (it is the notification); preferences choose the other channels (`email`; `push` when the deployment configured a push provider). An empty list keeps a category in-app only.
62
+
63
+ ## Push
64
+
65
+ A person's app installation registers its native APNs or FCM token with `notifications.registerInstallation` (never a relay service's token), from the person's own signed-in session: an agent (agent tools, MCP, an agent session), an API token, an OAuth grant and a device are refused. Installations are the person's across organisations (`eloxiv.push_installation`), one per `installationId` (the app install's stable id): registering it again replaces the token, app id and environment (rotation) and binds it to the calling session; when anything of it changed, it is a new registration (its `generation`), and decision tokens sent to the old one no longer redeem. A token is in one installation at a time: registered again anywhere (by anyone), it leaves where it was; registrations of one token are serialised, so many at once all succeed and the last one holds it. Tokens up to the contract's 4,096 characters register (uniqueness is kept on the token's SHA-256). Signing out of the registering session, or the kernel revoking it, deletes the installation at once (database triggers), so no device keeps receiving after its sign-out; erasure deletes every installation of the person; `unregisterInstallation` deletes one. Registration is audited (provider and app id, never the token).
66
+
67
+ A notification whose recipient's preference for its category includes `push` is delivered by the kernel's push channel to every live installation ([NotificationChannel](notification-channel.md#the-push-channel)), carrying the notification's organisation, id and category, and `link`: the [View](view.md) deep link that opens the notification's record, chosen as `recordLink` chooses (the first installed view, in module order then id, that shows the record's entity, in the notification's organisation), or null when no view shows it. A host writes the link out on its own origin or scheme. A consent request's body is replaced by fixed text: the lock screen never shows the call's input. A send is skipped when, as it is claimed, the installation is no longer the same registration of the recipient under a valid session, or the recipient is no longer a member of the organisation.
68
+
69
+ ## Decisions from a notification
70
+
71
+ The kernel's own approval and consent notifications offer a decision by push (`aps.category`, or FCM's `categoryId`, `eloxiv.decision`, and `eloxiv.decision = { kind: "approval" | "consent", requestId, verdicts: ["approve", "reject"], token? }`), and only while their request is pending. The token goes to **APNs installations only**: an Android notification's data reaches its posted extras (readable by apps with notification access) and debug logs, so an FCM payload offers the decision without one. An Android notification action never decides by itself (another app with notification access can invoke it): Approve or Reject opens the exact request in the app with that verdict preselected, and the decision is sent only when the person confirms it there, through their own session with the same actions, after checking the signed-in person, the installation and the organisation (the one the app opened the request in, and the generation it was shown for) against the payload's `userId`, `installationId` and `orgId` as it dispatches. A consent's Reject sent this way is `consent.rejectPending` ([ActionConsent](action-consent.md#operations); a kernel without that action refuses it rather than withdrawing an approval): an approval made meanwhile in chat or on another device stands, as it does for a token. Nothing is minted for an FCM installation. Which notifications offer one is the kernel's to say, never the notification's category or link: a notification sent with `notifications.notify` (or by module code) offers no decision whatever it names, and a decision's push text is derived from the request (its action and requester), not from the notification. An APNs token is single use, one per notification and installation registration, stored only as its SHA-256 (`eloxiv.notification_decision`) with the person, organisation, request and verdicts it may decide, and the session and registration generation it was sent to; it expires after 24 hours, or with the approval request when sooner. Its plaintext is only in the provider payload: never in a synced row, the delivery log, the audit log, the outbox, a URL or a log.
72
+
73
+ The person's tap on Approve or Reject (a notification action, never a tap on the notification, which only navigates) posts `{ token, verdict }` to `POST /api/notifications/decide`. No session is needed; each client address may try 30 a minute; every answer is `no-store`.
74
+
75
+ 1. The token must be known, offer the verdict, not have expired, and still belong to the registration it was sent to: the same installation, registered by the same session (unexpired, not signed out or revoked, and signed in by a method the organisation admits, as for any call of the person's, checked under the organisation's directory lock held shared until the decision commits, so a change to the sign-in methods waits for it or refuses it) with the same generation (signing out, unregistering, or registering the installation again from any session kills its tokens); otherwise `400 InvalidDecision` or `410 DecisionExpired`, audited (`notifications.decide`, `denied`, with a hash of the token's hash, never the token). A spent token's recorded answer is released only under the same conditions.
76
+ 2. The decision runs through the existing action through the one invocation path, as the person (origin `person`, surface `http`) under the registering session (held while the call runs and checked again at its commit, so a sign-out either waits for the decision or is seen by it): `approvals.approve` or `approvals.reject`, `consent.approve` with `remember: "once"` (never a remembered permission) or `consent.reject`, with the chat SDK's decision key as its idempotency key (`approval:<id>:<verdict>`, `consent:<id>:<verdict>:once`). Membership, the action's Cedar policy, the approver's live eligibility, the request's status and expiry are all resolved again now; the call is audited as any of theirs. Unregistering or registering the installation again waits for a decision in progress through it.
77
+ 3. Push decisions of one request by one person are serialised, and a consent must still be pending, its row locked: a consent the person already decided (in chat, or from another device) is not decided again from a push. The same verdict answers `200` with the request's status and `replayed: true`; the opposite one answers `409` and changes nothing. Withdrawing an approved consent stays the explicit `consent.reject` in the app or chat. Two devices answering one consent with opposite verdicts at once: one decides, the other is refused.
78
+ 4. The token's row is held by a transaction of the route's own, in which the action runs in a savepoint: the decision and the token's recorded answer commit together, or neither does. The token's expiry is read again after every lock the decision waited for. A decision that commits, or that the action refuses for good (`403` no longer eligible or not a member, `409` no longer pending), spends the token; a transient failure (`503 ActionFailed`, also when the token's answer could not be stored, the database connection was lost or the commit is uncertain, `no-store` like every answer) leaves nothing decided and the token unspent (a commit that did happen is replayed by the next try). Any later redemption, whatever its verdict, answers the recorded outcome with `replayed: true` and decides nothing, also one racing the first.
79
+ 5. A decision the person already made the same way elsewhere (the approval action's own idempotency, in chat or from another device, also a chat decision that carried a comment: matched against the person's vote) decides nothing and answers `200` with the request's status as it now stands (`pending` while an approval waits for its quorum) and `replayed: true`. The status is read once, its row locked until the answer commits.
80
+ 6. It is not an action: no agent tool, MCP tool or synced row reaches it. The token is a bearer credential: whoever holds it can make the one decision it offers, as the person, until it expires or its registration ends.
81
+
82
+ The response is `200 { kind, requestId, verdict, status, replayed }` (status as the action returned it: an approval's `pending`, `approved` or `rejected`; a consent's `approved` or `rejected`), or the error as above.
83
+
84
+ ## Email
85
+
86
+ Templates are registered in code: the kernel's own (`approvals.requested`, `approvals.decided`, `consent.requested`) and the app's (`KernelApp.emailTemplates`), each with an id, subject, text, optional HTML and its variables. `{{name}}` is replaced by the variable (`renderPlaceholders` in `@eloxiv/contracts`): a missing variable renders empty, a non-string is JSON, and HTML escapes every value. An organisation's override (`setEmailTemplate`) replaces subject, text and HTML for that organisation; `preview` renders either with example variables, sending nothing.
87
+
88
+ Every email carries `List-Unsubscribe: <url>` and `List-Unsubscribe-Post: List-Unsubscribe=One-Click` (RFC 8058), `X-Eloxiv-Category` and `X-Eloxiv-Notification`. The URL's token is signed (HMAC with the kernel's secret) and names the organisation, the person and the category. Following it (one-click `POST`, or `GET`) suppresses the address for that category and removes email from the person's preference; it needs no session and is audited (`notifications.unsubscribe`, surface `http`). A forged token is refused (400).
89
+
90
+ Configuration: `ELOXIV_SMTP_URL` (`smtp://user:password@host:port` or `smtps://...`) and `ELOXIV_EMAIL_FROM` (`Name <address>`), or `KernelConfig.email`. Without them the kernel has no email channel and notifications stay in-app.
91
+
92
+ ## Records
93
+
94
+ - **`Notification`**: `id`, `orgId`, `recipientId`, `category`, `title`, `body`, `link` (`EntityReference` or null), `createdAt`, `readAt`, `dismissedAt`.
95
+ - **`EmailTemplate`**, **`RenderedEmail`**, **`SendNotification`**, **`Preference`** (`category`, `channels`).
96
+ - **`PushProvider`**, **`PushInstallationRegistration`**, **`DecideRequest`**, **`DecideResult`**, and the errors **`InvalidDecision`** and **`DecisionExpired`**.
97
+ - The delivery log's **`DeliveryRecord`** is published with [NotificationChannel](notification-channel.md).
98
+
99
+ ## Sync
100
+
101
+ `notifications.mine` (from `@eloxiv/client/sync`, see [WorkItems](work-items.md#sync)) holds the person's own notifications in the organisation they act in, filtered by the module's read policy.
102
+
103
+ ## Guarantees
104
+
105
+ 1. A notification is durable and reaches only its recipient's replica; only the recipient marks or dismisses it.
106
+ 2. Sending is part of the caller's transaction: a rolled-back call notifies nobody.
107
+ 3. Channels are chosen per person and category; suppressed addresses are never sent to.
108
+ 4. Each delivery is retried until accepted or permanently failed, and every outcome is in the delivery log.
109
+ 5. Push goes only to installations their person registered from a session still in force; a decision from a notification is the person's, once, through the existing action under live policy.
110
+
111
+ ## How an implementation is checked
112
+
113
+ `notificationsConformance(start)` registers, against the inbox conformance app: a subscriber's notification reaches the order's owner in-app; sync holds a notification for its recipient only, who alone marks it read, unread and dismissed; system email arrives at the SMTP server with the template's subject, text and escaped HTML, a stable Message-ID, the category header and one-click unsubscribe headers, and is logged `sent`; two temporary failures are retried (three attempts logged); a refused recipient is logged `failed` after one attempt; a preference without email keeps a category in-app; only managers override a template, the preview shows it (and not in another organisation), and the next email uses it; the unsubscribe link (a forged one is refused) is audited, stops email for the category, and turning email back on still finds the address suppressed.
114
+
115
+ `pushConformance(start)` checks installations: registered from the person's own session and rotated on registering again (the next push goes to the new token only); refused for an agent (agent tools, MCP, an agent session); a token moving to whoever registered it last; sign-out removing exactly what that session registered; erasure removing all; and delivery and provider answers ([NotificationChannel](notification-channel.md#how-an-implementation-is-checked)). `decisionTokenConformance(start)` checks: an FCM installation offered the decision without a token, none minted for it; an approval approved as the person through the token (vote, audit, `no-store`), with the push's link and decision; a rejection, then both verdicts again answering the recorded outcome with nothing decided; opposite verdicts at once deciding once; consent approved (no permission remembered) and rejected; an unknown, altered or malformed token refused and audited; a token expired with its approval; a token of a person who lost the approver's role refused and spent; a token whose installation's session signed out refused; no agent or MCP route to it; the token in none of the notification, delivery, audit, outbox, push-delivery or idempotency rows. It also checks that an ordinary notification naming an approval request offers no decision; that a token is refused once its installation was registered again from another session, once the registering session expired, or once the organisation no longer admits how that session signed in; that a change to the organisation's sign-in methods waits for a decision already under way to commit; that two devices answering a consent with opposite verdicts decide it once, one after the other and at once; that a consent approved in chat is not rejected from a push; that a decision already made with the same verdict answers the request's status, and that a consent withdrawn while a redemption that found it approved runs is answered from one state (409, never an approval answered with the withdrawn status); that redemptions racing the first all answer what committed; that a recorded answer is not released after sign-out or expiry; that an approval given in chat with a comment answers the push's same verdict as a replay; and that a failure to store the token's answer, or the connection lost while storing it, answers `503` `no-store`, decides nothing, and the next try decides. The route's classification of refusals (definitive ones spend, transient ones do not) and of storage failures (also a failed rollback's defect) is checked by `packages/kernel/test/push-decisions.test.ts`.
116
+
117
+ ## Not yet guaranteed
118
+
119
+ - Engagement (opens, clicks) is not recorded; the delivery log records sends.
120
+ - Bounces and complaints do not feed the suppression list yet (only unsubscribe does).
121
+ - No digesting or rate limiting per person.
122
+ - A decision token (APNs only) is a bearer credential for its one decision until it expires or its registration ends: an app that leaks it (or a device left signed in) lets its holder make that decision as the person. Android decides in the app instead, with no token.
123
+ - Installations whose session expired without a sign-out get nothing (delivery checks the session), but their rows stay until the session's row is deleted.