@eloxiv/cli 0.0.0-stage → 0.1.1

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 +110 -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 +50 -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 +35 -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,260 @@
1
+ # Invocation
2
+
3
+ The one path every call takes, from every surface. Effect RPC (`/rpc`), HTTP (`POST /api/actions/<action>`), MCP tools (`/mcp`) and agent tools are projections of one action registry, and each lists a caller only what it can reach (`reach`); the CLI calls the HTTP surface, workflows and the scheduler call `invoke` in process, and inbound webhooks act through it from their durable execution ([Ingress](ingress.md)). Each hands the call to `invoke`, which decides who is calling, whether they may, and runs the action exactly once per idempotency key.
4
+
5
+ - Kind: kernel service. Version 1.6.0 (1.1.0: surface `sync`; a predicted insert's record key, derived on every surface. 1.2.0 adds `reach`; 1.3.0: external effects after commit; 1.4.0: `ActionFailed.effect`, what a failed call may have done; 1.5.0: receipts of version 2, with event references, provenance and an untargeted write's `written`; 1.6.0: `UnknownAction` carries a `message`, as every other error does).
6
+ - Schema: [`packages/contracts/schema/contracts/Invocation.json`](../../packages/contracts/schema/contracts/Invocation.json) (source [`Invocation.ts`](../../packages/contracts/src/contracts/Invocation.ts)).
7
+ - Implementation: [`packages/kernel/src/Invocation.ts`](../../packages/kernel/src/Invocation.ts).
8
+ - Kit: `@eloxiv/testing/conformance/Invocation` ([source](../../packages/testing/src/conformance/Invocation.ts)).
9
+
10
+ ## Operation
11
+
12
+ ### `invoke`
13
+
14
+ | | |
15
+ | --- | --- |
16
+ | Input | `InvocationRequest`: `action` (registered name), `input` (raw JSON, decoded by the path), `surface` (`rpc`, `http`, `mcp`, `agent`, `internal`, `workflow`, `scheduler`, `cli`, `ingress`, `sync`: a replica's optimistic write, pushed to `/zero/mutate`, see [Sync](sync.md#mutate); that endpoint decides each write's place in its client's order before calling, and a write answered before skips consent and business approval and may only replay its receipt), `headers`, optional `idempotencyKey`. In-process callers only (workflow steps and scheduled runs) may give an execution `identity` instead of headers; it is resolved to the same `Actor` as credentials would give (roles, groups, permissions read afresh, membership re-checked on every call), and no surface accepts one. The kernel's approval workflow alone also gives `approval`: the id of the approved business-approval request the call executes (see [Approvals](approvals.md)) |
17
+ | Output | `ActionResult`: `{ kind: "output", output }` on first execution, or `{ kind: "replay", receipt }` |
18
+ | Errors | the standard error set, `InvocationError` |
19
+
20
+ Credentials travel as headers on every surface: `authorization: Bearer <token>` or the session cookie. The token is a person's Better Auth session, an agent session the kernel issued for an agent acting for that person (see [ActionConsent](action-consent.md)), an API token, or an OAuth access token whose audience is the surface's resource ([MachineIdentity](machine-identity.md)); each is resolved afresh on every call, to one actor with the same fields (roles, groups, permissions). `x-eloxiv-org` names the organisation to act in; without it a session acts in its first membership, and an agent session or a machine credential in its own organisation (naming another is `Forbidden`). A machine credential's scope is checked right after identity: an action outside it is `Forbidden`.
21
+
22
+ Idempotency keys: RPC and HTTP read the `idempotency-key` header. MCP reads the key of each `tools/call` from `params._meta["io.eloxiv/idempotency-key"]` (a non-empty string of at most 255 characters; anything else fails the call with `InvalidInput` before it reaches the path, so it neither runs nor is audited); when `_meta` has no key, the `idempotency-key` HTTP header applies, to every call on the connection. `_meta` takes precedence. Agent tools use the model's tool-call id; workflow steps and ingress handlers `<execution id>:<step>`.
23
+
24
+ ### `reach`
25
+
26
+ | | |
27
+ | --- | --- |
28
+ | Input | `ReachRequest`: `surface` and `headers`, or (in-process callers) an execution `identity` and optional `agentSession` |
29
+ | Output | `Reach`: the resolved `actor`, the call's `origin`, and `actions`, the names of the actions this caller can reach now, sorted |
30
+ | Errors | `Unauthenticated`, `Forbidden` (the identity step's) |
31
+
32
+ What a caller can reach, among the app's actions and those of the MAKE modules installed in the caller's organisation, by exactly the checks `invoke` makes before it reads the input: the credential (or execution identity) resolved now, the credential's scope, whether the surface offers the action (its `exposure`, see [ActionRegistry](action-registry.md#exposure)), the action's agent tool group for an agent's call, and the action's policy for this actor. An action whose policy is constant false for the actor (or cannot be compiled) is hidden from it. The surfaces that list actions list only these: MCP `tools/list`, the OpenAPI document asked for with a credential (`GET /api/openapi.json`; without one it documents every action, as the public catalogue), and the agent tools (`AgentTools.toolsFor`, the agent runtime's offered tools). A call to a hidden action still reaches `invoke`, which refuses it and audits the refusal like any other, on every surface.
33
+
34
+ **Agent tool groups.** Every action is in its module's tool group (the module's name) and in each group its manifest declares (`toolGroups`, see [ModuleManifest](module-manifest.md)). An app disables groups for agents with `KernelApp.agentTools.disabledGroups` (an unknown group refuses the app at startup). An agent's call (agent origin: the agent tools, MCP, an agent session on any surface, or work an agent set up) to an action in a disabled group is `Forbidden` on every surface, and the action is hidden from every agent listing. Disabling a group is not a substitute for policy: it closes the action to agents everywhere (no HTTP route stays open to an agent session), and leaves people's calls to the policy.
35
+
36
+ **A record key the caller names, never a record key.** An action that predicts an insert (`optimistic.insert({ key, values })`, see [ModuleManifest](module-manifest.md#optimistic-effects)) receives, in its `key` input field, `recordKey(actor, entity, named)`: a UUID derived from the acting organisation, the acting user, the entity written and the key the caller named (a fresh one when it named none; a value that is not 1 to 128 letters, digits, `_` or `-` is `InvalidInput`). This holds on every surface, so a replica predicting the insert and the handler arrive at the same primary key, and no caller can choose a record's key outright: the same named key from another user, organisation or entity is another record, so the insert cannot collide with (and so disclose) a record the caller did not create. The idempotency hash, the audit record and an approval request carry the input as the caller sent it.
37
+
38
+ **Read batches.** `POST /api/batch` (`ReadBatchRequest`: `{ items: [{ action, input }] }`, 1 to 25 items) runs each item as its own `invoke` on the HTTP surface, with the request's headers (credential, organisation, client version), a few at a time, and answers `{ results }` in order: `{ ok: true, result }` (the envelope) or `{ ok: false, status, error }`, the error and the status the item would have had on its own route. Each item has its own identity check, policy, audit record and failure; one item's refusal, or a defect, is that item's answer only. An action that is not read-only (`hints.readOnly`) is refused as an item (`InvalidInput`) and never runs: a batch never writes. The batch is a transport, not an action: no surface lists it and no agent can call it as a tool. The client SDK's reader coalesces reads into it ([ClientSDK](client-sdk.md#transport)); tested in [`read-batch.test.ts`](../../packages/testing/test/read-batch.test.ts).
39
+
40
+ The surface label is not a credential. HTTP calls carrying `x-eloxiv-surface: cli` are recorded with surface `cli` (the CLI sets it); any other value is ordinary `http`; nothing reads the label but the audit record.
41
+
42
+ The path also decides where a call comes from, from the surface and the credential only (never a header): **agent** (the agent tools surface, MCP, or an agent session credential on any surface), **person**, or **system** (an execution identity). The agent surfaces come first: a call on the agent tools or MCP is an agent's whatever identity it carries, so `AgentTools.execute` given a caller identity and no agent session is still origin `agent` (before 2026-11-14 it was `system`, or `person` for a person's deferred call, while consent and tool groups already treated it as an agent's). Handlers see it as `ctx.origin`, and what the call acts under as `ctx.authority` (its credential's `scope`, null when not narrowed, and its `chain` of authorities, see [Authority](#authority); a module that defers work on the caller's behalf records it with the origin, as the scheduler does), beside `ctx.workItems` and `ctx.notify` (the [WorkItems](work-items.md) and [Notifications](notifications.md) APIs, applied after the handler's writes are checked, in the same transaction), `ctx.settings.get(key)` ([Settings](settings.md)) and `ctx.flags.isEnabled(flag)` ([Flags](flags.md)), both resolved for the caller in the call's transaction, and `ctx.sharing` (the [Sharing](sharing.md) operations for the caller, each authorised by the record's own `share` policy).
43
+
44
+ The kernel's own modules `query`, `settings` and `flags` are installed like any module, but their actions (`eloxiv.query`, `eloxiv.queryViews`, `settings.*`, `flags.*`) are served by kernel services (`KernelActionHandlers`), which may record a `detail` on the call's audit record (a query's hash and views, a setting's or rule's value before and after), on success and on failure.
45
+
46
+ ## Records
47
+
48
+ - **`InvocationStage`**: `identity`, `policy`, `approval`, `idempotency`, `execute`, `audit`, `outbox`, in the order every call passes them once its action has been found and its input decoded (see guarantee 1). The `approval` stage is consent ([ActionConsent](action-consent.md), for agent-originated calls to consent-marked actions) then business approval ([Approvals](approvals.md)).
49
+ - **`ActionResult`**: the envelope. The output always sits inside `output`, so an output that looks like a receipt (or a broad, any-JSON output schema) is never taken for a replay. `isReplay` in `@eloxiv/contracts` validates the whole envelope and receipt. The same envelope is the typed client's return type, the RPC success schema, the HTTP response and OpenAPI document, the MCP tool's output, the agent tool's `output` and `result` in the JSON module manifest.
50
+ - **`InvocationReceipt`**: committed with a keyed call, in its transaction, and what a replay returns, and nothing more:
51
+ - `version` (`2`; receipts committed before it have none), `action`, the original `invocationId`, `outcome: "succeeded"`;
52
+ - `targets`: the declared target ids exactly as the caller supplied them (deduplicated, in order), for best-effort actions the full requested list;
53
+ - `created`: ids of records of the action's own (`writes`) entity that the call inserted, that still existed when it committed, and that its output named;
54
+ - `completion`: best-effort actions only, the counts; otherwise `null`;
55
+ - `written`: an untargeted writing action only (it `writes`, with no `target`): how many records of its declared entities it inserted, and updated without inserting (`WrittenCounts`). Only rows it wrote: a row row-level security kept a statement from is neither counted nor named (backlog 2). An action that declares `reportsWritten` (with `WrittenFields` in its output; the manifest check refuses it on a targeted action, or without the field) gets the same counts in its output, set by the kernel;
56
+ - `events`: each event the call committed, by its CloudEvents identity (`specversion: "1.0"`, `id`, the outbox event's; `source`, `/modules/<module>`; `type`), in the order emitted: the outbox rows written in the same transaction, never a payload. A MAKE call's receipt names them too: its module's commit (`make_finish`) writes its events and then references every outbox row of the invocation in the receipt it commits ([Sandbox](sandbox.md), "One commit"; `make-sandbox.test.ts`, "a MAKE call's receipt");
57
+ - `provenance`: `correlationId` (the agent run, the durable execution or the approval the call is part of, else the call's own invocation id), `causationId` (the approval it executed, the run it was made from, or the execution it is a step of; null for a call a person or a client made), `runId` (the agent run, or null), `idempotencyKey` and `origin`. Ids only.
58
+ - **`Completion`**: `affected`, `requested`, `completion` (`complete` or `partial`), set by the kernel, never the handler.
59
+ - **`Actor`**: `userId`, `orgId`, `email`, `roles`, `groups`, `permissions` (see [actor.md](actor.md)).
60
+
61
+ ## Errors
62
+
63
+ | Tag | When | Audit outcome |
64
+ | --- | --- | --- |
65
+ | `Unauthenticated` | no valid session | `denied` |
66
+ | `Forbidden` | not a member of the named organisation; a call on a surface the action is not offered on (its `exposure`), or an agent session's credential calling over an API transport an action the agent surface does not offer; an agent's call to an action of an agent tool group the app disabled; an agent's call to a consent-marked action made with a service principal's credential (no person can consent); the policy denies or cannot be compiled; a target the caller may not act on; a write the database or the action contract refuses; a handler that changed its role; a replay whose caller lost membership or permission | `denied` |
67
+ | `ApprovalRequired` | a business approval rule matched the call: it was recorded, not run (carries `approvalId`) | `approval-required` |
68
+ | `ConsentRequired` | an agent-originated call to a consent-marked action was held for the person's consent (carries `consentId`) | `approval-required` |
69
+ | `IdempotencyConflict` | the key was used with another input, or its receipt is in an older format | `failed` |
70
+ | `InvalidInput` | the input does not decode, or a declared target is missing | `failed` |
71
+ | `UnknownAction` | no such action (`{ message, action }`) | `failed` |
72
+ | `ActionFailed` | the handler failed or died, or its output does not match the action's output schema (why is logged, never answered: the output may hold what the handler read). A defect of the kernel's own is logged and answered with a message naming only the invocation id, never its cause. Carries `effect`, what the call may have done (see below) | `failed` |
73
+ | `ClientOutdated` | an action that is not `readOnly`, called by a client whose `x-eloxiv-client-version` (on MCP, else an Eloxiv client's `initialize` `clientInfo.version`) is older than the kernel's minimum client version, or is not a version ([Release](release.md)); checked right after the action is looked up | `denied` |
74
+
75
+ Surfaces translate these (HTTP status 401, 403, 409, 422, 400, 404, 500, 426; MCP and agent tool errors) but keep the tag and fields.
76
+
77
+ **What a failed call may have done.** Every `ActionFailed` the path answers carries `effect`, so a caller knows whether a retry can do something twice:
78
+
79
+ - `none`: nothing of the call was kept. Its writes, the audit record of a success, its outbox events and the external effects it scheduled rolled back with its transaction (guarantee 2), and it changed nothing at a provider. This includes a handler that wrote and emitted and then returned an output its schema refuses: the output is checked inside the transaction, before anything commits.
80
+ - `unknown`: the call may have acted, for one of two reasons a caller handles differently:
81
+ - **Something outside the call's transaction changed.** Its handler called a direct capability operation that changes the account's own data (one needing any scope other than a `*.read` one, such as `mail.updateMessage`; see [External effects](#external-effects)), or a kernel action ran setup (MAKE's `make.install` and `make.rollback`, whose module migrations commit on their own). Those changes stay while the call, its idempotency claim included, rolled back, so a retry, even under the same key, runs the call again and repeats them. Reconcile first (read the provider's or the module's state back) and retry only what did not happen.
82
+ - **The failure came while the transaction was committing**, so the commit may have taken effect. A retry under the same idempotency key is safe: a call that committed answers with its receipt, one that did not runs once.
83
+
84
+ The kernel decides `effect` from what it saw, whatever a handler's own `ActionFailed` said: a handler cannot report `none` after a provider change. An approved call's execution record carries it too ([Approvals](approvals.md)).
85
+
86
+ Only `ActionFailed` carries it. The other errors roll the call back or come before it runs; a handler that changed the account's data directly and then had a write refused (`Forbidden`) or an input rejected (`InvalidInput`) leaves that provider change behind just the same, unflagged (a stated limit).
87
+
88
+ ## Authority
89
+
90
+ Work that acts in a person's name carries an **authority record** (`AuthorityRecord` in `@eloxiv/contracts`): the `scope` of the credential it was asked for with (null when not narrowed) and its **authority chain** (`AuthorityChain`), every authority it depends on, recorded when the work was asked for. The links (`AuthorityLink`):
91
+
92
+ | Kind | Id | Holds while |
93
+ | --- | --- | --- |
94
+ | `membership` | `<org>:<user>` | the person is a member of the organisation (every assertion for a person includes it) |
95
+ | `api-token` | the token's id | not revoked, not expired, still the person's in the organisation |
96
+ | `oauth` | the grant's id, with its `resource` | not revoked, same person, organisation and audience |
97
+ | `agent-session` | the session's id | not revoked, not expired, the person's, its device (if any) not revoked |
98
+ | `session` | the person's own signed-in session (Better Auth's session id; cookie or session bearer token) | still there (sign-out and revocation delete it), the person's, not expired by the clock. A link of the call it carries only: never recorded for deferred work |
99
+ | `device` | the device's id | not revoked, still the person's |
100
+ | `linked-identity` | `<platform>:<external id>` | still linked to the person in the organisation |
101
+ | `connection` | the connection's id | active, still the person's |
102
+ | `consent-permission` | the remembered permission's id | not revoked |
103
+ | `consent-request` | the one-time consent's id | approved, or used by the call it approved |
104
+
105
+ A business approval is not a link: the approved request is itself what runs ([Approvals](approvals.md)). A person's own session is a link of each call made with it (so a sign-out that commits before a call's assertion refuses the call, and one that comes while a call holds the session waits for it: Better Auth deletes the row the call holds `FOR SHARE`), but never of work that outlives the call: an approval, a schedule or an agent run a person set up records its chain without it and runs on their membership ([`session-authority.test.ts`](../../packages/testing/test/session-authority.test.ts)).
106
+
107
+ **The session is held until the work commits, and is valid at the commit.** One rule ([`Sessions.ts`](../../packages/kernel/src/Sessions.ts)), for work that authenticates a person's session and acts later (after a wait for a lock, a network call, or in another transaction):
108
+
109
+ - **Held.** In the transaction that commits the work, the session's row is locked `FOR SHARE` first (before the rows the work protects), then, once the lock is held, its expiry is read by `clock_timestamp()` (a predicate is evaluated before the lock is waited for, so the clock is never part of the locking read), and it must not be revoked. Sign-out deletes the row, so it waits for the work.
110
+ - **Valid at the commit.** The transaction's last statement checks the session again by the database's clock: still there, unexpired, not revoked (`Authority.confirm` on the invocation path and in `Authority.within`; `Identity.whileSignedIn` elsewhere). Work whose session expired, or was revoked, while it ran commits nothing (`Unauthenticated`). A stream checks it before each delivery. Activity moves a remembered session's expiry forward the kernel's way, not Better Auth's (whose refresh is off): by Better Auth's own terms (`expiresIn`, seven days, at most once per `updateAge`, a day), skipping a row that work holds (`FOR UPDATE SKIP LOCKED`), so a held session's expiry never moves under the work, the commit reads the one it held, and no refresh queues behind a hold. A browser's session slides as before: a request authenticated by the session cookie (the cookie guard, `Identity.refreshCookieSession`) that moves the expiry sends the cookie back with the new lifetime, its signed value, name and attributes as Better Auth set them; a session that is not remembered (a session-only cookie) is neither extended nor sent again, as Better Auth did.
111
+ - **Every session ended is ended by the kernel, within one bound.** Sign-out (`Identity.endSessions`) deletes the row in the kernel's own transaction, on a small pool of its own for endings (four connections: a kernel pool taken up by work holding sessions does not delay it), waiting for holders until `authLimits.signOutWaitMs` after the request began (`ELOXIV_SIGN_OUT_WAIT_MS`, default 5 s; `statement_timeout` and `lock_timeout` set to what is left before each statement, since a lock timeout bounds only each wait, and a delete behind holders that keep overlapping waits on one after another). Past that, or if the delete fails, a session still in force is revoked instead (`eloxiv.session_revocation`, kernel migration `0047_session_revocation`) within the bound's last second: every check refuses it from then on, and the housekeeping sweep (`Identity.sweepSessions`) deletes the row once no work holds it. Every other ending (Better Auth's deletes of sessions, a route whose purpose is to end them) is one set-based statement of the kernel's ([`AuthSeam.ts`](../../packages/kernel/src/AuthSeam.ts), `endingStatement`): every session it names revoked, its synced facts deleted, its live connections told at commit (`pg_notify`), and the rows no work holds deleted (`SKIP LOCKED`, so it never waits for a holder; the sweep deletes the rest once free). A session already expired authenticates no one and is not waited for. Both take, exclusively, the advisory lock on each session that the check at commit takes shared, so a holder either committed before the revocation, or sees it and commits nothing.
112
+ - **Sign-out** is the kernel's: the presented session resolved (Better Auth's own lookup, by an instance of Better Auth on the endings' connections, and the kernel's verdict there: nothing on the path of sign-out or a revocation waits for Better Auth's own pool), ended within the bound counted from the request, and the cookies Better Auth set cleared by the kernel with Better Auth's own serialisation (Better Auth's sign-out is not called: it reports success when its delete failed). Every statement of the kernel's is bounded by what is left (its statement and lock timeouts), and so is the wait for a connection: nothing of the kernel's runs on past the bound, and nothing is abandoned while it can still write. `503` only when the session could not be looked up, or ended or revoked; a credential that names no session in force has nothing to end and is cleared.
113
+ - **One resolution of a person's credential** (`Identity.resolvePerson`, every surface and Better Auth's routes alike): Better Auth resolves the credential (the `Authorization` header when there is one, else the session cookie), with its own cookie parsing and signature check: the kernel keeps no second parser that could disagree with it (a quoted cookie value Better Auth accepts, a space before the `=`, a duplicate). The kernel then judges the session by the clock (`clock_timestamp()`, never a transaction's start: a session that expired while a statement waited is expired) and the revocations, and refreshes a remembered one its way: one statement, conditional on the session being unexpired and unrevoked at that instant, skipping a row other work holds; with the cookie to send back (Better Auth's signed value, name and attributes) when the credential was the cookie. The cookie guard reads cookies with Better Auth's parser too. [`identity-resolution.test.ts`](../../packages/kernel/test/identity-resolution.test.ts) fails on a call into Better Auth's session lookup or handler anywhere else.
114
+ - **The kernel in front of Better Auth** (`Identity.handleAuth`, every `/auth/*` request and the OAuth pages' sign-in form): a presented session not in force (expired, revoked, unknown, badly signed) is removed from the request, so Better Auth never acts as it, lists anything for it, or cleans it up. No response lists sessions with their tokens: a JSON array of sessions (`list-sessions`) goes out without each one's `token`, its bearer credential (to revoke another session, `revoke-other-sessions` or `revoke-sessions`; `revoke-session` takes a token only the session's holder has). Better Auth runs on its own pool, in its own transactions: its rate-limit counts and everything else it writes persist as it decides, whatever the kernel does after.
115
+ - **The guarantee for Better Auth's own routes, for a signed-in request.** Better Auth does not run in the kernel's transaction, so the kernel cannot make what it writes commit only if the session is valid at that commit, as the kernel's own work does. What holds instead: every request that presents a session in force is held, whatever the route. A request whose session has ended (expired by the clock, or revoked) never reaches Better Auth. While Better Auth's handler runs, the kernel holds the session (a shared advisory lock on its request key, on a pool of the kernel's own for holds). Every ending of a session (sign-out, `revoke-session`, `revoke-sessions`, `revoke-other-sessions`, a password change or reset, an account's deletion, any delete of sessions Better Auth makes) first waits for the holds of the sessions it ends, up to `signOutWaitMs` (`eloxiv.await_session_requests`, kernel migration `0050_session_request_waits`), but the request's own. **Within that bound, everything such a request wrote has committed before the ending returns, and nothing of it commits after. Past the bound, the session is revoked at once and every later request made with it is refused, everywhere; and a handler then still running for it commits no write to an account after that: each write Better Auth makes for a request that presented a session (to the user, its accounts, its two-factor secret, its verification tokens; not its rate-limit count, kept whatever the outcome) is checked at its transaction's commit against that session, under the advisory lock a revocation takes exclusively (the account-write fence: kernel migration `0201_account_write_fence`, told the request's session through the settings `Identity` gives Better Auth's connections), so it commits only while the session is in force or was ended by the request's own statement (a password change ending every session). No credential is ever handed to a session that ended while its request ran: once Better Auth's handler returns, the kernel judges the presenting session again (by the clock; revoked by anything but the request's own statement), and if it has ended, every session the response would hand out (its session cookie, its `set-auth-token`, a `token` in its body) is ended, its cookies and tokens are discarded, and the answer is `401`.** [`auth-seam.test.ts`](../../packages/testing/test/auth-seam.test.ts): a slow `update-user` within the bound, which sign-out and `revoke-other-sessions` wait for; one past it, revoked at once, later requests refused, the write not landing; a password change paused after the hold while its session is signed out, not handing out the session it issued.
116
+ - **The routes that end sessions** (`SESSION_ENDING_ROUTES`: `revoke-session`, `revoke-sessions`, `revoke-other-sessions`, and `change-password`, `reset-password`, `delete-user`, which end them as a consequence, in Better Auth's own transaction, by the kernel's set-based statement) are not refreshed. After a route whose purpose is to end sessions (Better Auth done, or failed on its own), the kernel ends its whole set too (every session of the person, or every other one, or the one named and the person's): Better Auth enumerates them a page at a time, the kernel's statement names them all. That step, and only that step, is bounded (on the endings' connections, `signOutWaitMs` and a second, its statements' timeouts). Nothing bounds Better Auth's handler, and the kernel never answers before it has finished: its answer is what Better Auth did. Once the kernel's step after it fails, Better Auth's answer and its cookies are discarded: `503`, saying the sessions may still be signed in. A refusal of Better Auth's (a `4xx`) ends nothing. [`better-auth-sessions.test.ts`](../../packages/kernel/test/better-auth-sessions.test.ts) also reads Better Auth's route sources for routes that delete sessions, and checks that every delete of sessions Better Auth makes passes through its Kysely adapter, where the kernel's plugin makes it the set-based ending (compiled there).
117
+ - **Limits, stated** (each one line in [`docs/backlog.md`](../backlog.md) too):
118
+ - The activity refresh, and a revocation route's ending, wait for a lock someone holds on Better Auth's whole session table (an administrator's `LOCK TABLE`); past its bound, a revocation route answers `503`.
119
+ - Better Auth's own connections wait for a lock at most `signOutWaitMs` and run a statement at most thirty seconds (or four waits).
120
+ - **No request waits for a connection past the bound** (backlog 28). A request of Better Auth's waits at most `signOutWaitMs` for one of Better Auth's connections (eight) or, for a signed-in one, of the holds' (eight); past it, it answers `503` (a revocation route, a sign-in alike). People's sessions are looked up (on every surface, management included, and in front of Better Auth's routes) on a pool of their own (eight), so Better Auth's requests using up its pool never hold up the kernel's calls; a lookup waits for one of those at most the bound too, and a lookup that cannot run (no connection in time, the database failing) answers `503` on every route (`AuthUnavailable`), never a `401` a client would take for a sign-out; sign-out's lookup and ending run on the endings' connections (four), bounded the same. [`auth-seam.test.ts`](../../packages/testing/test/auth-seam.test.ts): with every connection of Better Auth's and the holds' taken, a revocation route and a sign-in answer `503` within the bound, while sign-out and a management read succeed; with the lookups blocked, two dozen management reads all answer `503` within the bound.
121
+ - Every ending deletes the sessions' synced facts (Sync) and tells their live sockets (collaboration), in every kernel process.
122
+ - The sweep runs every half minute in every kernel process, one at a time (an advisory lock: a process whose turn another holds skips it), each of its statements read through an index (kernel migration `0049_session_sweep_indexes`: session facts by session, rate-limit windows by start).
123
+ - **Deferred work carries no session, by design.** It is created inside a call that held the session and confirmed it at its commit, and it records the call's authority without the session (`recordOf`, `bindDeferred`, an approval's provenance): a schedule, an agent run, a device turn, an external effect or an approved call rests on the person's membership and the other links it recorded, which every one of its own steps asserts again in its own transaction (and refuses once any of them is revoked). Signing out ends the session, not the work the person set up while signed in. So the hold and the check at commit apply to work that runs on a session; work that runs later asserts what it recorded.
124
+ - **Later checks re-assert the original authority.** A check after the work started (a stream's next delivery, a completion's answer after the model call) asserts the authority the request was resolved to at first (the same person, organisation and links), never a fresh resolution of its credential, which could resolve another organisation; a collaboration socket pins the organisation it opened in.
125
+ - **The data is read inside the scope.** An assertion's scope never hands a value it had out for the work to run after it ([`assertion-scope.test.ts`](../../packages/kernel/test/assertion-scope.test.ts), a reading of the source: it refuses the shapes that only hand names out of a scope's callback or body, `=> Effect.succeed(actor)`, `Effect.succeed({ actor: caller.actor })` among them, and requires each hand-written `authority.assert` to have a check at commit of the capability it is bound to, counted per name; it cannot tell that check runs last in the assertion's transaction, which the runtime tests force for the paths they cover).
126
+
127
+ Every place that resolves a person's session and acts later, and how it holds it ([`session-hold.test.ts`](../../packages/testing/test/session-hold.test.ts) and [`session-commit.test.ts`](../../packages/testing/test/session-commit.test.ts) force each interleaving the reviews of the session link reproduced: blocked at the point named, signed out or expired, released; [`conformance/SignOutRace.ts`](../../packages/testing/src/conformance/SignOutRace.ts) is the race an app runs on its own optimistic writes, as `optimistic.test.ts` does):
128
+
129
+ | Where | What acts after the session is resolved | How it is held |
130
+ | --- | --- | --- |
131
+ | The invocation path (`Invocation.invoke`) | the handler and its writes | `Authority.assert` in the call's transaction (the session link), `Authority.confirm` as its last statement (a MAKE call's, before the module's commit) |
132
+ | Work a handler creates (a schedule, an agent run, a device turn, an external effect, anything `bindDeferred` records) | the record | created by the handler, under its assertion (the session included); `recordOf` and `bindDeferred` drop the session from what is recorded |
133
+ | A business-approval request and a consent request (`Approvals.check`) | the request's insert, after the identity, policy and consent checks | `Authority.assert` of the call's whole chain (`ApprovalCheck.held`), the session included, in the transaction that records the request, and `Authority.confirm` before it commits; the request's provenance drops the session |
134
+ | Better Auth's routes (`/auth/*`) presenting a session | whatever Better Auth writes, in its own transactions | not by the commit rule (Better Auth is not in the kernel's transaction): refused once the session has ended; held (a shared advisory lock, `Identity.handleAuth`) while the handler runs, which every ending waits for up to its bound; past it, revoked, and its writes to the account checked against the session at their commit (the account-write fence), with no credential handed out (above) |
135
+ | Management operations (`Managed`: MachineIdentity, Ingress links, Devices), reads too | the operation and its audit | `whileSignedIn`: held first in its transaction, valid at its commit |
136
+ | The directory's operations (`Directory.as`), reads too, and `listMyOrganizations` | the change and its audit, or the read | `whileSignedIn`: held first in its transaction (before the directory's lock), valid at its commit |
137
+ | Dead-letter management (`Outbox.as`) | the retry or discard and its audit | `whileSignedIn`: held first in its transaction, valid at its commit |
138
+ | Secrets over HTTP (`POST /kernel/secrets/*`) | the write or read and its audit | `whileSignedIn`, in one transaction with the operation; refusals audited |
139
+ | A published view read with a session (`QueryViews.read`) | the read | `whileSignedIn` in the read's transaction |
140
+ | OAuth consent and device approval (`POST /oauth/consent`, `POST /oauth/device`) | the code's issue, the device's approval | `whileSignedIn` in the transaction that records them; once the session is gone, the sign-in page (401) and nothing issued. The pages' organisation lists are read under it too |
141
+ | A connection's consent (`GET /connections/authorize`) | the flow's binding to the session | `whileSignedIn` in the transaction that writes it (a GET that changes state, protected by the flow's unguessable id: `GET_ROUTES`) |
142
+ | A connection's callback (`GET /connections/callback`) | the credentials, saved after the code exchange and the account lookup (network calls) | `whileSignedIn` in the transaction that consumes the state, and again in the one that saves them; once the session is gone, nothing is saved (403); the tokens the provider issued are revoked there (RFC 7009) only when the connector says its revocation ends only that token and no active Connection holds the same provider account, and are otherwise discarded; the callback's record says which (Connections) |
143
+ | The agent's routes (`/agent/*`, the metering reads `budgets` and `usage` included), the member list (`/api/org/members`) | the read | `Authority.within` with the credential's links (the session included), the read inside it |
144
+ | A run's event stream (`GET /agent/runs/<id>/events`) | stored events and live text, delivered as the run goes | the caller resolved once; every delivery asserts that authority, checks it at commit (`Authority.confirm`), then is enqueued, inside an assertion that began after what it delivers was read or arrived (live text waits for the next one); a refused assertion ends the stream |
145
+ | A one-shot completion (`POST /agent/complete`) | the model call, then the answer | the caller's authority asserted before the call, and the same authority (person, organisation, links) asserted again before the answer is handed over |
146
+ | Sync's push (`/zero/mutate`), MCP | each call | the invocation path |
147
+ | The collaboration socket (`/collab/socket`) | each call, and the deliveries between them | each call is the invocation path, in the organisation the socket opened in; when the session it authenticated with ends (sign-out, revocation, in any kernel process: `LISTEN eloxiv_session_ended`), the socket closes at once (4401); the person's other sessions' sockets stay open |
148
+ | Sync's query endpoint (`/zero/query`) and zero-cache's connections | nothing of the person's in the kernel: it answers a query's shape, which zero-cache runs on its replica | every query it transforms also tests a live fact naming the session (`sync_fact`, kind `session`), which it records under `whileSignedIn` and the kernel deletes when it ends the session: once that deletion replicates, the session's replicas receive nothing more and their rows are withdrawn (zero-cache gives the kernel no handle to close one connection; the fact is that handle). Revalidation (`ZERO_AUTH_REVALIDATE_INTERVAL_SECONDS`, 10 s in the harness and `mise run dev`) then disconnects them, the backstop for a session that ends without the kernel (expiry) ([Sync](sync.md)) |
149
+ | A download URL (`files.download`) | the bytes, streamed | the credential is checked when the URL is opened, and again after the stored object is opened (any wait for the store), before the first byte; a stream already open may finish (it was authorised when it opened, and is bounded by the file's size) |
150
+
151
+ Deferred work records its authority record: an approval request (in its provenance), a schedule, an agent run, a device turn, and every agent session (a turn's carries the turn's chain and the device; a conversation's, or one a device asks for without a turn, records what it is). Its calls carry the record in the `ExecutionIdentity` (`authority`). **Nothing missing is unrestricted**: work recorded before chains were (a NULL record on a run, a turn, a schedule or an agent session; an approval's provenance or a delivery's journalled identity without one; an identity that says `unrecorded`, or a person identity that says nothing) is refused when it acts (`Forbidden`, or `Unauthenticated` for a session, audited `denied`). Trusted server code that acts in a person's name with no revocable link says so (`{ scope: null, chain: [] }`). **An agent run's tools narrow its scope**, whoever it acts as: a run limited to some tools (a sub-agent's, a profile's) makes every call within the actions those tools are, recorded in the call's authority (a person's identity's `authority.scope`, the system actor's identity's `scope`), so what the call defers or reaches (a scheduled run, an approved call, a read program, a collection, a nested call) stays within them.
152
+
153
+ **`Authority.assert`** ([`Authority.ts`](../../packages/kernel/src/Authority.ts)) is the one check, and the only way to get the capability protected data needs:
154
+
155
+ - It runs inside the work's own transaction, before its first read or write of protected data. It locks every link's row `FOR SHARE`, the person's membership included, in one global order (by kind, then id). Once every lock is held it reads the expiry of the links that expire again by `clock_timestamp()` (the time it reads, never the transaction's start), so a wait for one link's lock never outlasts another's lifetime. A link missing, revoked, expired or no longer the person's refuses the work: `Unauthenticated` for a credential, `Forbidden` for consent and membership.
156
+ - It returns an **`Asserted`** capability: bound to that transaction and that person, carrying the scope. Every API that reads or writes protected data on someone's behalf requires it as a parameter, so code that has not asserted cannot compile a call: the invocation path's handler execution (and the kernel handlers it serves, the query surface's `run`), `QueryViews.readAs`, the agent's resources, skills and memory (`AgentResources.list`, `effective`, `recall`), a conversation's transcript (`inAgentFor`: context reads, compaction, the run's replies, tool results and device replies), and the agent's run routes (`AgentRuntime.status`, `events`, `inventory`, `children`). Only Authority.ts can make one:
157
+ - instances come from a factory in its closure, on a frozen prototype with no `constructor`, so one capability gives no route to another;
158
+ - an instance is frozen, and its person, scope and chain are kept privately and exposed as frozen copies, so nothing changes what it stands for;
159
+ - it is recognised only by membership of a module-private `WeakMap`, never by its shape; its type carries a brand nothing else has, and the lint rule `eloxiv/no-asserted-cast` refuses a cast to it;
160
+ - it is bound to its person and to the transaction and savepoint it was asserted in: the assertion records a nonce in a transaction-local setting, which a rollback to an earlier savepoint undoes (with the locks it took) and the transaction's end clears, so a capability used after either is refused (a defect). Every operation that takes locks or changes what a capability stands for (`consume`) returns one bound to the current savepoint, and the one it was given is no longer accepted.
161
+ - **Scope covers reads that are not actions.** A credential's scope names actions; a read on someone's behalf is covered by the action it is part of: a run's context, memory, resources and skills by `agent.send` (running the agent); a published view read (the agent's query fallback) by the query surface, `eloxiv.query`. So a token scoped to `agent.send` runs the agent, which reads its own conversation, memory and skills, and reads no view; a handler's own module views are covered by its action.
162
+ - After a later lock wait in the same transaction (a call's targets), `recheck` reads the expiring links by the clock again.
163
+ - A one-time consent a call runs under is used up by the call: `consume`, after the idempotency claim (a replay uses nothing), locks it `FOR UPDATE` while still approved, marks it used and records its use (`eloxiv.consent_use`, the fact that commits with the call: a request with a use is used, whatever its status says), so it commits used with the call, or stays approved if the call rolls back. Until then (a call held for a business approval) the person can withdraw it (`consent.reject`), and the approved execution is refused. Once used it still stands for work that call queued to run once (a device turn), but never for **recurring work**: a schedule records its authority as recurring (`AuthorityRecord.recurring`), and a recurring chain holding a one-time consent is refused at every run; a schedule an agent sets up runs only under a remembered permission (which replaces the one-time consent in its record, and whose revocation stops it). Every operation that creates, resumes, re-enables or changes deferred work binds it to the *current* call's authority through one function, `bindDeferred(ctx.authority, "once" | "recurring")` (a schedule's create and resume, a device turn, an agent run); a test fails on any handler that records `ctx.authority` otherwise.
164
+ - **MAKE calls.** A MAKE module's action runs on its module's own session, in a transaction the kernel cannot join, so its authority is held by a kernel transaction that encloses it: the call's chain asserted (links locked `FOR SHARE`), its run's cancellation guard, its one-time consent used up (locked `FOR UPDATE`), then the module's transaction runs and commits (its links' expiry read again just before), and the kernel's commits after it. A revocation therefore waits for a MAKE call in flight or refuses it, as for any call. The consent's use is recorded in the module's own transaction (`eloxiv_ctx.make_consume`, bound to the call's one-time ticket and to the consents the kernel listed on the call's record, `make_call.consumes`), so it commits or rolls back with the module's writes. (A function the module's session calls cannot lock the consent's rows itself: they are the consent module's, which the kernel's role does not reach.) The enclosing transaction holds one kernel connection for the call's length; MAKE's admission bounds how many run at once.
165
+ - **One lock order.** A piece of work takes its authority links before the rows they protect (a call's targets, its run's row the cancellation guard reads, a sync's cursor, a device's turn), and the links among themselves by kind, then id; every revocation takes the same links first. Bookkeeping that locks protected rows without asserting (reclaiming a device's expired turns) runs in a transaction of its own, which takes no link. A deadlock or serialisation failure the database still reports (an order a module's code chose, two handlers updating the same rows in opposite orders) aborts the transaction, which is run again (`db/Conflicts.ts`: the invocation path, a handler's own statements included, MAKE's enclosing transaction, `Authority.within`, the device bridge, management operations), never answered as a server error. **A retry runs the whole handler again**: everything it wrote rolled back, but a call it made outside the transaction (a connector's request, an email) happens again, so such effects belong after the commit (the outbox, or a workflow step), never in the handler itself ([`packages/testing/test/handler-deadlock.test.ts`](../../packages/testing/test/handler-deadlock.test.ts)).
166
+ - Every revocation (sign-out and session revocation, `revokeToken`, OAuth revocation, `revokeAgentSession`, `revokeDevice`, `unlink`, `connections.disconnect`, `consent.revoke`, `consent.reject`, removing a member) updates the same rows, in the same order, so it either waits for an execution that holds them to commit, or commits first and is seen by it: nothing executes after a revocation commits, and the two never deadlock.
167
+ - Before a stage that records something outside a transaction (a relay session's issue, a delegate's start), `check` runs the same check without locks, so refused work is settled rather than started.
168
+ - The guard against new paths around it: [`packages/kernel/test/authority-transcripts.test.ts`](../../packages/kernel/test/authority-transcripts.test.ts) derives the person-owned tables from the privacy inventory of the kernel's stores (every store with a column naming whose row it is and a column of personal content; a new table is covered as soon as the inventory classifies it, which its own test requires), and requires each statement on one to be an action handler's own (`<ctx>.sql` of a handler's context), inside the arguments of a helper that requires the capability (or of a wrapper that passes them on to one), tagged by one that checks it, or listed with why. It reads each file's syntax tree with its scopes (`packages/kernel/test/support/authorityGuard.ts`): names resolve to their declarations through imports and aliases, a helper covers only what is inside its call's arguments, and a function with an unguarded statement is a writer whose every reference is checked in its place (keyed by its `type` argument: `appendEvent`'s event); a writer nothing refers to is a finding. It counts every system-role helper (`asSystem`, `inSystem`, `inAgent`, `asAgent`) per file, through aliases, against what it is for, and requires every read of a handler's authority, however it is taken, to be `bindDeferred`'s first argument. The analysis is proven on planted bypasses (an alias, a statement beside a helper's call, a same-named helper, a renamed writer, a context that is not a handler's, an authority destructured).
169
+
170
+ Where it runs: every call of the invocation path (before its invocation context, idempotency claim and targets, with the chain it acts under: the identity's chain, the agent session it is made through, the consent that let an agent's call through); an agent run's own reads and writes of the person's data outside actions (its context, compaction, skills, the query fallback, the device bridge's message, a delegate's creation); an inbound webhook's handler (with the linked identity as a link, [Ingress](ingress.md)); a connection sync's page (with the connection as a link, asserted before the cursor it protects: a disconnect that commits first discards the page, and one asked for while a page applies waits for it, [Connections](connections.md)); a MAKE call (above); every agent HTTP route (runs, their context, children and events, completions, resources, memory, budgets, usage), under the credential's chain; a device's reports of a turn it runs (events and result: the turn's chain is asserted before the turn's row, and a turn whose chain no longer holds fails without them, [Daemon](daemon.md)); and a device's claim of a turn (its chain asserted, links locked, before the turn is taken). An agent run refused by any of these ends `failed`, saying its authority no longer holds. Work queued by work keeps the whole chain: a schedule, approval request or device turn a run creates records the run's chain and its agent session; a delegate records its parent's.
171
+
172
+ **Not covered, by design: reactions to committed facts.** Outbox subscribers and event-triggered workflows act as the organisation's system actor ([Outbox](outbox.md), [Workflow](workflow.md)): they are the app's reactions to facts already committed. A committed event carries no initiating chain, so revoking the credential (or the consent, or the membership) of the call that emitted it does not cancel the reactions to it; what a reaction does is authorised by the app's policies for the system actor.
173
+
174
+ ## Guarantees
175
+
176
+ 1. **Stage order.** First the path looks up the action and decodes its input; then come identity, policy, approval, idempotency, and finally execution, audit and outbox. A call that fails a step never reaches the next. So an unknown action is `UnknownAction` and undecodable input is `InvalidInput` even when the caller is not authenticated. An unauthenticated call to a known action with valid input is `Unauthenticated` whatever the policy. A policy denial never asks for approval. A call blocked for approval claims no idempotency key, so its retry is blocked again. A missing declared target is found after the key is claimed, inside the transaction, so it too is `InvalidInput`, with the claim rolled back.
177
+ 2. **One transaction.** The idempotency claim, the handler, the record checks, the audit record of a success and the outbox events commit or roll back together.
178
+ 3. **Authorisation before and after the handler.** A constant-false or uncompilable policy denies before anything runs. Declared targets are locked and must satisfy the action's compiled filter before the handler runs, so a handler cannot change what the check reads (ownership, a lock). Every row the handler inserted, updated or deleted is checked afterwards from the write log; row-level security has already checked each statement's old and new rows (see [Db/Tx](db-tx.md)). The action's filter applies only to the entities it declares (`writes`, `target`, `actsOn`): on any other entity it is false, here and in row-level security, so an action declaring no entity reads only what the read policy allows and writes nothing. An `organisationWide` action's filter is confined to records of the acting organisation. An action hinted `readOnly` runs its handler in a read-only scope: a write fails as `Forbidden`.
179
+ 4. **Exact targets** (the default for an action with `target`). Every declared target is inserted, updated or deleted, and no other row of the target entity is, or the call fails as `Forbidden` and rolls back. That holds for statements that reach other rows (`UPDATE ... FROM`, data-modifying CTEs, `INSERT ... ON CONFLICT DO UPDATE`) and for deletes. An undeclared insert fails the same way whether or not an unreadable record already holds the key.
180
+ 5. **Best-effort targets** (`bestEffort: true`, declared, never inferred). Targets the caller may not act on are skipped silently; the kernel overwrites `affected`, `requested` and `completion` in the output and writes them to the audit record. Neither those fields nor the receipt say which targets were affected. The rest of the output is the handler's: module authors must not name affected ids there.
181
+ 6. **Identities are immutable.** An update that changes a primary key is `Forbidden` before any referential check runs.
182
+ 7. **Replays return receipts, never cached output.** A retry with the same organisation, user, action, key and input returns the receipt of the original call and does not run again; a different input is `IdempotencyConflict`. Keys never cross organisations, users or actions, and concurrent duplicates run once. Before releasing a receipt, after any wait on the original call's claim, the kernel authenticates the caller again (same user, still a member of the same organisation) and re-checks the action's policy; the caller's membership is held from the assertion on ([Authority](#authority)), so a removal waits for both calls and refuses the next.
183
+ 8. **Audit on every outcome.** See [Audit](audit.md).
184
+ 9. **Deferred work keeps its provenance and its authority.** A business approval executes the approved call with the origin, agent session and credential scope it was made with ([Approvals](approvals.md)), and a schedule runs with its creator's origin and scope ([Scheduler](scheduler.md)); the identity, scope, tool-group and policy checks run again when the work executes. Every call asserts its authority chain inside its transaction ([Authority](#authority)), so deferring a call never widens it or outlives any authority it was asked under, and a revocation never races it. A refused deferred call is audited `denied` as whose call it was. Agent runs, their delegates, device turns and inbound webhooks carry their chains the same way ([AgentRuntime](agent-runtime.md), [Daemon](daemon.md), [Ingress](ingress.md)).
185
+ 10. **One path from every surface.** The typed client, HTTP, MCP, agent tools, the CLI, scheduled jobs, workflow steps and inbound webhooks give the same identity, policy result, approval behaviour, idempotency, audit record (apart from its surface, time, ids and key) and outbox event for the same call, with these documented differences: the origin (agent for agent tools, MCP and agent sessions; system for execution identities; consent applies to agents); OAuth access tokens are bound to their resource and refused on the in-process agent tools; an execution identity has no credential scope, and its refusal is audited as whose call it was; internal surfaces key idempotency themselves (`<execution id>:<step>`), so a repeated run, execution or delivery joins the first. An action `reach` hides from a caller is unreachable on every surface.
186
+
187
+
188
+ ## Cookie-authenticated requests
189
+
190
+ A browser attaches the person's session cookie (Better Auth's, `SameSite=Lax`) to a request another page makes. `SameSite=Lax` stops a cross-site `POST`, not a same-site one from another origin (a sibling subdomain), and CORS stops a page from reading the answer, not the request from acting. So `KernelRoutes` puts one guard in front of every route it serves ([`surfaces/CookieGuard.ts`](../../packages/kernel/src/surfaces/CookieGuard.ts), a global middleware: a route added later is behind it too). A state-changing request (`POST`, `PUT`, `PATCH`, `DELETE`) that carries the session cookie and no `Authorization` header is answered `403` (`{ "_tag": "Forbidden", "reason": "cookie-request-forgery" }`) before any route sees it, unless:
191
+
192
+ - its `Origin` is the kernel's own (`ELOXIV_BASE_URL`'s) or one the deployment trusts; a missing or `null` `Origin` is refused;
193
+ - its Fetch Metadata fits, when the browser sends it: `Sec-Fetch-Site: same-origin` only from the kernel's own origin, `same-site` and `cross-site` only from a trusted origin (`same-site` is not trust: a sibling subdomain is same-site), `none` never;
194
+ - its body is what the route takes: `application/json` (or the typed client's `application/ndjson`) on JSON routes, which is every route not listed otherwise; a form on the OAuth pages and one-click unsubscribe; anything on uploads and inbound webhooks. A `text/plain` or bodiless request, which a page can send without a CORS preflight, is refused.
195
+
196
+ A bearer credential (a session's bearer token, an API token, an OAuth token, an agent session, a device) is exempt: a browser never attaches it, and a page of another origin cannot send it without the kernel's CORS approval. The kernel's own clients (the client SDK, the Foldkit shell, the Tauri desktop host, the CLI) use bearer credentials; the OAuth pages post their forms from the kernel's own origin.
197
+
198
+ The exemption follows the credential actually used. A request with an `Authorization` header (any value: empty, `Basic …`, a bearer token that does not verify) reaches its route without its cookie (the guard removes it), and `Identity` never reads the cookie of a request that has one (`presentedCredential`): it authenticates by that header or not at all. Otherwise Better Auth, which falls back to the session cookie when a bearer token does not verify, would let `Authorization: Bearer x` carry a cookie-authenticated mutation past the guard (or sign the person out through `/auth/sign-out`). The guard reads the request's headers, not an RPC message's (Effect RPC carries a call's headers inside the message), so `@eloxiv/client`'s typed client sends each call's `Authorization` header on its HTTP request too: a runtime that keeps a cookie jar (React Native on Android attaches the cookie Better Auth set at sign-in to every later request, with no `Origin`) would otherwise send a cookie `POST /rpc` the guard refuses.
199
+
200
+ **Trusted origins** are configured with `ELOXIV_TRUSTED_ORIGINS`, comma-separated (default `http://localhost:5173,tauri://localhost,http://tauri.localhost`: the Vite dev server and Tauri's webview). They are also the origins CORS answers and Better Auth trusts. List an origin only when a page served there may act with the person's cookie; a deployment whose shell is served from the kernel's own origin needs none.
201
+
202
+ **A GET** is followed from any page with the cookie and no `Origin`, so the guard cannot tell a forged one from a navigation: a GET route either only reads, or changes state only under a protection a forged navigation cannot present. `GET_ROUTES` declares every GET route the kernel registers as `read` or `write`, and each `write` names its protection: Better Auth's (a link's token, or the session's own expiry), `/oauth/authorize` (a pending request that acts only once the person decides by POST, with its session-bound csrf), `/connections/authorize` (the flow's 144-bit id, for its own person; the write held under the session) and `/connections/callback` (the state bound to the session), `/notifications/unsubscribe` (the link's signed token), the collaboration socket (cookies only from a trusted origin; each change an action).
203
+
204
+ **Refusals are audited.** A request the guard refuses is recorded `denied` as its canonical action (`notebook.write` for `/api/actions/notebook.write`, `eloxiv.secrets.put` for `/kernel/secrets/put`, `agent.send` for `/agent/messages`, else `POST <route>`), with the reason, as is a management operation's or a secret's refusal for authentication or for its session (`Audit.denied`). A refusal of a caller the kernel could not identify (no credential that authenticates: a forged request, a signed-out session) is bounded: per route pattern (or registered action) and client address bucket, at most `authLimits.anonymousDenialsPerMinute` records a minute (`ELOXIV_ANONYMOUS_DENIALS_PER_MINUTE`, default 30), then one record saying the rest of that minute is only counted (in `eloxiv.rate_limit`, swept after a day), so unauthenticated traffic cannot grow the log without bound, however it varies paths, action names or IPv6 addresses ([Audit](audit.md), guarantee 7). The invocation path's refusals and failures of unidentified callers are bounded the same way; a path whose escapes do not decode is refused `400`, recorded the same way. The client address is the kernel's own: the guard sets `x-eloxiv-client-address` on every request (the connection's peer, or what a trusted proxy appended), replacing whatever a client sent.
205
+
206
+ `COOKIE_ROUTES` is the inventory of every state-changing route the kernel registers, with the body it takes: [`packages/testing/test/cookie-guard.test.ts`](../../packages/testing/test/cookie-guard.test.ts) builds `KernelRoutes` against a router that records every registration (whatever registered it: `HttpRouter.add`, `HttpApi`, the RPC and MCP servers, a path given as a constant), fails when a state-changing route is registered that the inventory does not cover, and sends a forged cookie request to each listed route (and to a path the kernel does not serve). It also checks that a forged `text/plain` or bodiless request to routes that read the body whatever its type (an agent's message, a secret) is answered `403` with the guard's reason and changes nothing, that a malformed `Authorization` header with the cookie acts as no one, that every GET route is declared in `GET_ROUTES`, and that a forged GET to each that writes changes nothing.
207
+
208
+ ## External effects
209
+
210
+ What an action changes in its own tables commits or rolls back with the call. What it does at a provider that other people see (a message sent, an invitation, an answer to an organiser) cannot be rolled back, so it never happens inside the call.
211
+
212
+ - **Declared.** An action names the capability operations its handler may call (`defineAction({ connections: { mail: ["getMessage"] } })`); `ctx.connections` refuses every other (`Forbidden`), on every surface and for every caller (a person, their agent, a scheduled call). The capability contracts mark the operations others see (`effect: "external"`); an action that declares one must need consent (`consent: true` or `"each-call"`), or the kernel refuses to start.
213
+ - **Scheduled, never called.** An external operation is not callable directly. The handler schedules it: `ctx.connections.schedule({ connectionId, capability, operation, input, onDone })` checks the declaration, the input against the contract and that the Connection is the caller's, and returns an effect id. Every `ctx.connections` operation requires the call's assertion ([Authority](#authority)): it acts on the caller's behalf only while the call's chain holds. The effect is recorded (`eloxiv.connection_effect`, state `pending`) with the call's authority bound to it (`bindDeferred(ctx.authority, "once")`), with an outbox event, in the call's transaction: a call that fails or rolls back schedules nothing, and a replay of the call's idempotency key schedules nothing more. With an idempotency key, an effect's id is derived from the key and its place in the call, and the replay receipt lists them (`effects`), so a caller who retries always finds the outcome of what the first call scheduled.
214
+ - **Delivered after commit, at most once.** The kernel's workflow `eloxiv.connection-effect` claims the effect (`running`, committed before the provider is called) and calls the operation over the Connection as its owner (still a member, the Connection still theirs and usable). The claim asserts the authority bound when the call scheduled it, extended with the Connection, before it locks the effect's row (the lock order): an effect whose chain no longer holds (a revoked token or consent, the owner no longer a member, the Connection disconnected) is never claimed, and concludes `failed` if it was pending or `unknown` if an interrupted attempt was running. An effect recorded before authorities were bound is unrecorded work and refused the same way. The module's `onDone` is invoked under that same authority. The HTTP layer never repeats an external request after a 5xx (it still waits out a 429, which refuses without acting). The outcome:
215
+ - `succeeded`: the provider answered;
216
+ - `failed`: the provider definitely did not act (a typed refusal: 401 after the refresh, 403, 404, 409, invalid input);
217
+ - not sent (`Unavailable` with `dispatched: false`: the operation failed before sending anything, such as a read it needs first) is run again exactly as a rate-limited effect is, within the same attempts;
218
+ - rate-limited (`RateLimited`: a 429 or a provider's rate-limit 403 the HTTP layer could not wait out within its budget, or a cooldown or quota that kept the request from being sent): the provider did not act, so the effect is run again rather than failed. It goes back to `pending` with its input kept, why it waits, and `not_before`: no earlier than the provider's retry time, and at least `connections.rateLimitedBackoffMs` (`ELOXIV_CONNECTIONS_RATE_LIMITED_BACKOFF_MS`, default 1 000; 0 to 600 000, any other value is the default) doubled for each run so far (2, 4, 8, 16, 32 s by default), and at most six hours whatever the provider asked, all in one statement. Every outcome clears `not_before`. The claim refuses a pending effect before its `not_before` (kernel migration `0046_effect_not_before`), so the wait holds even when the process dies before the workflow recorded it; the workflow sleeps durably until then and claims it again. After six runs (`RATE_LIMITED_ATTEMPTS`), all rate-limited, it is `failed`. Only a run that ended `RateLimited` is repeated: anything that may have acted is reconciled as below and never run again. This relies on what `failed` already relies on, which every capability contract requires ([a write is never hidden](README.md#capability-contracts)): an operation's refusal means it did not act. While it waits, `ctx.connections.effect` reports it `pending` with `waiting: { reason, retryAt }`;
219
+ - uncertain (a 5xx, a lost answer, a network failure, or a delivery found already `running`, interrupted mid-call): the provider may have acted, so the kernel reads it back where the contract lets it: a message by the client id the kernel sends it with (`MailProvider.findSent`; the effect's id, looked for no further back than when the effect was scheduled, `sentAfter`), an answer by the account's own response as the provider records it (`CalendarEvent.selfResponse`, never an attendee matched by address), an update by the event's fields, a delete by the event being gone or cancelled. Reading back can only conclude that it happened: the provider's state now matches what was asked (the answer asked for, every field the update gave, the event gone or cancelled, the message found), `succeeded`, with what it read (`reconciled`). A snapshot of the state now never proves that an earlier attempt did not happen (another client may have reset an answer, restored an event, the provider may not have filed a message yet), so everything else (no answer, another answer, fields that differ, the event still there, a message not found, a read that fails) is `unknown` ("it may have happened"), shown to the person through the module's `onDone`, and never run again by the kernel. Each effect acts at the provider at most once: only a run the provider refused for its rate limit is repeated. Every outcome clears the effect's input.
220
+ - `succeeded` always carries the operation's output (`result`), checked against the contract before it is stored, never null when stored (a database check refuses a succeeded effect with neither one nor a reason it was cleared, below): the provider's answer, or, reconciled, the resource read back (the event; `{ id }` of the message found; `{}` for an answer or a delete). `ctx.connections.effect` returns a union typed by `state`: only `succeeded` has a result, non-null, with `reconciled`; `failed` and `unknown` have an `error`; a `pending` effect waiting out a provider's rate limit has `waiting` (`reason`, and `retryAt`, when it runs again), null otherwise. The module is told only the outcome (`onDone`), not the wait: the wait, the attempts and whether the module was told are the kernel's record, which the owner reads with `connections.effects` (or a handler with `ctx.connections.effects`), and mail's `mail.outgoing` view gives each message's `effect_id` for it. A report the module refuses for good (`Unauthenticated` or `Forbidden`: the authority the call was bound to is gone) is not retried; the effect is recorded `reported: refused` (kernel migration `0165_effect_reported`), and the module brings its record up to date on its own later work, as its owner, from `ctx.connections.effect` (mail's inbox sync settles the messages it still shows as going).
221
+ - **The answer is kept only while the module may need it** (backlog 14; kernel migration `0240_effect_result_cleared`). Once the outcome is recorded the kernel keeps the outcome for good but the provider's answer (`result`) only as long as the scheduling module may still read it, and records why it went (`result_cleared`; `ctx.connections.effect` returns it as `cleared`, `result` then null, also for `succeeded`): `told` once the module's `onDone` committed (`told_at`; a callback run again answers what it recorded); `no-callback` as soon as the outcome is recorded when the action named no `onDone` (nothing reads it); `expired` when the module was never told (its report refused for good, or failed every attempt) and `ELOXIV_EFFECT_ANSWER_RETENTION_DAYS` (`retention.effectAnswerDays`, default 7; 0 clears it at the next sweep) have passed since the effect ended: the module's reconciling from the record reads the answer within that window, after which the kernel's hourly retention sweep ([Scheduler](scheduler.md), `Retention`) clears it; `erased` when an erasure of a person the answer mentions cleared it sooner ([Privacy](privacy.md), the source `eloxiv.effectAnswers`). A module that reads a cleared answer of a `succeeded` effect settles without it and leaves the resource to its next sync (mail 0.2.6 settles a send without the provider's id; calendar 0.2.5 records a create or update done and leaves the event to the sync). Tests: `registry/test/effects.test.ts` ("clears the answer of an effect that names no callback once its outcome is recorded", "keeps a refused callback's answer for the module's reconciling within the window, then clears it", "clears every saved answer that mentions an erased person, whoever owns the effect", "keeps the provider's answer only until the module is told: then the outcome stays and the answer goes"). A module decodes the result with the operation's output schema (calendar's `changed` decodes a `CalendarEvent`), and a result it cannot decode is an outcome of its own for the person (calendar records the change `unknown`, with why), never a callback that fails again. Effects recorded as succeeded without a result before the check existed are `unknown` after kernel migration `0039_derived_ingestion`, which then validates the check for every row.
222
+ - **Effect ids**: without an idempotency key, random. With one, derived from the key and the effect's place in the call: its `name` when the handler gives one (`schedule({ ..., name })`, like a durable step's name; letters, digits, `.`, `_`, `:`, `-`; a name given twice in a call is refused with `InvalidInput`), else its number in the order the effects were scheduled, taken synchronously before anything waits. Effects scheduled concurrently never share an id; a duplicate is refused before anything is recorded.
223
+ - **Later, and cancelled.** `schedule({ ..., notBefore })` (an ISO instant with its offset, at most `MAX_EFFECT_DELAY_DAYS`, 366, ahead) records the effect with `not_before` set, so it waits `pending` exactly as a rate-limited one does: the claim refuses it before then, the workflow sleeps durably until then (a restart keeps the wait; a kernel down at the time runs it when it is back), and `ctx.connections.effect` reports `waiting: { reason: "Scheduled", retryAt }`. It runs under the authority bound when it was scheduled, asserted at the claim like any other: a credential, consent or membership revoked meanwhile fails it. `ctx.connections.cancel(effectId)` concludes a pending effect of the caller's `failed` with the error `Cancelled`, written with the call's own writes in its transaction, so the module's record of the cancellation and the cancellation commit together or not at all (a call that fails or rolls back cancels nothing). The claim takes only a `pending` row under its lock, so an effect is either cancelled or run, never both: `cancel` answers false for one that is running or concluded, and an effect that starts after `cancel` answered but before the call commits fails the call (`InvalidInput`), with nothing of it committed. The module's `onDone` is told of a cancelled effect at its original time, as of any outcome. Mail's scheduled sends and snoozes are built on it (`registry/test/mail-workflows.test.ts`: a send not made before its time and made after it, a cancelled one never made, a snooze's return called off by bringing the message back by hand). A read-back after an uncertain `mail.updateMessage` (a snoozed message moved back) concludes `succeeded` when the message's read state and folders are as asked.
224
+ - **Reported.** The workflow invokes the scheduling module's `onDone` action as the owner with `{ effectId }` (its own idempotency key), which reads the outcome as the kernel recorded it (`ctx.connections.effect`): a module records what happened, never what a caller claims happened. A failure is retried, each attempt a step with a durable wait (2 s doubling to 5 minutes, eight attempts) before the execution fails; the callback must be idempotent.
225
+
226
+ Direct calls (operations that read, or change only the account's own data, like read state or folders) run on a connection of their own, outside the call's transaction: they are not undone if the call then fails, which is why only those are allowed directly.
227
+
228
+ ## Entity references
229
+
230
+ Modules work together only through actions, events, entity references and capability contracts, never through each other's tables. A module that refers to another module's record keeps its id (notes' `greeting_id`) and names the entity from the owner's contract (`import { greeting } from "../hello/contract.ts"`, the only file of another module it may load, `tools/done/test/module-imports.test.ts`). Its handlers read the record with `ctx.references.read(entity, id)`:
231
+
232
+ - The kernel reads it as the **owner's** runtime role, under the owner's row-level security, filtered by the owner entity's own `read` policy compiled for the caller, in the call's transaction: the caller gets exactly what the owner's policy lets them read (groups, roles, sharing grants and all), in the organisation they act in.
233
+ - The answer is the record's fields by field name, with Postgres's JSON values (timestamps as ISO text), or `undefined`: a record that does not exist and one the caller may not read get the same answer.
234
+ - The entity used is the one registered under the value's `cedarType`; whatever else the value passed says (another table, other attributes) is ignored.
235
+ - The handler's own SQL never reaches the owner's table: its role has no privilege on another module's schema, so PostgreSQL refuses the statement and the call fails.
236
+
237
+ Capabilities go the same way: a connector implements a capability contract, and a module uses it only through `ctx.connections` (above), never by loading the connector's code (`tools/done/test/module-imports.test.ts`; fallow's `modules` zone may not import `connectors`).
238
+
239
+ The handler's own role never changes between its statements ([Db/Tx](db-tx.md), guarantee 2): the switch to the owner's role, the read and the switch back are one statement (a `DO` block with the compiled filter inlined as literals, as row-level security's DDL inlines it), so SQL the handler runs concurrently on its transaction never runs as the owner's role. Proven by [`packages/testing/test/entity-references.test.ts`](../../packages/testing/test/entity-references.test.ts) (the owner, a reviewers group's member and another member against team's policy; another organisation; a missing record; the handler's concurrent SQL only ever as its own role; its direct read refused).
240
+
241
+ ## How an implementation is checked
242
+
243
+ `invocationConformance(start)` registers, against the fixture app (see [Running the kernel kits](README.md#running-the-kernel-kits)):
244
+
245
+ - *stages run in order*: action lookup and input decoding before identity, identity before policy and approval, non-member organisation, policy before approval, approval blocks before anything is written or emitted, approval before idempotency, the standard error set;
246
+ - *every result is an envelope*: output and replay envelopes, validated with the published schema;
247
+ - *record authorisation*: ownership change, lock clearing, more than the target, deletes beyond the target, the legitimate path, side-effect updates;
248
+ - *exact and best-effort targets*: upserts, joined updates and CTEs onto other rows, key changes over an unreadable child, a forbidden new state, an untouched target, best-effort counts in the result and audit;
249
+ - *identities and constraint outcomes*: moving a record onto the target's key, undeclared inserts with and without a conflicting unreadable key, a reference to an unreadable and to a missing record, and the stated limit (deleting a record a readable or an unreadable record references fails alike);
250
+ - *replay receipts*: after revocation, after a new forbid, create-or-get, deletes, conflicts, nested, map-keyed and counted outputs, joined entities, best-effort counts, untargeted updates, created records the output did or did not name, secondary entities, policy and membership re-checked after waiting on a claim, removed members;
251
+ - *idempotency scoping*: across organisations, concurrent duplicates.
252
+
253
+ The Eloxiv kernel runs it in `packages/testing/test/invocation.test.ts`, which also covers what depends on its storage: receipts stored under older formats are refused, and the upgrade that discarded cached outputs. `registry/test/surfaces.test.ts`, `envelope.test.ts` and `approval.test.ts` prove the four surfaces give the same audit record, outbox event, receipt, conflict and approval behaviour for the same call. Guarantee 9 is proven by [`packages/testing/test/provenance.test.ts`](../../packages/testing/test/provenance.test.ts) (an agent's approved schedule of an action its tool group closes runs as the agent's and is refused; a person's runs; a scoped token's keeps its scope), [`deferred-authority.test.ts`](../../packages/testing/test/deferred-authority.test.ts) and [`authority-chain.test.ts`](../../packages/testing/test/authority-chain.test.ts): for each kind of link, revoking it while a deferred call holds it waits for the call, and the next call is refused; a revocation the call waited for refuses it (an API token, a business-approved call's consent, an agent's consented call, a webhook's linked identity); a token that expires while the call waits for its target; an agent's query fallback and automatic compaction once its token is revoked; a schedule a run made once the run's agent session is revoked; old runs, turns and schedules with no chain, and a person identity that names none; device revocation against a turn's call (no deadlock). [`packages/kernel/test/authority-capability.test.ts`](../../packages/kernel/test/authority-capability.test.ts) checks the capability: the compiler refuses a protected read without it or with an object passed off as it, Authority.ts exports no way to make one, and the lint rule refuses every cast to it. The fourth review's regressions, in `authority-chain.test.ts` and [`registry/test/connection-authority.test.ts`](../../registry/test/connection-authority.test.ts): removing a member waits for their in-flight deferred call and refuses the next; a removal the call waited for refuses it; a removed member's agent reads no skill; a token scoped to `agent.send` reads no view through the query fallback; a token that expires while the assertion waits for its row; an agent session and a webhook's journalled identity recorded before chains were; a one-time consent stays unused while its business approval is pending, is used when the approved call runs, and can be withdrawn until then; a sync page fetched before a disconnect is discarded. Guarantee 10 is a property ([`packages/testing/test/surfaces-property.test.ts`](../../packages/testing/test/surfaces-property.test.ts), fixture module [`fixtures/surf`](../../packages/testing/test/fixtures/surf/module.ts)): generated actors (members with roles and groups, people no longer members, sessions, agent sessions, API tokens with and without a scope, OAuth tokens, service principals), records, actions of every kind (untargeted, exact, best effort, consent-marked, approval-ruled, hidden by policy, in a disabled agent tool group), inputs, conflicting inputs and keys; each case's call goes through all eight surfaces from the same records, and every surface is checked against one model of the path and against the others (the first call; a call held for consent approved by the person and made again; a call held for business approval approved and run as it was made; the actor leaving before the same call again; the same key from another surface; the conflicting call; the identity its handler saw; audit records, outbox events and resulting records), and every listing against `reach`. Its scheduled jobs are set up with the actor's own credential, through consent and approval. Twelve examples that always run (among them, schedules set up through an approval whose chain is then revoked) and 12 seeded cases, about a minute (`ELOXIV_SURFACES_PROPERTY_CASES`, `ELOXIV_SURFACES_PROPERTY_SEED`); it caught the consent stage holding a service principal's call for a person who does not exist.
254
+
255
+ ## Not yet guaranteed
256
+
257
+ - **Reconciling a create**: an event creation whose outcome is uncertain is `unknown`; the capability contracts do not yet pass an id a provider honours (Graph's event `transactionId`, a client-chosen Google event id) that would let it be found or retried safely. Messaging's `sendMessage` has no reconciliation either.
258
+ - **Constraint disclosure, two stated limits** (backlog 1): a key the caller names in an untargeted or best-effort insert discloses whether a record holds it (derive keys callers name with `recordKey`); deleting a referenced record fails while any record references it, readable or not, and says only that (`ActionFailed`); both are accepted limits (owner decision, 2026-11-16). The other constraint channels a caller can reach are closed (see [scaffold.md](../scaffold.md) "The action contract"): references are guarded, unique keys a writer could meet unreadable records on are refused at setup. Trusted module code keeps two caveats (scaffold known gap 11): its own `BEFORE INSERT` trigger can change a row after the reference guard, and a subscriber's later visible effect can disclose a unique-key outcome on an entity no action declares.
259
+ - **Policy coverage** (backlog 4, resolved): the compiler's subset fails closed outside it, and compiled filters are keyed on the policy set's version; what stays refused is in [the spike](../spikes/cedar-policy-to-sql.md#limits-and-follow-ups). Row-level security needs setup to run again after a policy change.
260
+ - **Business approvals and consent** are specified by their own contracts: [Approvals](approvals.md), [ActionConsent](action-consent.md).
@@ -0,0 +1,110 @@
1
+ # LocalClient
2
+
3
+ The protocol native clients reach the client core through (decision 14). A host that cannot run the TypeScript client core in process (the Rune desktop host) talks to the device daemon instead: the daemon signs the person in, holds their session and the replica, and serves the core as JSON over HTTP plus one server-sent event stream under `/client/v1` on its loopback relay. Native types are generated from this contract's JSON Schema, never written by hand.
4
+
5
+ - Kind: shell contract. Version 1.2.0 (1.2.0: the offline start, a signed-in session's `offline` and the `offlineStart` feature; 1.1.0: the agent's run events and readiness, and a write's or call's expected `generation`; each additive: an older client is served unchanged).
6
+ - Schema: [`packages/contracts/schema/contracts/LocalClient.json`](../../packages/contracts/schema/contracts/LocalClient.json) (source [`LocalClient.ts`](../../packages/contracts/src/contracts/LocalClient.ts)); for code generation, the same types as one document with every type under `$defs` by name and tagged unions as `oneOf`, an empty struct as `{ type: "object" }`: [`packages/contracts/schema/codegen/LocalClient.json`](../../packages/contracts/schema/codegen/LocalClient.json) (`codegenBundle` in [`Catalog.ts`](../../packages/contracts/src/Catalog.ts)); the MAKE view types a native renderer draws are bundled the same way in [`codegen/Sandbox.json`](../../packages/contracts/schema/codegen/Sandbox.json).
7
+ - Implementation: `@eloxiv/daemon` composed with a `clientApp` ([`Client.ts`](../../packages/daemon/src/Client.ts)), over `ClientRuntime` from `@eloxiv/client/runtime` ([`Runtime.ts`](../../packages/client/src/Runtime.ts)).
8
+ - Kit: `@eloxiv/testing/conformance/LocalClient` ([source](../../packages/testing/src/conformance/LocalClient.ts)).
9
+
10
+ ## Who may use it
11
+
12
+ Every route needs a local token (`Authorization: Bearer ...`) except the sign-in callback. Only two kinds of caller are accepted: the **host** (the per-launch secret it handed the daemon in `ELOXIV_DAEMON_HOST_SECRET`, at least 32 characters) and local clients paired with kind **`desktop-app`**. A harness's per-turn token, a companion (`browser-extension`, `computer-use`), the shell and a CLI are refused with `Forbidden`: the person's session is the native app's, never an agent's. A daemon composed without a `clientApp` answers every `/client/v1` route with `404 ClientNotConfigured` and behaves as before otherwise.
13
+
14
+ ## Operations
15
+
16
+ | Operation | Route | Body | Answer |
17
+ | --- | --- | --- | --- |
18
+ | `hello` | `GET /client/v1/hello` | | `Hello`: `{ protocol: "eloxiv.local-client", version: "1.2.0", features, app: { queries, mutators, actions } }`; `features` are `snapshots`, `optimisticWrites`, `actions`, `desktopSignIn`, since 1.1.0 `runEvents` and `agentReadiness`, and since 1.2.0 `offlineStart` |
19
+ | `session` | `GET /client/v1/session` | | `SessionState` |
20
+ | `signIn` | `POST /client/v1/sign-in` | `{}` | `SignInStarted`: `{ url, state }`. The daemon has bound its callback before answering; the host opens `url` (the app's web sign-in page with `challenge`, `redirect_uri` and `state`) in the system browser. The session becomes `signingIn` |
21
+ | `signInCallback` | `GET /client/v1/sign-in/callback?code&state` | | A small HTML page ("You can return to the app"). Browser-facing: no token, checked by its `state`, accepted once and within 60 s of `signIn`. The daemon redeems the code with the PKCE verifier it kept, keeps the session and emits `session`. A wrong, used or expired state answers `400` and redeems nothing |
22
+ | `selectOrg` | `POST /client/v1/org` | `{ orgId }` | `{ generation }`. Must be one of the person's organisations. Emits `context` (reason `org`), then `session` |
23
+ | `signOut` | `POST /client/v1/sign-out` | `{}` | `{ ok: true }` once the kernel confirmed the revocation (the session is `signingOut` until then; the revocation is retried). Emits `context` (reason `signOut`) and `session` |
24
+ | `events` | `GET /client/v1/events` | | `text/event-stream`: each event one `data:` line holding one `Event`; a heartbeat comment (`: heartbeat`) every 15 s |
25
+ | `subscribe` | `POST /client/v1/subscriptions` | `{ query, args?, id? }` (`id`: client-chosen) | `{ id, generation }`; the first `rows` event follows on the stream. Refused while signed out (`NotSignedIn`); an unknown query is `UnknownQuery`, arguments the query refuses `InvalidInput` |
26
+ | `unsubscribe` | `DELETE /client/v1/subscriptions/:id` | | `{ ok: true }`; another client's or an unknown id is `UnknownSubscription` |
27
+ | `write` | `POST /client/v1/writes` | `{ mutator, input, id?, generation? }` (`generation`, 1.1.0: the one the write was made in) | `{ id, generation }` once the prediction is in the replica; `write` events follow. An unknown mutator is `UnknownMutator`; an input the action's schema refuses is `InvalidInput`, and nothing is predicted or sent; so is a write made in another `generation` than the current one (`StaleGeneration`, guarantee 10) |
28
+ | `action` | `POST /client/v1/actions/:name` | `{ input?, idempotencyKey?, generation? }` (`generation`, 1.1.0: the one the call was made in) | The action's result envelope (`{ kind: "output", output }`, or `{ kind: "replay", receipt }` for a replayed idempotent call), or its typed error, as the person in the selected organisation. Covers the app's actions, the kernel's (`agent.send`, `consent.approve`, `approvals.approve`, ...), `make.view` and `make.renderView`, and installed MAKE modules' actions. A call made in another `generation` than the current one is refused with `StaleGeneration` and not run (guarantee 10) |
29
+ | `followRun` (1.1.0) | `POST /client/v1/runs` | `{ runId, after?, id? }` (`after`: the last stored event seen, default -1; `id`: client-chosen) | `{ id, generation }`; the run's `run` events follow on the stream, for this client only. Refused while signed out (`NotSignedIn`); an id in use is `InvalidInput`. A run that is not the person's, or not of the selected organisation, is the kernel's to refuse: the subscription then ends with that `error` |
30
+ | `unfollowRun` (1.1.0) | `DELETE /client/v1/runs/:id` | | `{ ok: true }`; another client's, an unknown or an ended one is `UnknownSubscription` |
31
+ | `agentReadiness` (1.1.0) | `GET /client/v1/agent/readiness` | | `EngineReadiness`: `{ state: "configured" \| "missing" \| "unavailable" \| "unknown", provider, model, detail }`, the kernel's `GET /agent/readiness` for the person in the selected organisation; `unknown` when the kernel could not be asked (a failed probe is never `missing`); a refusal of the caller is its typed error |
32
+
33
+ Errors are JSON `{ _tag, message, ...fields }`: the standard invocation errors (`Unauthenticated`, `Forbidden`, `ApprovalRequired`, `ConsentRequired`, `IdempotencyConflict`, `InvalidInput`, `UnknownAction`, `ActionFailed`, `ClientOutdated`) and the protocol's own: `ClientNotConfigured` (404), `NotSignedIn` (409), `UnknownSubscription`, `UnknownQuery`, `UnknownMutator` (404), `StaleGeneration` (409), `SignInFailed` (400 or 502), `ProtocolVersion` (400). The whole set is the `LocalClientError` type.
34
+
35
+ ## Records
36
+
37
+ ```
38
+ SessionState =
39
+ | { state: "signedOut" }
40
+ | { state: "signingIn" }
41
+ | { state: "signedIn", user: { id, email, name }, organizations: { orgId, name, roles }[], orgId: string | null, generation, offline?: true }
42
+ | { state: "signingOut" }
43
+
44
+ Event =
45
+ | { seq, type: "session", session: SessionState }
46
+ | { seq, type: "context", generation, reason: "org" | "signOut" | "needsAuth" }
47
+ | { seq, type: "rows", subscription, generation, status: "unknown" | "cached" | "complete" | "error", rows: JSON[], error?: InvocationError }
48
+ | { seq, type: "write", id, generation, phase: "predicted" | "confirmed" | "rejected" | "notConfirmed", error?: InvocationError, message? }
49
+ | { seq, type: "connection", state: "connecting" | "connected" | "disconnected" | "needsAuth" }
50
+ | { seq, type: "run", subscription, generation, event?: AgentRunEvent, error?: InvocationError } (1.1.0)
51
+
52
+ AgentRunEvent = { runId, seq, type: RunEventKind, data: JSON, at }
53
+ ```
54
+
55
+ A `run` event carries the run's next event (`AgentRunEvent`, the chat SDK's `RunEvent` as `chatClient.events` delivers it: `text-delta` with `seq: -1` and `data: { delta, step, attempt }`; `consent-required` with `data: { consentId, action, toolCallId, step }`; `model-step` with `data: { step, text }`; `run-finished`; ...), or, with no `event`, the kernel's refusal of the stream (`error`) that ended the subscription.
56
+
57
+ A `rows` event with status `error` and a `rejected` write carry the same kind of `error`: the kernel's typed invocation error (the sync server's refusal of the query, else `ActionFailed` naming the query). `notConfirmed` carries a plain `message` instead: nothing refused it, the outcome is unknown.
58
+
59
+ `seq` starts at 1 on each stream and increases by one per event; the first event on a stream is the current `session`. A subscription's snapshots, a write's outcomes and a run's events are sent only to the client that made them; `session`, `context` and `connection` events to every client. A client may name the major version it speaks in `x-eloxiv-local-client: 1.0.0`; another major is refused with `ProtocolVersion`. When a person signs in, the first organisation they belong to (the oldest membership, as the kernel's own default) is selected, so `orgId` is null only for a person in no organisation.
60
+
61
+ ## Guarantees
62
+
63
+ 1. **No kernel credential leaves the daemon.** No answer, event or page carries the person's session token, the device credential or any other kernel credential; the daemon keeps the person's session in its secret store under a key of its own (never in `state.json`), apart from the device credential. The kernel and zero-cache URLs it sends the session to must be `https`, or `http` on loopback only (the rule for pairing with a kernel): a daemon composed or configured with any other refuses to start, before the session is loaded.
64
+ 2. **The callback cannot be forged or replayed.** Only a `state` the daemon issued for a sign-in started through `signIn`, within 60 s, once, is accepted; anything else answers `400` and redeems nothing. The verifier never leaves the daemon, so a code intercepted on its way is useless elsewhere.
65
+ 3. **One context at a time.** The selected organisation has a generation, advanced by every organisation change, sign-out and `needs-auth`. Before the reset is announced, every view of the old context is destroyed and its replica closed; then `context` is sent, then `session`. Every `rows` and `write` event carries its generation, and after a `context` event no event of an older generation is ever sent (late results of an old replica are dropped). Subscriptions do not survive a reset: subscribe again in the new context.
66
+ 4. **Snapshots are the replica's.** `rows` events carry the full result of the subscription's named query as the replica holds it (policy-filtered by the kernel), copied out of Zero's view; version 1 sends the whole result on every change.
67
+ 5. **Optimistic writes are the core's, not the client's.** A write goes through the app's generated mutator (the same prediction the web uses, a module's own custom prediction included: it runs in the daemon's core, so a native host writes `hello.wave` exactly as `hello.greet`) and is reported `predicted`, then `confirmed`, `rejected` or `notConfirmed`. `rejected` carries the kernel's typed error (`Forbidden`, `InvalidInput`, `ApprovalRequired` with its id, ...) and is sent only after the replica dropped the prediction, so the next `rows` already reflect it. `notConfirmed` means the replica went offline or closed first: the write may still run. No native client predicts or rolls back anything itself.
68
+ 6. **One stream per client.** A new `events` stream from the same client closes the previous one; closing a stream destroys every subscription the client made.
69
+ 7. **Sign-out stops reads first.** It moves to `signingOut` and resets the context before the revocation is sent; it answers once the kernel confirmed it, retrying, and the stored session is forgotten only then. A sign-in still completing when the person signs out, the sign-in is cancelled or replaced, or the daemon stops adopts nothing: a session its code already redeemed is revoked exactly once and never stored or reported, also while its account is being checked (the session is stored only once its account was checked and the attempt is still current) and when that check fails while a sign-out waits; a sign-out with a session in the secret store revokes and forgets it even when no session is signed in.
70
+ 8. **`needs-auth` resets.** When the sync server refuses the session, the context resets (reason `needsAuth`) and the session is checked again with the kernel: a session the kernel refuses is forgotten (`signedOut`).
71
+ 9. **A run's events are the chat SDK's, once each (1.1.0).** A run subscription is `chatClient.events(runId, after)` inside the core: a connection to the kernel that drops or fails without a definitive answer is followed by another from the last stored event delivered, so a consent asked meanwhile, or the run's end, is never missed; each stored event reaches the client at most once (by its `seq`, whatever a reconnection repeats), streamed text as it comes. It ends after the event of type `run-finished`, or with the kernel's refusal (`error`); nothing of it follows either. Like a row subscription it is the client's own, destroyed when its stream closes, and ended by every context reset before the `context` event: no `run` event of an older generation is ever sent. Nothing of a subscription follows its end, not even an event the core had queued before it (unfollowed, its stream closed or replaced, a reset); `run-finished` and a refusal, which end it themselves, are still delivered.
72
+ 10. **A request runs only in the context it was made in (1.1.0).** A write or a call may name the `generation` the client made it in. The daemon checks it against the current generation after every context change asked before it has finished, and before anything runs: in another, it is refused with `StaleGeneration` naming the **current** generation, and nothing is predicted, sent or run, so a send made in one organisation never runs in the next (another local client may have switched the shared daemon). `StaleGeneration` naming the request's **own** generation means the context changed while it ran: it may have run (a send is then resent under its key). A client retrying a request keeps the generation it was first made in. Without `generation` (a 1.0.0 client), the current context is used.
73
+
74
+ 11. **An offline start shows the device's copy, and says so (1.2.0).** The daemon keeps the person's session in the secret store and, beside `state.json`, the person and organisation last open with it, bound to the token by its SHA-256 digest (never the token; `person-context.json`, 0600). One daemon serves LocalClient per state directory: a second one on the same canonical directory refuses to start while the first runs (`person-session.lock`, holding its process id; a lock left by a process that is gone is taken over), and a recall reads the context only after the secret store answered. A daemon that starts without reaching the kernel reports that person signed in, in that organisation alone, with `offline: true`, and serves its replica from disk at once: subscriptions answer from it and writes are predicted in it (pushed when the sync server is reachable again, within the sync engine's disconnect timeout of one minute; after it a write is `notConfirmed` with nothing predicted). Selecting another organisation is refused meanwhile (`ActionFailed`). When the kernel accepts the session, the same context goes on (same generation, `offline` gone, a `session` event), its organisations listed in the background: nothing waits on that listing. When it refuses it, the context resets and the session and its context are forgotten (guarantee 8). Nothing opens for another token, after a sign-out (the context is forgotten before the revocation is sent, whether or not the kernel confirms it; once the kernel confirms it the session goes from the secret store even when the context file cannot be removed, and the sign-out fails only when neither could be), or once the kernel listed the person in no organisation. Limit: rows synced in the last second before the daemon stopped may not be on disk (the sync engine writes its store a second after it settles).
75
+
76
+ ## The agent through LocalClient
77
+
78
+ A native chat screen needs nothing beyond the operations above (the reference is the Rune host's, [`desktop-rune`](../registry/desktop-rune.md)); the guarantees that are hard to get right are the chat SDK's ([client SDK, "The chat SDK"](client-sdk.md#the-chat-sdk)), and a native host keeps its state the same way:
79
+
80
+ - **Conversations, messages, runs and approvals are rows**: subscribe to the app's named queries `agent.conversations`, `agent.messages` (filter by conversation), `agent.runs` and `approvals.requests` (an app with the kernel's agent and inbox modules has them; `hello.app.queries` names them).
81
+ - **Sends and decisions are actions**, each with the `generation` it was made in (guarantee 10), under the chat SDK's idempotency keys: `agent.send` (`{ text, conversationId? }`) under a key made once per send and kept until the send settles (a retry under it is a `replay`, never a second run; a native host keeps its outstanding sends per person and organisation outside the screen, as chat SDK guarantee 4 says, and the Rune host in a file of its own, which hosts sharing its data directory change under a lock, each to the file as it is then); `consent.approve` and `consent.reject` (`{ id }`) under `consent:<consentId>:<approve|reject>:<remember>` (`decisionKey.consent`); `approvals.approve` and `approvals.reject` under `approval:<approvalId>:<decision>`; `agent.cancel` (`{ runId }`) under `cancel:<runId>`. They are the person's: the daemon refuses every caller but the host and desktop apps (DM-16), and the kernel refuses an agent.
82
+ - **The run's progress is a run subscription** (`followRun` with the `runId` the send answered): streamed text by model step until the replica holds the step's stored answer, `consent-required` until `consent-decided` or the run's end, `run-finished` ending the run at once.
83
+ - **Whether the agent can answer** is `agentReadiness`: while it is `missing` or `unavailable` the composer keeps its draft and does not send.
84
+
85
+ ## Composing an app's sidecar
86
+
87
+ The generic daemon knows no app. An app builds its own sidecar from an entry that imports its composition and calls the daemon's `runMain` with a `clientApp`. The [`desktop-rune`](../registry/desktop-rune.md) item ships one, `desktop-rune/sidecar/daemon.ts` (`daemon-node.ts` on Node; hello-app's, installed by `eloxiv add desktop-rune`: [`examples/hello-app/desktop-rune/sidecar/daemon.ts`](../../examples/hello-app/desktop-rune/sidecar/daemon.ts)):
88
+
89
+ ```ts
90
+ import { runMain } from "@eloxiv/daemon/runtime/bun"
91
+ import { contracts } from "../../eloxiv.modules.ts"
92
+ import { mutators, queries, schema } from "../../eloxiv.sync.ts"
93
+
94
+ runMain(process.argv.slice(2), process.env, { clientApp: { modules: contracts, schema, queries, mutators } })
95
+ ```
96
+
97
+ `clientApp` also takes `kernelUrl`, `zeroUrl` (default `ELOXIV_KERNEL_URL`, `ELOXIV_ZERO_URL`), `signInPage` (the app's web page that approves a desktop sign-in, given `challenge`, `redirect_uri` and `state`; default `ELOXIV_SIGN_IN_PAGE`, else the web shell's `/desktop/sign-in` at `shellUrl`), `shellUrl` (the web shell's origin; default `ELOXIV_SHELL_URL`, else `http://localhost:5173`, the shell's development server) and `clientVersion`. The replica lives in `<state dir>/replicas` (SQLite through `bun:sqlite` or `node:sqlite`). `node desktop-rune/scripts/build-sidecar.ts` compiles it like the generic sidecar (`@eloxiv/daemon/build-sidecar` with `--entry` and `--name`) into `desktop-rune/target/sidecar/eloxiv-daemon`. A host starts it with a per-launch `ELOXIV_DAEMON_HOST_SECRET` (at least 32 characters) and `--stdin-lifeline`, waits for `/health`, and uses `/client/v1` with that secret.
98
+
99
+ ## How an implementation is checked
100
+
101
+ `localClientConformance(subject)` takes a `LocalClientSubject`: a daemon serving LocalClient for the registry's app, over a real kernel and zero-cache, with the host's secret, the tokens of other kinds of caller to refuse, a second person's client to make changes from, a way to play the browser (sign in by password and approve the desktop sign-in), and optionally the app's agent on a scripted model (a prompt whose turn asks for a consent-marked call, the action it names and the answer it gives). Its checks: `hello`; sign-in through the daemon's callback; a wrong and a replayed state refused with nothing redeemed; the session; listing and switching organisations, with the `context` reset before any row of the new organisation and no event of the old generation after it; a subscription's first snapshot and another person's change arriving; an optimistic write predicted, then confirmed; a refused write rejected with `Forbidden` after the rollback; a non-optimistic action call; a write not confirmed while the sync server is unreachable (when the subject can cut it off); harness, companion, shell and CLI tokens refused, and `ClientNotConfigured` from a daemon without an app; no kernel credential in any answer or event; closing the stream destroying its subscriptions; sign-out revoking the session and resetting; a call and a write made in the generation before a switch refused with `StaleGeneration` naming the current one, and run nowhere (1.1.0); with an agent (1.1.0): readiness, an agent turn through the protocol alone (`agent.messages` and `agent.runs` subscribed, `agent.send` as an action under its key and replayed under it, the run followed: streamed deltas, `consent-required`, approved with `consent.approve` under the decision's key, `consent-decided`, `run-finished` last, each stored event once and in order, the streamed answer the one the replica then holds), and a followed run of the first organisation sending nothing after the switch (its subscription gone; following it from the second ends with the kernel's refusal); with a restart (1.2.0, `restart`: the daemon stopped and started again in place with the kernel and the sync server unreachable, then reachable): the remembered person and organisation reported `offline`, its rows from disk, a write predicted, then the same context checked (`offline` gone, every organisation) and the write confirmed. Eloxiv's daemon runs it on Bun and on Node in [`registry/test/local-client.test.ts`](../../registry/test/local-client.test.ts) (in process, composed with the registry app, the replica in `bun:sqlite` or `node:sqlite`, zero-cache and the kernel behind proxies the test cuts for the not-confirmed write and the offline restart, the agent on a scripted OpenAI-compatible model, `startScriptedChatModel` from `@eloxiv/testing`, whose turn moves the person's agent resources, `agent.moveResources`, a consent-marked call); [`registry/test/daemon-session-store.test.ts`](../../registry/test/daemon-session-store.test.ts) runs the offline start's custody kit over the daemon's person session; [`packages/testing/test/client-runtime-runs.test.ts`](../../packages/testing/test/client-runtime-runs.test.ts) checks the core's run subscriptions against a stubbed kernel (each stored event once across reconnections, a refusal as the subscription's error, every run stopped by a reset with nothing after the `context` event, readiness); [`registry/test/app-daemon.test.ts`](../../registry/test/app-daemon.test.ts) starts hello-app's own sidecar (the item's entry) as a process; [`registry/test/desktop-rune-journey.test.ts`](../../registry/test/desktop-rune-journey.test.ts) drives the Rune host against it live (decision 14's journey: sign-in through the web shell's approval page, live rows, an optimistic write a second client receives, a refused write rolled back with `Forbidden`, an agent turn on the scripted model with its consent approved in the chat screen, an organisation switch, a MAKE view step with a call, sign-out).
102
+
103
+ ## Not yet guaranteed
104
+
105
+ - **Snapshots only.** Every change sends the whole result; there is no size bound beyond the query's own `limit`, and no diff format yet (a later minor version may add one as a feature `hello` names).
106
+ - **No resume.** A dropped stream loses its subscriptions; reconnect, subscribe again and take the first snapshot. `seq` has no replay. A run subscription lost with its stream is followed again with `after` set to the last stored event the client saw (the chat SDK's own resume).
107
+ - **Write outcomes are not kept across a daemon restart**, nor across a context reset: a write still in flight when the organisation changes is not reported (it may still run).
108
+ - **Close is not delete.** Signing out closes the replica; its SQLite file stays on disk under the daemon's state directory until dropped.
109
+ - **The approval page is the web shell's.** The default `signInPage` is the reference shell's `/desktop/sign-in` (shell-foldkit 0.6.0) at `ELOXIV_SHELL_URL`; an app without that shell, or serving it elsewhere, sets `signInPage` or `ELOXIV_SHELL_URL`. The kernel serves no page of its own, and the kit plays the page itself (the shell's is checked by its own tests and `e2e/desktop-sign-in.spec.ts`).
110
+ - **One person per daemon.** The daemon holds one person session; every desktop-app client of the same daemon shares it and its selected organisation.