@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,45 @@
1
+ # StorageAdapter
2
+
3
+ Where a client's local replica lives (decision 7): IndexedDB on the web, SQLite on desktop, servers and mobile, memory for tests. The replica is a transactional key-value store (Zero's store interface); an adapter is what `connectSync({ storage })` takes.
4
+
5
+ - Kind: shell contract. Version 1.0.0.
6
+ - Schema: [`packages/contracts/schema/contracts/StorageAdapter.json`](../../packages/contracts/schema/contracts/StorageAdapter.json) (source [`StorageAdapter.ts`](../../packages/contracts/src/contracts/StorageAdapter.ts)).
7
+ - Implementation: `@eloxiv/client/storage` ([`Storage.ts`](../../packages/client/src/Storage.ts)): `indexedDbStorage()`, `sqliteStorage(open, options)`, `memoryStorage()`; and `expoSQLiteStoreProvider` in `@eloxiv/client/expo-sqlite` on React Native.
8
+ - Kit: `@eloxiv/testing/conformance/StorageAdapter` ([source](../../packages/testing/src/conformance/StorageAdapter.ts)).
9
+
10
+ ```ts
11
+ import { sqliteStorage } from "@eloxiv/client/storage"
12
+ import { Database } from "bun:sqlite" // or: import { DatabaseSync } from "node:sqlite"
13
+
14
+ const replica = sqliteStorage((file) => new Database(file), { directory: stateDir })
15
+ const zero = connectSync({ server, schema, userId, token, orgId, storage: replica.storage })
16
+ ```
17
+
18
+ | Adapter | Where | Durable | How |
19
+ | --- | --- | --- | --- |
20
+ | `indexedDbStorage()` | browsers, webviews (the Tauri desktop host included) | yes | Zero's IndexedDB store (`"idb"`) |
21
+ | `sqliteStorage(open)` | desktop processes, servers, the daemon | yes | Zero's `SQLiteStore` over any synchronous SQLite binding (`bun:sqlite`, `node:sqlite`); the SDK imports none itself, so it stays portable. One file per person and organisation in `directory`. `drop` wipes the store in place (its table dropped, the file vacuumed, the WAL truncated) and fails if anything is left; `remove`, if given, also deletes the files |
22
+ | `expoSQLiteStoreProvider()` | React Native | yes | Zero's expo-sqlite store |
23
+ | `memoryStorage()` | anywhere | no | Zero's memory store (`"mem"`) |
24
+
25
+ **Tauri's own SQLite**: not provided. Zero's SQLite store opens transactions with synchronous `BEGIN`/`COMMIT` on one connection, and `tauri-plugin-sql` offers only asynchronous calls over a connection pool, so it cannot back the store. The desktop host's webview uses IndexedDB, which WebKitGTK, WKWebView and WebView2 all provide; a native SQLite replica on desktop goes through the daemon sidecar instead, as the Rune host's does (LocalClient: the daemon's client core on `sqliteStorage`, [desktop-rune](../registry/desktop-rune.md)).
26
+
27
+ ## Operations
28
+
29
+ The store interface, as records: `info` (`{ kind, durable, platforms }`), and on a named store `get`, `has`, `put`, `del`, `commit`, `close` and `drop`. `put`, `del` and `commit` happen in a write transaction; `get` and `has` in a read or write transaction. Errors: `StoreClosed`, `StorageFailure`.
30
+
31
+ ## Guarantees
32
+
33
+ 1. **Transactions**: a write's changes are visible to it at once, to others on commit, and never if it is released without committing; many readers or one writer (a writer waits for readers).
34
+ 2. **Isolation by name**: one store per person and organisation (`connectSync` names it from the user and `orgId`), so two never share rows.
35
+ 3. **Durability**: a durable adapter keeps a store across closing it, and the replica reopened with no server to reach reads its rows from storage.
36
+ 4. **Policy holds in storage too**: a replica stores only rows its person may read in its organisation.
37
+
38
+ ## How an implementation is checked
39
+
40
+ `storageAdapterConformance({ adapters, system })` runs, for each adapter, the store checks (when it exposes its store provider: commit and abandon, readers and a waiting writer, isolation, durability across close, drop, a closed store) and the replica scenario against a real kernel and zero-cache: another person's org-visible write arrives, a private one never does, a second organisation's replica is a store of its own, and a durable replica reopened against an unreachable server reads the row back. Eloxiv's adapters run it in [`registry/test/storage-adapter.test.ts`](../../registry/test/storage-adapter.test.ts): SQLite over `bun:sqlite` (Bun) or `node:sqlite` (Node), IndexedDB over `fake-indexeddb` (standing in for a browser's; the browser's own IndexedDB holds the shell's replica in the Playwright suites), and memory. `expo-sqlite` runs the replica, offline included, in CI's React Native lane ([`tools/react-native/journey.ts`](../../tools/react-native/journey.ts)).
41
+
42
+ ## Not yet guaranteed
43
+
44
+ - **No OPFS adapter**: Zero has no OPFS store, and an OPFS SQLite store needs a synchronous file handle, which only a worker has.
45
+ - **No encryption at rest** of the replica beyond the platform's own (disk encryption, the browser profile).
@@ -0,0 +1,56 @@
1
+ # StorageBackend
2
+
3
+ Where the bytes of files live (decisions.md "Capability contracts"; ledger A-045, C-055). A capability the deployment chooses, never a module's: the [Files](files.md) contract keeps every file's metadata, attachment and authorisation in the kernel's tables and hands the backend opaque keys it made itself.
4
+
5
+ - Kind: capability. Version 1.0.0.
6
+ - Schema: [`packages/contracts/schema/contracts/StorageBackend.json`](../../packages/contracts/schema/contracts/StorageBackend.json) (source [`StorageBackend.ts`](../../packages/contracts/src/contracts/StorageBackend.ts)).
7
+ - Implementations: a local directory ([`LocalStorage.ts`](../../packages/kernel/src/files/LocalStorage.ts), development and tests) and any S3-compatible object store ([`S3Storage.ts`](../../packages/kernel/src/files/S3Storage.ts): AWS S3, MinIO, R2, Garage, rclone's `serve s3`), with Signature Version 4 written on web-standard crypto ([`SigV4.ts`](../../packages/kernel/src/files/SigV4.ts)). The in-process interface is `StorageBackendShape` ([`Storage.ts`](../../packages/kernel/src/files/Storage.ts)).
8
+ - Kit: `@eloxiv/testing/conformance/StorageBackend` ([source](../../packages/testing/src/conformance/StorageBackend.ts)).
9
+
10
+ ## Choosing a backend
11
+
12
+ `ELOXIV_STORAGE` (or `KernelConfig.storage`, or a layer in `KernelOptions.storage`):
13
+
14
+ | Value | Backend |
15
+ | --- | --- |
16
+ | `local:<directory>` | A local directory, for one kernel process. Objects are stored under the SHA-256 of their key, so no key names a path; each put writes a new version file and changes to one key run one at a time, so concurrent puts and reads always see one whole version |
17
+ | `s3://<bucket>?endpoint=<url>&region=<region>[&prefix=<p>][&pathStyle=false]` | An S3-compatible store; credentials in `ELOXIV_STORAGE_ACCESS_KEY_ID` and `ELOXIV_STORAGE_SECRET_ACCESS_KEY`. Path-style addressing unless `pathStyle=false` (AWS's virtual-hosted style). `prefix` keeps one deployment's keys apart in a shared bucket |
18
+
19
+ An app that installs the kernel's `filesModule` without a backend gets a local `.eloxiv/storage` directory in development and is refused in production.
20
+
21
+ ## Operations
22
+
23
+ Bodies are bytes in process; the JSON form carries them base64-encoded.
24
+
25
+ | Operation | What it does |
26
+ | --- | --- |
27
+ | `capabilities` | `signedUrls`, `multipart`, `ranges`: what the backend does beyond the core operations |
28
+ | `put` | Store an object, replacing any object at the key atomically (a reader sees the old or the new, whole) |
29
+ | `get` | The content, whole or an inclusive byte range (a range starting past the end is `StorageConflict`; one ending past it is cut) |
30
+ | `head` | The metadata: size, etag (changes with the content), content type, modification time |
31
+ | `delete` | Delete; deleting a missing object succeeds |
32
+ | `list` | Objects under a prefix in key (byte) order, a page at a time with a cursor; unfinished multipart uploads are not listed |
33
+ | `signedUrl` | A URL a client uses directly: `GET` (with response type and disposition overrides) or `PUT` of exactly `contentLength` bytes, or one multipart part. It works until it expires (1 s to 7 days) and cannot be revoked before |
34
+ | `createMultipart`, `uploadPart`, `listParts`, `completeMultipart`, `abortMultipart` | Multipart uploads: parts (1 to 10000) in any order, again on retry; `listParts` is how an upload resumes; completion assembles exactly the named parts in part order, each by the etag its upload returned; nothing is visible at the key before |
35
+
36
+ **Keys** are 1 to 1024 characters of `A-Z a-z 0-9 / _ . = -`, with no empty, `.` or `..` segment and no leading or trailing `/` (`STORAGE_KEY_PATTERN`). Every backend refuses any other key with `StorageInvalid` before touching anything, so a key cannot escape its backend.
37
+
38
+ **Errors:** `StorageNotFound`, `StorageConflict` (a part list that does not match, a range past the end), `StorageInvalid` (a bad key or part number, a missing capability), `StorageUnavailable` (unreachable, the deployment's credentials refused, with the store's status).
39
+
40
+ ## Guarantees
41
+
42
+ 1. Bytes come back exactly as stored; an object is replaced atomically.
43
+ 2. No key outside `StorageKey` is accepted; the local backend writes nothing outside its root.
44
+ 3. A multipart upload is invisible until completed, and completes only from the parts named with the etags they were uploaded with.
45
+ 4. A signed URL works for exactly what was signed (method, key, length, overrides) and only until it expires.
46
+ 5. A backend authorises nothing: the kernel issues keys and signed URLs only after its own policy checks ([Files](files.md)).
47
+
48
+ ## How an implementation is checked
49
+
50
+ `storageBackendConformance(name, start)` takes a subject: the backend, its minimum part size, and whether it replaces a part uploaded again with different content (`replacesParts: false` for a store that streams parts through, like rclone's; the same content again must always work). The kernel's runner, [`storage-backend.test.ts`](../../packages/testing/test/storage-backend.test.ts), runs it against the local backend, against the S3 backend talking to an **in-process S3 protocol fake** ([`S3Fake.ts`](../../packages/testing/src/fakes/S3Fake.ts), a stand-in that verifies every Signature Version 4 signature with its own implementation), and, where `rclone` is installed, against a real S3-compatible server (`rclone serve s3`). The signer matches AWS's published S3 examples ([`sigv4.test.ts`](../../packages/kernel/test/sigv4.test.ts)). No container runtime is needed.
51
+
52
+ ## Not yet guaranteed
53
+
54
+ - The S3 backend is proven against the fake and rclone's server, not against AWS S3 itself (no account is set up); CI runs the fake only.
55
+ - Server-side encryption, storage classes and object lock are not exposed.
56
+ - Files uses neither signed URLs nor direct uploads: every byte goes through the kernel's routes, which check each part and each download (see [Files](files.md)).
@@ -0,0 +1,213 @@
1
+ # Sync
2
+
3
+ Policy-scoped partial replication (decisions 2 and 5). Each client keeps a local replica (Zero) per user and organisation, holding only rows its user may read. The same compiled Cedar policy that authorises actions filters what syncs. Writes go through actions: through any surface, or optimistically through the replica, which shows the write at once and keeps the server's answer ([Optimistic writes](#optimistic-writes)).
4
+
5
+ - Kind: kernel service. Version 3.2.0 (1.0.0 refused related queries and required a `shares` relationship; 2.0.0 took `queryEntities`, which the kernel now infers; 3.1.0 adds `mutate`, optimistic writes; 3.2.0: a module may predict a write itself, [custom predictions](#custom-predictions)).
6
+ - Schema: [`packages/contracts/schema/contracts/Sync.json`](../../packages/contracts/schema/contracts/Sync.json) (source [`Sync.ts`](../../packages/contracts/src/contracts/Sync.ts)).
7
+ - Implementation: [`packages/kernel/src/Sync.ts`](../../packages/kernel/src/Sync.ts) (`SyncEndpoint`, `scopeQuery`, `liveBindings`, `syncSchemaProblems`, `SyncMutateEndpoint`; the push bookkeeping in [`db/ZeroPush.ts`](../../packages/kernel/src/db/ZeroPush.ts)); the policy compiler's ZQL output in [`policy/Compiler.ts`](../../packages/kernel/src/policy/Compiler.ts); the client side in `@eloxiv/client` (`connectSync`, the query builder and named queries; the Foldkit adapter in `@eloxiv/client/foldkit`; deprecated React hooks in `@eloxiv/client/react`); the generator in `@eloxiv/cli` (`syncSource`, run by `eloxiv generate`).
8
+ - Kit: `@eloxiv/testing/conformance/Sync` ([source](../../packages/testing/src/conformance/Sync.ts)).
9
+
10
+ An app declares its sync configuration: its sync `schema` and its modules' named `queries` (`eloxiv.schema.ts`, which the server imports, and `eloxiv.sync.ts`, which re-exports it with the generated mutators for clients; both written by the CLI). The schema is generated (decision 9): each module's Zero tables come from its Drizzle tables and entities (`sync.gen.ts`, see [Generated tables](#generated-tables)), so no field, column or query entity is declared twice. A query's entity is the entity whose table it reads. zero-cache replicates the module schemas and five kernel tables (publication `eloxiv_sync`: the sharing grants `eloxiv.share_grant` and link redemptions `eloxiv.share_redemption`, the directory facts `eloxiv.sync_fact` and `eloxiv.sync_org`, and the file metadata `eloxiv.file`, whose Zero table `eloxivFile` is generated from the kernel's Drizzle declaration of it and whose queries the kernel filters by each file's record, see [Files](files.md#sync)) and asks the kernel to resolve each named query for each client. The kernel adds its live tables to the schema it resolves queries with (`withKernelTables`); apps do not declare them, and the names `eloxivSyncOrg`, `eloxivSyncFact`, `eloxivShareGrant` and `eloxivShareRedemption` are reserved. (An app schema may still list `@eloxiv/client/sync`'s `shareGrant` table, which the kernel no longer needs.)
11
+
12
+ ## Operations
13
+
14
+ ### `query`
15
+
16
+ Resolve one named query for the caller. Its entity is inferred: the query's table is resolved through the sync schema to its database table, and that to the registered entity whose table it is (each `related()` and `whereExists()` child the same way). On the wire: zero-cache forwards the client's request to `POST /zero/query` with the client's `authorization` header and, when the client names one, `x-eloxiv-org`. Input `SyncQueryRequest` (`name`, `args`, `headers`); output `ScopedQuery` (`name` and the ZQL `ast` zero-cache runs). Errors:
17
+
18
+ - `Unauthenticated` (HTTP 401): no valid session, or the caller is not a member of the organisation it names;
19
+ - `QueryRefused` (Zero's `{ error: "app", message }`): the query is unknown, reads (or reaches through a child) a table no entity contract governs (a kernel table, say) or carries a permission subquery of its own, or its read filter uses a construct the compiler cannot translate.
20
+
21
+ ### `mutate`
22
+
23
+ Run a client's pushed optimistic writes (see [Optimistic writes](#optimistic-writes)), declarative or [custom](#custom-predictions) alike: the prediction never runs here. On the wire: zero-cache forwards each push to `POST /zero/mutate?schema=<shard>&appID=<app id>` with the client's `authorization` header and, when the client names them, `x-eloxiv-org` and `x-eloxiv-client-version`. Input `SyncPushRequest` (Zero's push: the client group, and its mutations in order, each naming an action and carrying its encoded input); output `SyncPushResponse` (Zero's `MutateResponse`: per mutation `{}` confirmed, `{ error: "app", message, details }` refused with the encoded `InvocationError` as `details`, or `{ error: "alreadyProcessed" }`; or `PushFailed` with `oooMutation` for a mutation out of order). Errors:
24
+
25
+ - `Unauthenticated` (HTTP 401): no valid bearer session (a cookie does not count), or the caller is not a member of the organisation it names;
26
+ - `PushRefused` (HTTP 403, so zero-cache closes the connection): the push names a schema other than the shard zero-cache keeps for the kernel's app id (`ELOXIV_ZERO_APP_ID`, which must equal zero-cache's `ZERO_APP_ID`), or a client another user's pushes already claimed.
27
+
28
+ ### `checkSchema`
29
+
30
+ Check a sync schema against the entity contracts (input: the sync `schema`); output the problems found. The kernel runs it at startup and does not start while there are any.
31
+
32
+ ## Records
33
+
34
+ - **`SyncQueryRequest`**, **`ScopedQuery`**, **`QueryRefused`** as above.
35
+ - **`ReservedSyncTables`**: the Zero table names the kernel reserves.
36
+
37
+ ## Guarantees
38
+
39
+ 1. **The read policy is added to every query.** The kernel runs the module's query, then adds the entity's `read` filter, compiled with the principal unknown exactly as for row-level security, with the caller's user and organisation bound. The same policy authorises actions and filters every database read (see [Invocation](invocation.md)), so what a client syncs is what the caller may read. A policy the compiler cannot translate makes the query fail rather than sync more.
40
+ 2. **Per user and organisation.** The filter uses the organisation the client names (`orgId` in `connectSync`, sent as `x-eloxiv-org`), which the caller must belong to, or their first membership when it names none. Replicas are stored per user and organisation.
41
+ 3. **The policy of the table actually read.** A query's entity is never declared: its Zero table is resolved through the schema to its database table, and the entity is the registered one whose table that is. A query whose table no entity governs is refused.
42
+ 4. **Related tables are authorised per child entity.** A module query may reach related tables with `related()` and `whereExists()` (and their negations). Every subquery's table must be a registered entity's; the kernel adds that entity's own read filter (compiled, bound and live exactly as for the query's own table) to the subquery's rows, recursively for its children. So a parent the caller may read never brings in a child it may not, and a filter on children counts only children the caller may read (`whereExists` is true only if a readable child matches; `NOT EXISTS` only if none does). A subquery reaching a table no entity governs (a kernel table) is refused, and only the kernel adds permission subqueries.
43
+ 5. **Membership in a record's group.** `principal in resource.<attribute>` (an entity-typed column: a group, a user or an organisation) compiles, for a group column, to a live test that the caller is in the group the record names in the acting organisation (a subquery on `eloxiv.sync_fact`, see guarantee 7) for sync and to `eloxiv_ctx.in_group(<column>)` for row-level security; a user column compares with the caller and an organisation column with the acting organisation. This is how work items assigned to a group reach its members (see [WorkItems](work-items.md#sync)).
44
+ 6. **Column mappings are checked before serving.** The generator writes them (see [Generated tables](#generated-tables)); the kernel still refuses to start with a schema that differs, so a stale or edited generated file is caught: every synced entity of an app module has its table (a kernel-provided module's tables all or none), with exactly the generated columns, key, unique keys and relationships (the Drizzle relations and `shares`). Every Zero table over an entity table needs the entity's organisation column (an `Eloxiv::Org` policy attribute), through which the live directory tests reach the facts; the entity must sync (`sync: false` refuses it); every policy-relevant field (each column policy attribute, and the primary key) must exist and read the entity's column; every other column must be a synced field reading its column with the field's type and nullability; every synced field must be there and the primary key must be the entity's; no table may take a reserved name.
45
+ 7. **Directory changes and grants reach connected replicas live.** zero-cache transforms a client's queries when it connects and keeps running them, so neither the directory nor any grant is bound into a transform. Every directory test of the read filter (the caller's membership of the organisation, which every query also requires, each `principal in Eloxiv::Group::"g"`, each `principal in resource.<group attribute>`, `principal.roles` and `principal.permissions` tests, and `principal.email` equality and `like`) is a subquery zero-cache evaluates on its replica against `eloxiv.sync_fact`, which triggers keep equal to the directory (and to Better Auth's user emails) in each change's own transaction, whoever writes it (a management call, a trusted system helper, machine identity or plain SQL): each trigger takes the organisation's directory lock before it reads and recomputes the affected members' facts from committed state once it holds it, so concurrent writers serialise and the second recomputes from what the first committed (a directory change at REPEATABLE READ or SERIALIZABLE, whose snapshot would not move, is refused, and so is `TRUNCATE` of a directory table, which would skip the triggers). Sharing grants are evaluated the same way: a grant to the caller, to a group the caller is in in the acting organisation, to the acting organisation, or a link of the acting organisation the caller redeemed (`eloxiv.share_redemption`), not expired when the query was transformed. A one-hop reference (`resource.folder.owner`) is a subquery on the referenced entity's replicated table. These are Zero permission subqueries: their rows are never sent to clients. Bound: **no row written after a revocation commits is delivered to a replica the revocation affects, and rows it already holds are removed as soon as zero-cache replicates the revoking transaction** (replication lag, typically milliseconds on one host); grants apply the same way, without reconnecting. This covers removing a member, a group membership, a role, a role's permission, a sharing grant of any kind or a link, changing an email, and adding a member to a group a `forbid` names. An expired grant is removed when the kernel's sweep deletes it ([Sharing](sharing.md), guarantee 3).
46
+ 8. **A signed-out session's replica receives nothing more.** Every query a replica runs also tests a live fact naming the session it was transformed with (`eloxiv.sync_fact`, kind `session`): the query endpoint records it while the session holds, and the kernel deletes it in the transaction that ends the session (sign-out, revocation; kernel migration `0048_sync_session_facts`). zero-cache evaluates facts live (guarantee 7), so once that deletion replicates, the replica receives no row of any query, none written after the sign-out and none newly authorised, and the rows it held are withdrawn. The person's other sessions have their own facts and stay connected. The fact exists before the session's first query: it is recorded when the session starts, in every organisation its person belongs to (a trigger on `auth.session`), and when a membership is added, for the person's live sessions (`refresh_sync_facts`; kernel migration `0216_session_facts_at_start`); leaving an organisation removes its session facts there. Those writers are serialised with each other and with the ending of sessions: the session start and every refresh take the person's lock, and a refresh then takes each of the person's sessions' locks shared (the ones sign-out and the set-based ending take), reading only after them; a revocation deletes the session's facts by trigger, after the ending's locks. One global lock order keeps these from waiting on each other: directory locks sorted by organisation (a change of email takes all of the person's before its first refresh), then the person's lock, then sessions' request locks; work that holds a session's row (`Identity.whileSignedIn`, `Authority.assert`'s session link) takes its request lock first, as sign-out does. So a refresh never writes back the fact of a session whose ending had not committed when it read, and a session starting while a membership is added gets its fact there whichever commits first (`session-facts.test.ts`, both races driven on two connections). So it has replicated before a client connects, and a query's first complete answer (Zero's `complete`) is not empty for want of it ([`session-facts.test.ts`](../../packages/testing/test/session-facts.test.ts); [`sync-property.test.ts`](../../packages/testing/test/sync-property.test.ts) compares each replica's first complete answer exactly, with nothing recorded beforehand but the sign-in). The query endpoint still records the fact (a session older than the migration). Exactly what such a replica can still receive: changes that replicate before the sign-out's own commit does (zero-cache applies the replication stream in commit order), and nothing after. Pushes are refused from the sign-out's commit (`Unauthenticated`: a push is an invocation, which asserts the session), and so is every new transform. Revalidation (`ZERO_AUTH_REVALIDATE_INTERVAL_SECONDS`) then disconnects the replica; it is the bound for a session that ends without the kernel (expiry): Zero's default is 300 s, the harness and `mise run dev` set 10 s (`ZERO_REVALIDATE_SECONDS` in `@eloxiv/testing`), and deployments set it to that or less. Connections of one client group (the tabs of one browser profile, sharing its storage) share their queries' transforms; another device is another client group. [`sync-revocation.test.ts`](../../packages/testing/test/sync-revocation.test.ts) signs a session out with revalidation a minute away, then writes the person's own row, makes a whole set of rows newly readable for them, and writes a row of that set: the signed-out replica receives none of it and is emptied.
47
+ 9. **A changed policy set is never served stale by the kernel.** The kernel compiles read filters from `PolicySet` and keys them on its version (a hash of the policy text), read at every request. zero-cache itself caches a transform for 5 s per (query, token, user, headers) and keeps a connected replica's transform until its retransform interval (`ZERO_AUTH_RETRANSFORM_INTERVAL_SECONDS`), so a runtime policy change (MAKE) reaches new connections within 5 s and connected ones at their next retransform; row-level security changes when setup runs again.
48
+ 10. **A read filter's shape stays cheap for zero-cache.** zero-cache runs an OR that holds a subquery as a fan-out and a fan-in, and passes every filter signal down each of its branches to everything after it in the pipeline, so several such ORs in one pipeline (in a row, or nested, as a policy of nested `if`s compiles to) multiply its work for every row: one generated filter took 125 s to hydrate three rows. The kernel moves each such OR, unless it is a (sub)query's whole condition, into a permission subquery of its own over the same row (`EXISTS` by primary key), so each pipeline holds at most one, and keeps identical siblings once (`isolateSubqueryOrs`, `packages/kernel/test/sync-isolate.test.ts`; the case is a fixed example of the sync property).
49
+
50
+ 11. **An optimistic write is an action call.** Each pushed mutation runs as the action it names, through the one invocation path ([Invocation](invocation.md)), as the signed-in person, on surface `sync`: identity, policy, consent or business approval, idempotency, execute (the handler, never the prediction), audit and outbox. Only an action that declares an optimistic effect is a mutator; a push naming any other is refused as `UnknownAction`. The idempotency key is the client and its mutation id (`zero:<client group>:<client>:<mutation id>`).
51
+ 12. **The server's answer is what the replica keeps.** The client's last mutation id advances inside the action's own transaction (before its idempotency claim), so its rows and its confirmation commit together and zero-cache delivers them in one change: the replica drops the prediction and shows the server's rows (an insert's predicted record has the server's primary key, which both derive with `recordKey`, so the confirmed row takes its place). A refused call (`Forbidden`, `InvalidInput`, `ApprovalRequired` with its `approvalId`, `ConsentRequired` with its `consentId`, `ActionFailed` for a conflict or a handler failure, `ClientOutdated`, ...) rolls back with everything it wrote, and the client's last mutation id advances in a transaction of its own with the error recorded as the mutation's result: the replica drops the prediction and the caller's promise rejects with the error. Nothing of a refused write is stored or delivered to any other replica, and a confirmed write's output is never recorded.
52
+ 13. **A push's order is decided before anything of it runs, and a retry runs nothing twice.** Each mutation's place in its client's order is read first, writing nothing. One beyond the next is `PushFailed` (`oooMutation`), and one through another user's client is `PushRefused`, before any stage of the call runs. One at or below the client's last mutation id was answered before: it skips consent and business approval (stages that commit requests, work items, notifications and outbox events on their own) and only replays the receipt its idempotency key stored, or is answered `alreadyProcessed` when there is none (it was refused) or its input differs. Neither leaves anything behind but its audit record. The client's next mutation takes its place in the call's own transaction; if another push for the same client took it meanwhile, the call is refused and its write never commits. Such a losing push may still leave a business approval or consent request of its own, distinct from the winner's (those stages commit on their own, before the call's transaction); requests are keyed by the idempotency key and input, so it is never a second request for the same mutation and input.
53
+ 14. **A client is its user's.** The first push through a client binds it to the pushing user; a later push through it by anyone else is refused (`PushRefused`) and nothing of it commits, and only the bound user's pushes clear its recorded results, and only within the push's own client group (a cleanup naming another group refuses the push, `PushRefused`) (Zero's `_zero_cleanupResults`, which zero-cache sends with mutation id 0 once the client has a refusal: `{ type: "single", clientID, upToMutationID }` or `{ type: "bulk", clientIDs }`).
54
+ 15. **A prediction shows only what the client wrote.** A prediction is computed on the replica from the client's own input, its user and organisation and the current time, over rows the replica already holds (which its read policy let it hold): an update or delete of a record the replica does not hold changes nothing there. A [custom prediction](#custom-predictions) writes only the synced tables of the entities its action declares; one that writes another table, or throws, is rolled back whole and its write is never sent. Whatever the server then answers replaces it.
55
+
56
+ ## Optimistic writes
57
+
58
+ Decision "Data": the replica takes writes optimistically. An action declares the change it predicts (`optimistic.insert`, `update` or `delete`, [ModuleManifest](module-manifest.md#optimistic-effects), or `custom`: the module's own code, [below](#custom-predictions)); `eloxiv generate` writes the module's mutators from those declarations into its `sync.gen.ts`, beside its tables, and `eloxiv.sync.ts` composes every module's into the app's `mutators` (`defineMutators<AppSchema>()(...)`). For a declarative effect nothing is written by hand:
59
+
60
+ ```ts
61
+ // modules/hello/sync.gen.ts (generated)
62
+ export const mutators = {
63
+ hello: {
64
+ greet: defineOptimistic(hello.actions.greet, async ({ tx, args, ctx }) => {
65
+ await tx.mutate.greeting.insert({
66
+ id: predictedKey(ctx, "Hello::Greeting", args.key),
67
+ orgId: ctx.orgId,
68
+ ownerId: ctx.userId,
69
+ message: args.message,
70
+ visibility: (args.visibility ?? "org"),
71
+ createdAt: predictedNow(tx),
72
+ })
73
+ }),
74
+ },
75
+ }
76
+ ```
77
+
78
+ A client opens its replica with them and writes through `@eloxiv/client` (modules and UI never import Zero, decision 9):
79
+
80
+ ```ts
81
+ import { connectSync, write } from "@eloxiv/client"
82
+ import { mutators, schema } from "./eloxiv.sync.ts"
83
+
84
+ const replica = connectSync({ server, schema, userId, token, orgId, mutators, clientVersion })
85
+ const { client, server: confirmed } = write(replica, mutators.hello.greet({ message: "Hello!" }))
86
+ await client // the greeting is in the replica
87
+ await confirmed // the server ran hello.greet; or it rejects with the InvocationError, the greeting gone
88
+ ```
89
+
90
+ `write` checks the input against the action's input schema first (an invalid one rejects both promises with `InvalidInput`, and nothing is predicted or sent) and names an insert's record key when the caller leaves it out. A replica that writes names its organisation (`orgId`), which its predictions are made for. While offline (Zero's `connecting` state, up to its disconnect timeout) writes queue on the replica, predicted, and are pushed in order when it reconnects; each is then confirmed or refused as above. The server promise rejects with `WriteNotConfirmed` when Zero gives up on the connection (`disconnected`, `closed`); the write itself stays queued with the replica and may still be confirmed or refused when it reconnects.
91
+
92
+ ### Custom predictions
93
+
94
+ When the three declarative kinds cannot express what an action changes (several rows, a computed field, a counter, or a move between parents), declare `optimistic: optimistic.custom()` ([ModuleManifest](module-manifest.md#optimistic-effects)) and write the prediction in a `predictions.ts` file beside `sync.gen.ts`. Export one function per custom action, named after the action's local name and typed with the generated `Predictions` interface. `eloxiv generate` wires each function into the module's mutators, generated into `mutators.gen.ts` (or the module's `sync.mutators`; its imports are relative to wherever it is written), the only file that imports `predictions.ts` (and fails if `predictions.ts` is missing), whether or not the module's registry metadata names that file; with no custom action left it removes the generated file, and `eloxiv.sync.ts` imports a module's mutators file only while it exists; the server imports only the tables and queries (`sync.gen.ts`, `eloxiv.schema.ts`), so a prediction's code, or a client-only module it imports, is never loaded on the server, so clients call it like any other mutator: `write(replica, mutators.hello.wave({ greetingId }))`, `writeOptimistic`, or `runtime.write({ mutator: "hello.wave", ... })` — including over [LocalClient](local-client.md), because the daemon runs the client runtime directly.
95
+
96
+ ```ts
97
+ // modules/hello/contract.ts
98
+ export const wave = defineAction({
99
+ name: "hello.wave",
100
+ input: Schema.Struct({ greetingId: Schema.String }),
101
+ output: Schema.Struct({ id: Schema.String, waves: Schema.Number }),
102
+ writes: "greeting",
103
+ target: { entity: "greeting", field: "greetingId" },
104
+ optimistic: optimistic.custom(),
105
+ // ...
106
+ })
107
+
108
+ // modules/hello/predictions.ts
109
+ import type { Predictions } from "./sync.gen.ts"
110
+
111
+ export const wave: Predictions["wave"] = async ({ tx, args, zql }) => {
112
+ const greeting = await tx.run(zql.greeting.where("id", args.greetingId).one())
113
+ if (greeting !== undefined) await tx.mutate.greeting.update({ id: greeting.id, waves: greeting.waves + 1 })
114
+ }
115
+
116
+ // modules/hello/sync.gen.ts (generated): the tables, and the Predictions types
117
+ export interface Predictions {
118
+ readonly wave: Prediction<typeof schema, typeof hello.actions.wave, "greeting">
119
+ }
120
+
121
+ // modules/hello/mutators.gen.ts (generated): the only file importing predictions.ts
122
+ const definePrediction = definePredictionWithType(schema)
123
+ export const mutators = { hello: { /* greet: ..., */ wave: definePrediction(hello.actions.wave, ["greeting"], predictions.wave) } }
124
+ ```
125
+
126
+ A prediction receives the action's encoded input (`args`), the replica's user and organisation with a clock and the kernel's record key derivation (`ctx`: `userId`, `orgId`, `now()`, `recordKey(cedarType, key)`), the module's query builder (`zql`, ZQL over its own tables) and a transaction that reads what the replica holds (`tx.run`) and writes only the tables it may (`tx.mutate`). What holds:
127
+
128
+ - **It runs only on the replica.** The kernel never runs it: the push runs the action's handler through the invocation path, as for a declarative effect (guarantee 11), and the replica keeps the server's rows, whether they match the prediction or not (guarantee 12; a refusal rolls it back with its typed error).
129
+ - **It writes only the tables of the entities its action declares** (`writes`, `target`, `actsOn`: the entities its policy reaches) that sync. `tx.mutate` holds no other table in its type, and at run time any other name refuses the write. It cannot widen what a person sees: it writes the person's own replica, whose read policy is unchanged, and the server's answer replaces it.
130
+ - **A broken prediction predicts nothing and sends nothing.** If a prediction throws or tries to write an undeclared table, the local transaction rolls back completely and nothing is pushed: both promises reject with `ActionFailed` (`"Custom prediction for hello.wave failed; nothing was applied or sent: ..."`), and the client runtime refuses the write with the same error. Zero re-applies pending predictions on top of incoming server changes until the server answers; if a prediction throws during a rebase, that pass predicts nothing while the write still goes to the server. Derive every predicted write solely from its arguments (`ctx.now()` returns the same timestamp on every pass).
131
+ - **Refused before it runs where possible.** `load` refuses `optimistic.custom()` on an action that declares no entity, only entities that do not sync, or is read-only; `eloxiv generate` refuses a module without its `predictions.ts`; the generated file does not typecheck without a function for each action, and refuses at load an action without one (`definePredictionWithType`), as it does a table that is not the schema's.
132
+
133
+ **Deployments** run zero-cache with `ZERO_MUTATE_URL=<kernel>/zero/mutate`, `ZERO_MUTATE_ALLOWED_CLIENT_HEADERS=x-eloxiv-org,x-eloxiv-client-version`, and `ZERO_ENABLE_CRUD_MUTATIONS=false` (Zero's legacy CRUD writes would run as zero-cache's superuser under Zero's permissions instead of the invocation path; with none configured Zero denies them, but they also advance a client's last mutation id), and the kernel with `ELOXIV_ZERO_APP_ID` equal to zero-cache's `ZERO_APP_ID`. zero-cache creates its shard schema (`clients`, `mutations`) after setup, as its superuser, so the kernel role is granted nothing there: setup's superuser owns `SECURITY DEFINER` functions with a fixed search path, `eloxiv_setup.zero_push` and `eloxiv_setup.zero_cleanup`, which only the kernel role may run and which do exactly the bookkeeping above, only in a shard schema a superuser owns, and a third, `eloxiv_setup.zero_push_status`, which reads a mutation's place in the order and writes nothing. They are part of the kernel's recorded security state.
134
+
135
+ ## Generated tables
136
+
137
+ Decision 9: a module declares each field once, in its Drizzle table; its entity ([ModuleManifest](module-manifest.md#entities)) references the table's columns and says what syncs. `eloxiv generate` ([CLI](../cli.md#generate)) writes each module's `sync.gen.ts` from them, and `eloxiv.sync.ts` composes every module's tables into the app's schema.
138
+
139
+ | From | Becomes |
140
+ | --- | --- |
141
+ | The Drizzle table's `pgSchema("<module>").table("<name>", ...)` | `table("<entity name or sync.name>").from("<module>.<name>")` |
142
+ | A column (`orgId: text("org_id")`) | A Zero column under the field's name, `.from("org_id")` when the names differ |
143
+ | A column's type | Only the types on the [sync type allowlist](#sync-types); any other is refused for a synced field |
144
+ | `text`, `varchar(n)`, `char(n)` (Drizzle's bare `char()` is `character(1)`), `uuid`, Postgres enums | `string()`; a column `enum` becomes `enumeration<"a" \| "b">()` |
145
+ | `smallint`, `integer`, `bigint({ mode: "number" })`, `double precision`, `timestamp with time zone`, `date`, `time(0..3)` without a time zone | `number()` (instants and dates as epoch milliseconds, times as milliseconds of the day) |
146
+ | `boolean` | `boolean()` |
147
+ | `jsonb`, arrays of the exact scalars (`text`, `varchar`, `char(n)`, `uuid`, `boolean`, `smallint`, `integer`) | `json()` (`ReadonlyJSONValue`: a Drizzle `$type` is not visible at run time) |
148
+ | An array of a Postgres enum | `json<ReadonlyArray<"a" \| "b">>()`; the entity's row schema is an array of the labels |
149
+ | A generated column (`generatedAlwaysAs`) | not synced: Zero's replica cannot recompute it, so it is in the storage map (marked `generated`) and left out of the entity's `sync.fields` |
150
+ | A nullable column (no `notNull`) | `.optional()`; a `NOT NULL` column with a default is not optional |
151
+ | The table's primary key and unique keys | `.primaryKey(...)`, `.unique(...)` |
152
+ | `relations: relations(table, ...)` on the entity | the Drizzle relations as Zero relationships (both ends must be synced entities of the module) |
153
+ | A sharing policy attribute | `shares: many(...)` to `@eloxiv/client/sync`'s `shareGrant` on `resourceId` (the kernel refuses queries that read it; sharing is evaluated by the kernel's own predicate, guarantee 7) |
154
+
155
+ ### Sync types
156
+
157
+ A synced column round-trips through zero-cache exactly, or it is not synced. zero-cache reads a row two ways: rows that exist when it starts arrive in its initial snapshot (a binary `COPY`), rows written while it runs on its change stream (logical replication, as text), and the two differ (a date before year 100 or after 9999 survives the first and not the second; so does a NULL element of a text array, or a microsecond before 1970). The allowlist is in `@eloxiv/contracts/drizzle` (`syncTypeOfSql`); `packages/testing/test/sync-types.test.ts` proves it through a live replica on both paths: one table per candidate type, edge values written before zero-cache starts and again while it runs (extremes, `NaN`, `±Infinity`, `-0`, precision boundaries, each guard window's edges, `NULL`s, `NULL` elements, empty, two-dimensional and zero-based arrays), replicated by fresh clients and compared with Postgres's values for equality (an instant of microseconds: the replica's epoch milliseconds are nearer its value than any other microsecond's). Every allowlisted type comes back exactly on both paths, every edge value a guard refuses is refused by that guard (the same ones on both), `NULL` is always written, and every refused type loses or changes a value. JSON numbers are a property there too: random numbers in random spellings, accepted exactly when JavaScript reads and spells back the same number (and, for an integer, a safe one), each accepted one equal to the original when the replica's value is written back.
158
+
159
+ | Type | How it syncs |
160
+ | --- | --- |
161
+ | `text`, `varchar(n)`, `character(n)`, `uuid`, enums, `boolean`, `smallint`, `integer`, `time(0)` to `time(3)` without a time zone | exactly, no guard |
162
+ | arrays of those (enums included) | as JSON, guard `plain-array`: one dimension, from index 1, no `NULL` element (the change stream reads a `NULL` element of a string or boolean array as `"NULL"` or `false`) |
163
+ | `bigint` (Drizzle `mode: "number"`) | guard `safe-integer`: within ±(2^53 − 1) |
164
+ | `double precision` | guard `finite-double`: not `NaN`, `±Infinity` or `-0` (Zero replicates them as `null` and `0`) |
165
+ | `timestamp(4)` to `timestamp(6)` with a time zone (and the unqualified one) | guard `instant`: 1970-01-01 to 2037-12-31 (Zero's epoch milliseconds resolve a microsecond there; its change stream misreads microseconds before 1970) |
166
+ | `timestamp(0)` to `timestamp(3)` with a time zone | guard `instant-ms`: 1970-01-01 to 9999-12-31 (the change stream misreads some instants before 1970 with a fraction of a second) |
167
+ | `date` | guard `date`: 1902-01-01 to 9999-12-31 |
168
+ | `jsonb` | guard `json-doubles` (`eloxiv_guard.json_doubles`): every number within ±(2^53 − 1) and already in its shortest double spelling, which Postgres and JavaScript share (`{"v": 65370544689408496}` would come back as `…500`) |
169
+ | `real`, `numeric`, `bigint({ mode: "bigint" })`, timestamps without a time zone, `time(4..6)`, `timetz`, `json`, arrays of any other type, domains, `bytea`, intervals, ranges, extension types | refused for a synced field (leave the column out with `sync: { omit: [...] }`) |
170
+
171
+ **A date before 1970 belongs in a `date` column, not a timestamp.** A synced timestamp (of either precision) cannot hold an instant before 1970-01-01; a `date` column syncs every day from 1902-01-01 to 9999-12-31. Store a birth date, a founding date or any other historical day as a `date`; keep timestamps for instants an app records (creation, updates, schedules).
172
+
173
+ **zero-cache must read in UTC.** Its change stream drops the seconds of a time-zone offset, which a session in another zone prints for old instants (Baghdad's `+02:57:36` before 1918, Amsterdam's `+00:19:32` before 1937): give its upstream connection `TimeZone=UTC` (`ZERO_UPSTREAM_DB=postgres://...?TimeZone=UTC`, as the test harness does), or run Postgres in UTC.
174
+
175
+ Setup installs each guard as a CHECK constraint before the module's roles are fixed; a row already outside one fails setup, since it could not sync. A guard is named from a hash of its column, its kind and its check (`eloxiv_sync_v1_<hash>`, so no two collide, however long the columns), commented with the column it guards, and written with epoch numbers as bounds, so its definition reads the same in every session. Setup keeps a guard only if its definition (`pg_get_constraintdef`) and validity are what it recorded in the module's security state when it installed it; one changed since (an edited window, a `CHECK (true)` under its name, a `NOT VALID` copy) is security drift (the Release status reports it), and setup replaces it and reports the module repaired, never recording the change. Setup also compares every column's declared type with the database's by type OID and modifier, so a domain or an altered type over a declared column is refused.
176
+
177
+ The Drizzle-to-Zero conversion is drizzle-zero 0.21.0's programmatic `drizzleZeroConfig`; Eloxiv's adapter (`packages/cli/src/SyncGen.ts`) corrects read nullability, adds enums and the sharing relationship, fails where drizzle-zero would skip a column or relation, cross-checks every field against the entity's own derivation, and emits static code so the schema keeps literal types. The kernel-provided modules' tables are generated the same way into `@eloxiv/client` (`KernelTables.gen.ts`, by `pnpm --filter @eloxiv/testing generate`).
178
+
179
+ ## The client
180
+
181
+ Modules and registry UI reach sync only through `@eloxiv/client` (a fallow rule, `tools/fallow/eloxiv-sync.json`, refuses `@rocicorp/zero` in modules, the shell, the desktop host, app composition and the app server; the definition of done also walks each app's import graph, `tools/done/src/syncImports.ts`, through relative paths with TypeScript's extension substitution, dependency aliases and every export condition of workspace packages, and fails if any path reaches `@rocicorp/zero` other than through the public entry points of the packages that own it; and it checks the package graph, `tools/done/src/syncPackages.ts`: only `@eloxiv/client`, `@eloxiv/kernel`, `@eloxiv/testing` and `@eloxiv/cli` (and the workspace root's tooling) may depend on `@rocicorp/zero`, under any name, and no other workspace package's `package.json` or lockfile closure reaches it except through them). Queries keep ZQL's shape:
182
+
183
+ - `@eloxiv/client`: `connectSync<S>({ schema, ... })` returns a `SyncClient<S>` typed by the app's schema; Zero's query builder (`createBuilder`), named queries (`defineQuery`, `defineQueryWithType`, `defineQueries`, `defineQueriesWithType`), schema builders (for generated files) and row types (`Row`, `QueryRowType`, `QueryResultType`, ...).
184
+ - `@eloxiv/client/foldkit`: the replica and live queries for a Foldkit screen (`replicaResources`, `liveQuery`, `writeOptimistic`; [ClientSDK](client-sdk.md#ui-bindings)), the default path (decision 10).
185
+ - `@eloxiv/client/react`: `ZeroProvider`, `useQuery`, `useSuspenseQuery`, `useZero`, `useConnectionState` (Zero's own, re-exported: one React context). **Deprecated** with the retired React shell; kept so an app on it keeps building. The headless SDK does not load React.
186
+ - `@eloxiv/client/sync`: the kernel-provided modules' generated tables and named queries (`inboxTables`, `inboxQueries`, `platformTables`, `agentTables`, ...).
187
+
188
+ A module's `sync.ts` holds only its named queries, over its generated `zql`:
189
+
190
+ ```ts
191
+ import { defineQuery, zql } from "./sync.gen.ts"
192
+
193
+ export const queries = {
194
+ greetings: defineQuery(() => zql.greeting.orderBy("createdAt", "desc").limit(100)),
195
+ }
196
+ ```
197
+
198
+ ## How an implementation is checked
199
+
200
+ `syncConformance(start)` registers, against the fixture app: the read policy added to a plain query, with the caller's organisation and user; per-organisation scoping for a member of two organisations; refusal of unauthenticated callers and non-members; per-child authorisation of `related()` and `whereExists()` over the docs fixture's attachments (each child subquery carries the attachment's own read policy, bound to the caller); refusal of queries that reach a kernel table (`shares`, as a child or a filter) and of a query whose own table no entity governs (`docs.grants`), each as Zero's `{ error: "app", message }` with no AST (the subject passes the endpoint's answer through unchanged); refusal to start with a schema mapping `orgId` to another column; the push endpoint's refusal of a push without a bearer session (401) and of one naming a schema other than zero-cache's shard for the kernel's app (403); and the schema check on the fixture's generated schema, a table tampered in type, nullability and columns, a remapped policy field and a reserved table name. `packages/testing/test/sync-generated.test.ts` proves the generator cannot produce a mismatch (for generated Drizzle tables of any shape, the emitted file passes the check; so does every generated file of the repository, which is also current) and that each kind of tampering with a generated file is named, and the kernel refuses to start with one.
201
+
202
+ The Eloxiv kernel runs it in `packages/testing/test/sync-scope.test.ts`. End to end through zero-cache, `registry/test/sync.test.ts` proves a write reaching a second client's replica, a private record withheld until a sharing grant and withdrawn from the connected replica when the grant is revoked, no readable projection exposing a private record, per-organisation replicas, and the client SDK in a bare JavaScript runtime. `packages/testing/test/sync-revocation.test.ts` proves guarantees 7 and 8 live for the directory; `packages/testing/test/sharing-live.test.ts` proves them for every grant kind, expiry and child queries (unreadable children never reach the replica, including ones written after the transform, and revoking a child's grant removes it live). `packages/testing/test/sync-property.test.ts` proves criterion 6 as a property through zero-cache: for generated policies, actors, records and grants, a replica holds exactly what Cedar authorises; `packages/kernel/test/policy-zql.test.ts` checks the same for 1,500 cases over the transform's conditions in memory. `packages/testing/test/sync-fact-concurrency.test.ts` proves the facts under concurrency: the review's schedule (a trusted `addMember`, and a plain SQL insert, blocked behind a revocation of the role's permission until it commits) live through zero-cache, and rounds of concurrent mixed directory writes through every path (management calls, system helpers, machine identity, plain SQL transactions), after each of which the stored facts must equal those recomputed from the directory.
203
+
204
+ Optimistic writes are proven live through zero-cache in `packages/testing/test/optimistic.test.ts` (the `tasks` fixture: inserts, updates of one target and of a target set, and deletes confirmed, a second client seeing only confirmed rows; custom predictions with the push held at a barrier: a counter shown before the server answers, the server's different result replacing it, a refusal rolled back with its typed error, several rows changed at once, and a prediction that writes an undeclared table or throws refused with nothing kept or sent; each rejection kind rolling back on the client that made it, with its typed error: a forbidden insert no other client ever saw, an update of a record the client cannot read predicting nothing, invalid input refused before it is sent and from a client that sends it anyway, `ApprovalRequired` with its request, `ConsentRequired` with its consent, a conflict and a handler failure; writes queued offline, confirmed or refused on reconnect; a push whose answer was lost replayed from its receipt; concurrent conflicting writes from two clients converging on the server's outcome; and the endpoint's own refusals: no bearer token, another schema, an action without an optimistic effect, another user's client, out of order, a bad record key; an out-of-order or replayed push reaching no consent or approval stage and leaving no request; Zero's cleanup in both of the forms zero-cache sends, and through a real client once it has a refusal), in `registry/test/sync.test.ts` for hello (`hello.wave`'s own prediction among them, its server write held behind a table lock), through the client core in `registry/test/client-runtime.test.ts`, in the browser in `e2e/optimistic.spec.ts`, the record key and manifest checks in `packages/contracts/test/optimistic.test.ts`, and the generator's wiring and definition-time refusals of custom predictions in `packages/testing/test/predictions.test.ts`.
205
+
206
+ ## Version skew
207
+
208
+ A client's sync schema names every column it reads, and zero-cache compares the whole schema with the columns the kernel's database publishes when the client connects: a client whose schema names a column the kernel has not added yet is refused (`SchemaVersionNotSupported`) and syncs nothing, even when the screen it shows reads none of the new columns. Marking the new column nullable in the client's schema does not help, because the schema still names it. So any release that adds a synced column (for example `approvalRequest.title` in `eloxiv_approvals.request`, added with ModuleManifest 1.6.0) needs this order: upgrade and migrate the kernel first, check that zero-cache publishes the new column, and only then distribute the clients built against it. A newer kernel serves older clients: they do not name the column, so it is not checked. Mixed versions in the other direction are not supported, as there is no negotiation of which columns a kernel publishes.
209
+
210
+ ## Not yet guaranteed
211
+
212
+ - **A client newer than its kernel** cannot sync when its schema names a column the kernel does not publish yet (see [Version skew](#version-skew)): the kernel is upgraded before the clients.
213
+ - **React Native** (backlog 10): the client SDK and sync are proven in a bare JavaScript VM, not on Hermes.
@@ -0,0 +1,80 @@
1
+ # Telemetry
2
+
3
+ Traces and metrics through OpenTelemetry (Effect's OTLP exporters), error capture with a Sentry adapter, and product analytics with a PostHog adapter, gated by [Privacy](privacy.md) consent (decisions.md "Kernel contracts" and "Stack": OpenTelemetry through Effect, Sentry for errors, PostHog for product analytics; the ledger's A-099, A-100, B-057, B-059, C-065).
4
+
5
+ - Kind: kernel service. Version 1.0.0.
6
+ - Schema: [`packages/contracts/schema/contracts/Telemetry.json`](../../packages/contracts/schema/contracts/Telemetry.json) (source [`Telemetry.ts`](../../packages/contracts/src/contracts/Telemetry.ts), including `TELEMETRY_SPAN_ATTRIBUTES` and `CAPTURED_ERROR_MESSAGES`; declared analytics events and `checkAnalyticsProperties` in [`Analytics.ts`](../../packages/contracts/src/Analytics.ts)).
7
+ - Implementation: [`packages/kernel/src/Telemetry.ts`](../../packages/kernel/src/Telemetry.ts) (`TelemetryTracing`, `safeTracer`, `routeTemplate`, `ErrorCapture` with `sentryAdapter`, `Analytics` with `posthogAdapter`); the invocation path's spans, metrics, capture and events in [`Invocation.ts`](../../packages/kernel/src/Invocation.ts); the kernel module `telemetryModule` ([`telemetry/module.ts`](../../packages/kernel/src/telemetry/module.ts)).
8
+ - Kit: `@eloxiv/testing/conformance/Telemetry` ([source](../../packages/testing/src/conformance/Telemetry.ts)), against the protocol fakes in [`fakes/TelemetryFakes.ts`](../../packages/testing/src/fakes/TelemetryFakes.ts).
9
+
10
+ ## Configuration
11
+
12
+ Each destination is off unless configured (`KernelConfig.telemetry`, or the environment):
13
+
14
+ | Destination | Environment | Notes |
15
+ | --- | --- | --- |
16
+ | OTLP traces and metrics (HTTP, JSON) | `OTEL_EXPORTER_OTLP_ENDPOINT` (base URL; `/v1/traces` and `/v1/metrics` are appended), `OTEL_SERVICE_NAME` | logs are never exported (free text) |
17
+ | Sentry | `ELOXIV_SENTRY_DSN`, `ELOXIV_SENTRY_ENVIRONMENT` | the release is the app's version |
18
+ | PostHog | `ELOXIV_POSTHOG_HOST`, `ELOXIV_POSTHOG_KEY` | |
19
+ | Analytics key | `ELOXIV_ANALYTICS_KEY` | derives distinct ids (default: the auth secret) |
20
+
21
+ `KernelOptions.errorAdapter` and `analyticsAdapter` replace the Sentry and PostHog adapters with others (an `ErrorAdapter` sends `CapturedError`s, an `AnalyticsAdapter` sends `AnalyticsEvent`s). Telemetry is provided innermost, so every kernel service, background loop and request runs under it.
22
+
23
+ ## Traces and metrics
24
+
25
+ **Allowlist-only: no free-form string ever leaves the kernel.**
26
+
27
+ - **Spans.** `Invocation.invoke` for every call, under the HTTP server's span for the request (W3C trace context is accepted from callers). Every span passes `safeTracer`: an attribute leaves only if its key is in `TELEMETRY_SPAN_ATTRIBUTES` and its value is one the key may hold: `eloxiv.action` and `eloxiv.module` a registered name (anything else, such as an unknown action a caller named, leaves as `unknown`), `eloxiv.surface`, `eloxiv.origin`, `eloxiv.outcome` (`succeeded`, `replayed`, `failed`, `interrupted`) and `eloxiv.error_tag` (the standard errors and `Defect`, else `Other`) from their enums, `eloxiv.replayed` a boolean, the HTTP method from its enum, the status code a number, and `http.route` the **template** of the kernel route the path matched (`/api/actions/:action`, `/ingress/:source`, `/auth/*`, ...; `unmatched` for anything else), never the path itself. Nothing high-cardinality or caller-chosen is an attribute: no invocation id, organisation, user, URL, query string, header, address or SQL text. **Span names are declared or templated too** (`exportedSpanName`): the kernel's own (`Invocation.invoke`, `Scheduler.sweep`, ...), a SQL statement's kind (`SELECT postgres`), an HTTP method, a registered action's or workflow's name (and the workflow engine's spans of it), an MCP method of the protocol; a workflow step's as `step/:name` (step names are the work's own and may name what it works on); anything else (a name a module's code or a caller chose) as `other`. Span events (log lines) never leave, and a failed span records only its error's known tag.
28
+ - **Metrics.** `eloxiv.invocations` (count) and `eloxiv.invocation.duration` (milliseconds), by action (registered or `unknown`), surface and outcome, beside Effect's runtime metrics.
29
+ - Logs are never exported.
30
+
31
+ ## Error capture
32
+
33
+ Unexpected failures are captured: a defect in a handler (module or kernel), and a defect outside the handler on the invocation path. Expected failures (`Forbidden`, `InvalidInput`, approval and consent holds, ...) are not. A report (`CapturedError`) carries **only the failure's tag, the invocation id and the tag's fixed message** (`CAPTURED_ERROR_MESSAGES`), with the deployment's environment and release: never the error's own message, its stack, the call's action, inputs, outputs or anyone's id. The invocation id leads an operator to the kernel's own logs and audit record. Errors are sent off the caller's path, in batches; an adapter's failure is logged and never reaches the caller.
34
+
35
+ **A client's errors** come through the action `telemetry.captureError` (telemetry module 1.1.0; the client SDK's `errorReporter({ send, route })`, which installs on a window's `error` and `unhandledrejection` and keeps the last 20 breadcrumbs): a `ClientErrorReport` is **labels only**, each refused (`InvalidInput`) unless it is one: its `kind` (`exception`, `rejection`), the error's class name, the route as the app's router names it, a registered template (`errorReporter({ route })`; `/unknown` for a route the router does not know: the SDK never derives one from a path, whose segments can be names or diagnoses), the invocation it followed (correlation), and breadcrumbs (`navigation`, `action`, `request`, `ui`, each with a label and a time). Never a message, a stack, a URL's values or input. It is captured with the tag `Client` and its fixed message, the labels as Sentry tags and breadcrumbs; at most `CLIENT_ERRORS_PER_MINUTE` (30) a person per calendar minute in a process are kept (so up to 60 in any 60 seconds across a minute's boundary: a fixed window, enough to keep a crash loop from flooding error capture), the rest answered `{ accepted: false }`.
36
+
37
+ The **Sentry adapter** speaks the envelope protocol: `POST <scheme>://<host>/api/<project>/envelope/`, `X-Sentry-Auth: Sentry sentry_version=7, sentry_key=<public key>`, an envelope header (`event_id`, `sent_at`, `dsn`), an item header (`type: event`) and the event (`exception: [{ type: <tag>, value: <fixed message> }]`, `tags: { invocation_id, error_tag }`).
38
+
39
+ ## Product analytics
40
+
41
+ Every event is **declared**, with its consent category and typed properties:
42
+
43
+ ```ts
44
+ analyticsEvents: {
45
+ "journal.viewed": {
46
+ description: "Entries were viewed",
47
+ category: "analytics",
48
+ properties: { view: { kind: "enum", values: ["list", "detail"] }, count: { kind: "number" }, pinned: { kind: "boolean" }, entry: { kind: "id" } },
49
+ },
50
+ }
51
+ ```
52
+
53
+ Modules declare theirs in their manifests (`<module>.*`), the app declares its clients' (`KernelApp.analytics.events`, `client.*`), and the kernel declares its own `eloxiv.action_invoked` (for every first execution a person or their agent makes: `action` from the registered names, `surface`, `origin`, `duration_ms`). A property is an `enum` (one of the declared short tokens), a `number`, a `boolean` or an `id`, which leaves only as a keyed hash (`id_<32 hex>`). An undeclared event or property, a value outside its enum or of another type, is refused with `InvalidInput` (`checkAnalyticsProperties`); the kernel refuses at startup a declaration that could carry free text or needs no consent. Handlers send with `ctx.analytics.track({ event, properties })`, clients with `telemetry.track`. Events a call asked for are queued only after it commits.
54
+
55
+ **Consent decides.** When a batch leaves (every second by default, and at shutdown), each event's person's consent for its declared category in its organisation is read (`Privacy.allows`, fail-closed); events without it are dropped and counted. So a refusal made after the call still stops its events, and without the privacy module nothing leaves. The person is a keyed hash too (`u_<32 hex>`). Without an analytics destination configured events are still checked and nothing is queued.
56
+
57
+ **A web client's pageviews, lifecycle and action timing** come from the client SDK's opt-in collector, `browserAnalytics({ track, consent, routes, actions })` ([`BrowserAnalytics.ts`](../../packages/client/src/BrowserAnalytics.ts)), sent through `telemetry.track` as the events `browserAnalyticsEvents({ routes, actions })` declares for the app (`KernelApp.analytics.events`): `client.pageview` (`route`: one of the app's route names, lower-case tokens such as `journal.entry`, else `unknown`, never a path), `client.lifecycle` (`state`: `visible`, `hidden`, `left`, from the page's `visibilitychange` and `pagehide`) and `client.action_timed` (`action`: a declared action, `outcome` `ok` or `failed`, `duration_ms`). It sends nothing unless the consent controller grants `analytics` when the event is queued and again just before it leaves, and the kernel checks the person's consent again when the batch leaves; the person is the kernel's keyed hash. It uses no DOM API (the app passes its `window`), so the root SDK stays free of DOM types for Hermes. ([`browser-analytics.test.ts`](../../packages/testing/test/browser-analytics.test.ts))
58
+
59
+ The **PostHog adapter** posts batches to `<host>/batch/` (`api_key`, and per event `event`, `distinct_id`, `timestamp`, `uuid`, `properties` with `consent_category`).
60
+
61
+ ## Operations
62
+
63
+ | Operation | Where | Input | Output |
64
+ | --- | --- | --- | --- |
65
+ | `captureError` | in process (`ErrorCapture.capture`) | the failure's tag and invocation id | never fails |
66
+ | `track` | `ctx.analytics.track`; action `telemetry.track` for clients | `TrackEvent`: a declared event and its declared properties | `{ accepted }` (checked and queued, not a promise that it is sent) |
67
+ | `reportClientError` | action `telemetry.captureError` for clients | `ClientErrorReport` (labels only) | `{ accepted }` (false past the bound) |
68
+ | `flush` | in process (`ErrorCapture.flush`, `Analytics.flush`, the OTLP flusher) | | |
69
+
70
+ ## How an implementation is checked
71
+
72
+ `telemetryConformance(start)` takes a `ServicesSubject` (see [Progress](progress.md#how-an-implementation-is-checked)) whose kernel exports to the subject's protocol fakes: an OTLP collector (`/v1/traces`, `/v1/metrics`, JSON), a Sentry envelope endpoint (checks the key and project), a PostHog batch endpoint (checks the API key). Results against them are proven against protocol fakes, not the real services. The kit checks: an invocation span with exactly its declared attributes and the HTTP span (with its route template, no path) as parent; a refused call's span with its tag and no message; invocation metrics; an unknown action and an unmatched path leaving only as `unknown` and `unmatched`, the caller's text nowhere in what was exported; no exported byte holding a record value, a session token, an e-mail address, a user id, the organisation or a bearer credential, and every attribute allowlisted; a crashing handler reported to Sentry with exactly its tag, the invocation id and the fixed message, none of the secret, the error's text, the action, an address or an id; refusals and invalid input not reported; undeclared events and properties, values outside an enum and wrong types refused, ids and people pseudonymised; analytics refused for an opt-in region and an unplaced person until they consent, sent for an opt-out region until refusal, per declared category; the kernel's own event only for a consenting person; clients' declared events only as `client.*`. The Eloxiv kernel runs it in [`packages/testing/test/telemetry.test.ts`](../../packages/testing/test/telemetry.test.ts); the property checks are proven property-based in [`packages/contracts/test/platform-services.test.ts`](../../packages/contracts/test/platform-services.test.ts).
73
+
74
+ ## Not yet guaranteed
75
+
76
+ - **Real services**: the Sentry and PostHog adapters and the OTLP export are proven against protocol fakes only.
77
+ - **Client-side capture**: the client SDK reports global exceptions and rejections with breadcrumbs and correlation (above, [`client-errors.test.ts`](../../packages/testing/test/client-errors.test.ts)). Session replay, the in-memory diagnostic recorder and private problem reports (the ledger's B-060 to B-062, A-108) are deferred products (decision 12). The client SDK's opt-in `browserAnalytics` collector sends pageviews, lifecycle and action timing as declared `client.*` events (below).
78
+ - **Agent observability** is the agent's own data: each run's stored trace and people's feedback ([AgentRuntime](agent-runtime.md) `trace`, `feedback`), usage insights and alerts ([Metering](metering.md)). Trace review, experiments and evals promoted from traces are deferred products (decision 12).
79
+ - **Workflow and subscriber defects** are logged and dead-lettered, not yet captured.
80
+ - **The kernel's logs** (stdout) are the operator's and are not exported: a defect is logged with its cause (which can carry a module's message and what the work was about), under the deployment's log retention.
@@ -0,0 +1,50 @@
1
+ # ThemeTokens
2
+
3
+ The design tokens a registry theme provides and the shell and UI items consume: colours in light and dark pairs, a radius, a spacing unit and font stacks, resolved per scheme and writing direction, and written as one stylesheet of CSS custom properties.
4
+
5
+ - Kind: shell contract. Version 1.0.0.
6
+ - Schema: [`packages/contracts/schema/contracts/ThemeTokens.json`](../../packages/contracts/schema/contracts/ThemeTokens.json) (source [`ThemeTokens.ts`](../../packages/contracts/src/contracts/ThemeTokens.ts)).
7
+ - Implementation: `themeProblems`, `resolveTheme`, `themeCss`, `physicalInset` and `contrastRatio` in `@eloxiv/shell-core` ([`Theme.ts`](../../packages/shell-core/src/Theme.ts)). The registry's `theme` item ([`app/themes/default`](../../registry/app/themes/default)) is a theme: `tokens.ts` and the `theme.css` written from it (`pnpm --filter @eloxiv/registry-source themes`).
8
+ - Kit: `@eloxiv/testing/conformance/ThemeTokens` ([source](../../packages/testing/src/conformance/ThemeTokens.ts)).
9
+
10
+ ## Operations
11
+
12
+ | Operation | Input | Output | What it does |
13
+ | --- | --- | --- | --- |
14
+ | `validate` | `ThemeTokens` | `{ problems }` | Every problem: a missing colour token, a colour it cannot measure, a translucent text pair, a foreground below 4.5:1 against its background in either scheme |
15
+ | `resolve` | `{ theme, scheme, direction }` | `ResolvedTheme` | One scheme's tokens as custom properties (`--background`, `--radius`, `--spacing`, `--font-sans`, `--font-mono`), with `--direction`, `--inline-start` and `--inline-end` for the direction |
16
+ | `css` | `{ theme }` | `{ css }` | One stylesheet: light on `:root` (with `color-scheme: light`), dark on `.dark` and `[data-theme="dark"]`, rtl on `[dir="rtl"]` |
17
+ | `inset` | `{ inset, direction }` | `PhysicalInset` | Logical insets (`blockStart`, `inlineEnd`, `blockEnd`, `inlineStart`) on physical sides: inline start is left in ltr and right in rtl |
18
+
19
+ ## Records
20
+
21
+ - **`ThemeTokens`**: `name`, `colors` (token to `{ light, dark }`; every token in `COLOR_TOKENS` is required, others such as `chart-1` or `sidebar` may be added), `radius` and `spacing` (CSS lengths), `fonts` (`sans`, `mono`).
22
+ - Colours are `#rgb`, `#rrggbb` or `oklch(L C H[ / A])`, so contrast can be measured.
23
+ - `COLOR_TOKENS` is shadcn/ui's vocabulary: `background`, `foreground`, `card`, `popover`, `primary`, `secondary`, `muted`, `accent`, `destructive` (each with `-foreground`), `border`, `input`, `ring`.
24
+
25
+ ## Guarantees
26
+
27
+ 1. **Every token in both schemes.**
28
+ 2. **Measured contrast.** Each `<name>-foreground` on `<name>`, and `foreground` on `background`, is at least 4.5:1 (WCAG 2.2 AA) in light and dark: OKLCH is converted to linear sRGB with OKLab's published matrices and compared by relative luminance. Text pairs must be opaque. (shadcn's own `muted-foreground`, 0.556, is 4.34:1 on `muted`; the default theme uses 0.53.)
29
+ 3. **Right to left without a second theme.** Spacing is logical; the stylesheet and `resolve` give the direction's sides for code that cannot use logical properties (a canvas, a native view).
30
+
31
+ ## How an implementation is checked
32
+
33
+ `themeTokensConformance({ validate, resolve, css, inset, themes })` checks a reference theme is valid, every missing token is named, the threshold exactly (`#767676` on white passes at 4.54:1, `#777777` fails at 4.48:1; a dark pair; `foreground` on `background`), unmeasurable and translucent colours, the resolved properties for each scheme and direction, the stylesheet's three blocks, the insets mirrored for rtl as a property, and that every theme the implementation ships is valid. It runs in [`registry/test/theme-tokens.test.ts`](../../registry/test/theme-tokens.test.ts), which also checks the registry theme's `theme.css` is what its tokens produce.
34
+
35
+ ## StyleX
36
+
37
+ `themeStylex(theme)` (in `@eloxiv/shell-core`) writes the theme as a StyleX module, `tokens.stylex.ts` beside `theme.css` in the registry's `theme` item (0.2.0; `pnpm --filter @eloxiv/registry-source themes` writes both): `stylex.defineVars` groups `colors`, `sizes` (radius, spacing, fonts) and `direction` (the sides, for what cannot use logical properties), with the light scheme and left to right as defaults, and two `stylex.createTheme` overrides, `dark` and `rtl`, that a shell applies to its root. The values are exactly `resolveTheme`'s, and it refuses a theme with problems, so measured contrast holds for every StyleX theme written (`registry/test/theme-tokens.test.ts`). The Foldkit shell (`shell-foldkit`) styles everything with StyleX over these variables and logical properties, so its `dark` and `rtl` switches restyle and mirror the whole shell (`e2e/foldkit.spec.ts` checks the computed colours and the mirrored layout in a browser).
38
+
39
+ ## Presets, the first paint and MAKE frames
40
+
41
+ A theme can have presets over its own variables: `themePresetStylex(preset, "./tokens.stylex.ts")` writes a preset's colours as StyleX themes (`preset` for light, `presetDark` for dark) over the base theme's `colors`, refusing a preset with contrast problems. The registry's default theme has a high-contrast preset (`contrastTheme` in `themes/default/tokens.ts`, `contrast.stylex.ts`, theme 0.3.0); the reference shell (shell-foldkit 0.5.0) offers it beside the scheme and direction, keeps the choice on the device (`eloxiv.appearance.preset`) and applies it instead of the base's scheme colours.
42
+
43
+ The shell's page runs a small pre-paint script in its head (`shell-foldkit/public/boot.js`) that applies the stored scheme, preset, direction and language to the document root, with the theme's own first background, before anything is drawn, so a reload never flashes light before dark; the shell takes over on its first frame. `registry/test/shell-foldkit-lifecycle.test.ts` checks the script's backgrounds against the tokens.
44
+
45
+ MAKE views wear the app's theme: the shell's MAKE host resolves the app's tokens for the shell's scheme, preset and direction (`frameTheme`, read from the shell's root and again whenever they change) and sets them as the frame root's custom properties, which the frame's own sheet draws controls with. A view's `style` may name those variables (`var(--primary)`) and no other variable, fallback or spelling (`registry/test/make-view-style.test.ts`).
46
+
47
+ ## Not yet guaranteed
48
+
49
+ - **The React registry shell does not import the theme yet**: its stylesheet still holds its own variables (the `theme` item's next step replaces them with `@import "../../themes/default/theme.css"`). The Foldkit shell does, through `tokens.stylex.ts`.
50
+ - **No typography scale, shadows or motion tokens**; no contrast check for non-text pairs (borders, rings).
@@ -0,0 +1,58 @@
1
+ # ToolSource
2
+
3
+ An external server's tools as a capability: a remote MCP server (or any server speaking a tool protocol a connector implements) over a kernel [endpoint Connection](connections.md#endpoint-connections) whose endpoint is the server. The kernel carries the credential (none, a secret it holds, or an OAuth grant it discovered from the server and keeps), checks the server's address on every request, applies the 401-versus-403 rule and backpressure, and never hands the credential to connector or module code; the connector speaks the protocol.
4
+
5
+ - Kind: capability. Version 1.1.0 (1.1.0: a tool's MCP Apps declaration, `RemoteTool.ui`, and `readResource`).
6
+ - Schema: [`packages/contracts/schema/contracts/ToolSource.json`](../../packages/contracts/schema/contracts/ToolSource.json) (source [`ToolSource.ts`](../../packages/contracts/src/contracts/ToolSource.ts)).
7
+ - Implementations: the [`mcp`](../connectors/mcp.md) registry connector ([`registry/app/connectors/mcp`](../../registry/app/connectors/mcp)): MCP protocol revision 2025-06-18 over Streamable HTTP.
8
+ - Kit: `@eloxiv/testing/conformance/ToolSource` ([source](../../packages/testing/src/conformance/ToolSource.ts)), run by [`registry/test/connector-mcp.test.ts`](../../registry/test/connector-mcp.test.ts) against the MCP protocol fake ([`fakes/McpFake.ts`](../../packages/testing/src/fakes/McpFake.ts): a stand-in for a server, in its three authentication modes, not a real service).
9
+
10
+ Shared parts: [Capability contracts](README.md#capability-contracts).
11
+
12
+ ## Records
13
+
14
+ - `RemoteTool`: `name`, `title`, `description`, `inputSchema` (a JSON Schema object), `readOnly` and `destructive` (the server's hints: its word, not a guarantee), and `ui` when the server declares the tool under the MCP Apps extension (`_meta.ui`): `resourceUri` (the `ui://` view its result is shown in, or null) and `visibility` (`model`, `app`, or both, the default).
15
+ - `ResourceContent`: `uri`, `mimeType`, `text` or `blob` (base64), and `meta` (the content's `_meta`: for an MCP App, its CSP and permissions), as the server sent them.
16
+ - `ToolResult`: `content` (the server's content blocks, as it sent them), `structuredContent` (or null), `isError` (the tool itself reported a failure).
17
+ - `ToolSourceFlags`: `protocol` (the revision the connector speaks).
18
+
19
+ ## Operations
20
+
21
+ | Operation | Scopes | What |
22
+ | --- | --- | --- |
23
+ | `listTools` | `tools.read` | The server's tools, one page at a time (`pageToken`, `nextPageToken`) |
24
+ | `callTool` | `tools.call` | Call one tool with its arguments. `effect: "external"`: the server may act, so a 5xx is never sent again; a module's handler schedules it (`ctx.connections.schedule`) rather than calling it |
25
+ | `readResource` | `tools.read` | Read one resource by its URI (`resources/read`): its contents. A resource the server does not have (JSON-RPC `-32002`) is `InvalidInput` |
26
+
27
+ A tool that fails answers a result with `isError: true`; a request the server refuses as malformed (an unknown tool, invalid arguments: JSON-RPC `-32602`, `-32601`, `-32600`) is `InvalidInput`; any other protocol failure is `Unavailable`.
28
+
29
+ ## Exposure
30
+
31
+ A Connection's `tools` (set by `connections.add`) is the only tools it exposes: the kernel filters `listTools` and refuses `callTool` for any other before anything is sent (`Forbidden`), whoever calls it (the kernel's actions or a module's handler).
32
+
33
+ People and the agent reach a Connection's tools through two actions of the kernel's `connections` module, on every surface: `connections.tools` (every page, up to 1000 tools) and `connections.callTool`. `callTool` is marked `consent`: an agent's call waits for the person's consent (ActionConsent; a permission they remember covers later calls), which is the pre-execution authorisation of a remote call. An app without the inbox modules refuses an agent's call outright.
34
+
35
+ ## MCP App sessions
36
+
37
+ The MCP Apps extension lets a server declare, for a tool, an interactive view (an HTML `ui://` resource) that a host renders and that calls the server's tools back. The kernel keeps the headless part: the session, and its tool calls through the same path as `connections.callTool`. Three actions of the `connections` module, on every surface (the client SDK's `connectionsOf(...).apps`):
38
+
39
+ | Action | What |
40
+ | --- | --- |
41
+ | `connections.openApp` | `{ connectionId, tool }`: for a tool the Connection exposes whose `ui.resourceUri` is a `ui://` URI, reads that resource and opens a session for the caller. Answers `{ session, resource, tools }`: the session (`id`, `connectionId`, `tool`, `resourceUri`, `tools`, `openedAt`, `expiresAt`), the resource as the server sent it, and the tools the view may call: the Connection's exposed tools whose visibility includes `app`. A tool without a view, or one the Connection does not expose, is `InvalidInput` |
42
+ | `connections.appCall` | `{ sessionId, name, arguments? }`: calls a tool for the view, as `connections.callTool` does: the Connection's grant, state and exposed tools are checked again on each call, and an agent's call waits for the person's consent (`consent: true`). Refused (`Forbidden`, nothing sent) for a tool the session does not list (a model-only one), a session that is closed, past `expiresAt` or another person's (which answers as one that does not exist), and a Connection the caller may no longer use (a revoked grant, a disconnect) |
43
+ | `connections.closeApp` | `{ sessionId }`: closes one of the caller's sessions (another's is left alone); its calls are refused from then on |
44
+
45
+ A session belongs to the person who opened it, in that organisation (`eloxiv.mcp_app_session`), for 12 hours unless closed sooner; an expired one is deleted by its person's next open, and an erasure deletes a person's sessions. The client renders `resource` in a sandbox of its own and relays the view's tool calls with `appCall`.
46
+
47
+ ## How an implementation is checked
48
+
49
+ `toolSourceConformance(start)` starts the MCP fake in its three modes and a kernel that allows only their hosts as private destinations, then registers: a server added without a credential is active at once and lists every page of its tools with their hints; a call answers content, structured content and a tool's own error as a result, and an unknown tool as `InvalidInput`; answers sent as an event stream are read; a named secret is sent only in its header and is in no Connection, flow or audit row and no answer; a secret that is not the caller's, missing, or restricted to other origins is refused before anything is sent; OAuth discovered from the server registers a client, completes consent with PKCE S256 and the resource, and leaves no token in any kernel table in clear, while the Connection is unusable (nothing sent) until consent; a 401 refreshes once, a refused refresh marks the Connection for reauthorisation and later calls fail fast without reaching the server, and consenting again recovers it; a 403 is a refusal and never refreshes; a Connection's `tools` limit what is listed and callable, nothing sent for another; endpoints that are not public (loopback, the metadata address, private ranges, `localhost`, other schemes) are refused unless allowed; an agent's call is held for consent with nothing sent; a shared server is used only by the members it is granted to, and from a module's handler only when granted to the module, and revoking takes effect on the next use. MCP App sessions, against the fake's MCP App mode (a tool declaring `ui://board/view.html`, an app-only tool and a model-only one): a session opens on the tool's view with the resource as sent and the app's tools only, calls through it (a model-only tool refused, an agent's call held for consent with nothing sent; a tool without a view, or one the Connection does not expose, opens none); its calls are refused once it is closed or the shared server's grant is revoked, nothing sent; another member can neither call through nor close it; a session that expires while its call waits (on a lock, before the session check) is refused, nothing sent: expiry is read by the clock, not the transaction's start.
50
+
51
+ ## Not yet guaranteed
52
+
53
+ - **Proven against a protocol fake only**: no real MCP server is run in CI. The presets' endpoints ([`presets.ts`](../../registry/app/connectors/mcp/presets.ts)) are starting points, not checked services.
54
+ - **One session per operation**: each operation initialises its own MCP session and leaves it to the server to expire; no server-initiated streams (notifications, sampling, elicitation) or prompts, and resources only by `readResource` (no listing or subscriptions).
55
+ - **Local (stdio) MCP servers** are not a ToolSource: they run on a person's machine, which is the daemon's ([DeviceControl](device-control.md)).
56
+ - **Incremental consent for a server's scopes**: a 403 naming `insufficient_scope` reports no missing scopes (a server's scopes are its own); consent again with `connections.reconnect` asking for them.
57
+ - **MCP App host UI (deferred)**: rendering a view is the client's: no Eloxiv screen renders one (the shell allows iframes only for MAKE views, decision 10), so the host side of the MCP Apps bridge (the view's `ui/*` messages over `postMessage`: initialisation, tool input and results pushed to the view, size changes, links and messages it asks the host to open or send) and enforcing the resource's CSP and permissions are not built. The kernel answers the resource's `meta` for a client that does.
58
+ - **An app-only tool is still listed to the agent**: `connections.tools` and `connections.callTool` do not filter by `visibility`; the agent sees it in `ui.visibility`.