@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.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/dist/AgentSkills.d.ts +51 -0
- package/dist/AgentSkills.d.ts.map +1 -0
- package/dist/AgentSkills.js +264 -0
- package/dist/AgentSkills.js.map +1 -0
- package/dist/AgentWeb.d.ts +83 -0
- package/dist/AgentWeb.d.ts.map +1 -0
- package/dist/AgentWeb.js +436 -0
- package/dist/AgentWeb.js.map +1 -0
- package/dist/App.d.ts +213 -0
- package/dist/App.d.ts.map +1 -0
- package/dist/App.js +357 -0
- package/dist/App.js.map +1 -0
- package/dist/Blueprint.d.ts +47 -0
- package/dist/Blueprint.d.ts.map +1 -0
- package/dist/Blueprint.js +241 -0
- package/dist/Blueprint.js.map +1 -0
- package/dist/Brand.d.ts +42 -0
- package/dist/Brand.d.ts.map +1 -0
- package/dist/Brand.js +370 -0
- package/dist/Brand.js.map +1 -0
- package/dist/Changelog.d.ts +22 -0
- package/dist/Changelog.d.ts.map +1 -0
- package/dist/Changelog.js +117 -0
- package/dist/Changelog.js.map +1 -0
- package/dist/Cli.d.ts +17 -0
- package/dist/Cli.d.ts.map +1 -0
- package/dist/Cli.js +810 -0
- package/dist/Cli.js.map +1 -0
- package/dist/DbAdmin.d.ts +18 -0
- package/dist/DbAdmin.d.ts.map +1 -0
- package/dist/DbAdmin.js +91 -0
- package/dist/DbAdmin.js.map +1 -0
- package/dist/Dependencies.d.ts +53 -0
- package/dist/Dependencies.d.ts.map +1 -0
- package/dist/Dependencies.js +132 -0
- package/dist/Dependencies.js.map +1 -0
- package/dist/Deploy.d.ts +39 -0
- package/dist/Deploy.d.ts.map +1 -0
- package/dist/Deploy.js +458 -0
- package/dist/Deploy.js.map +1 -0
- package/dist/Docs.d.ts +71 -0
- package/dist/Docs.d.ts.map +1 -0
- package/dist/Docs.js +240 -0
- package/dist/Docs.js.map +1 -0
- package/dist/Doctor.d.ts +56 -0
- package/dist/Doctor.d.ts.map +1 -0
- package/dist/Doctor.js +368 -0
- package/dist/Doctor.js.map +1 -0
- package/dist/Dossier.d.ts +23 -0
- package/dist/Dossier.d.ts.map +1 -0
- package/dist/Dossier.js +92 -0
- package/dist/Dossier.js.map +1 -0
- package/dist/Emit.d.ts +26 -0
- package/dist/Emit.d.ts.map +1 -0
- package/dist/Emit.js +51 -0
- package/dist/Emit.js.map +1 -0
- package/dist/Errors.d.ts +26 -0
- package/dist/Errors.d.ts.map +1 -0
- package/dist/Errors.js +17 -0
- package/dist/Errors.js.map +1 -0
- package/dist/Evals.d.ts +52 -0
- package/dist/Evals.d.ts.map +1 -0
- package/dist/Evals.js +126 -0
- package/dist/Evals.js.map +1 -0
- package/dist/Files.d.ts +47 -0
- package/dist/Files.d.ts.map +1 -0
- package/dist/Files.js +145 -0
- package/dist/Files.js.map +1 -0
- package/dist/Generate.d.ts +80 -0
- package/dist/Generate.d.ts.map +1 -0
- package/dist/Generate.js +310 -0
- package/dist/Generate.js.map +1 -0
- package/dist/Guards.d.ts +45 -0
- package/dist/Guards.d.ts.map +1 -0
- package/dist/Guards.js +530 -0
- package/dist/Guards.js.map +1 -0
- package/dist/Inspect.d.ts +125 -0
- package/dist/Inspect.d.ts.map +1 -0
- package/dist/Inspect.js +270 -0
- package/dist/Inspect.js.map +1 -0
- package/dist/Keychain.d.ts +57 -0
- package/dist/Keychain.d.ts.map +1 -0
- package/dist/Keychain.js +73 -0
- package/dist/Keychain.js.map +1 -0
- package/dist/Lock.d.ts +13 -0
- package/dist/Lock.d.ts.map +1 -0
- package/dist/Lock.js +145 -0
- package/dist/Lock.js.map +1 -0
- package/dist/Mcp.d.ts +91 -0
- package/dist/Mcp.d.ts.map +1 -0
- package/dist/Mcp.js +128 -0
- package/dist/Mcp.js.map +1 -0
- package/dist/Merge.d.ts +18 -0
- package/dist/Merge.d.ts.map +1 -0
- package/dist/Merge.js +43 -0
- package/dist/Merge.js.map +1 -0
- package/dist/Migrate.d.ts +78 -0
- package/dist/Migrate.d.ts.map +1 -0
- package/dist/Migrate.js +288 -0
- package/dist/Migrate.js.map +1 -0
- package/dist/Plugins.d.ts +36 -0
- package/dist/Plugins.d.ts.map +1 -0
- package/dist/Plugins.js +304 -0
- package/dist/Plugins.js.map +1 -0
- package/dist/Postgres.d.ts +73 -0
- package/dist/Postgres.d.ts.map +1 -0
- package/dist/Postgres.js +294 -0
- package/dist/Postgres.js.map +1 -0
- package/dist/Publish.d.ts +23 -0
- package/dist/Publish.d.ts.map +1 -0
- package/dist/Publish.js +59 -0
- package/dist/Publish.js.map +1 -0
- package/dist/Registry.d.ts +539 -0
- package/dist/Registry.d.ts.map +1 -0
- package/dist/Registry.js +340 -0
- package/dist/Registry.js.map +1 -0
- package/dist/Remote.d.ts +90 -0
- package/dist/Remote.d.ts.map +1 -0
- package/dist/Remote.js +1006 -0
- package/dist/Remote.js.map +1 -0
- package/dist/Run.d.ts +120 -0
- package/dist/Run.d.ts.map +1 -0
- package/dist/Run.js +477 -0
- package/dist/Run.js.map +1 -0
- package/dist/SyncGen.d.ts +118 -0
- package/dist/SyncGen.d.ts.map +1 -0
- package/dist/SyncGen.js +392 -0
- package/dist/SyncGen.js.map +1 -0
- package/dist/Update.d.ts +301 -0
- package/dist/Update.d.ts.map +1 -0
- package/dist/Update.js +627 -0
- package/dist/Update.js.map +1 -0
- package/dist/bin.d.ts +3 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +42 -0
- package/dist/bin.js.map +1 -0
- package/dist/docs/backlog.md +56 -0
- package/dist/docs/ci.md +277 -0
- package/dist/docs/cli.md +696 -0
- package/dist/docs/connectors/google.md +115 -0
- package/dist/docs/connectors/http-openapi.md +7 -0
- package/dist/docs/connectors/mcp.md +8 -0
- package/dist/docs/connectors/microsoft-graph.md +75 -0
- package/dist/docs/connectors/openai.md +25 -0
- package/dist/docs/connectors/slack.md +162 -0
- package/dist/docs/connectors/workos.md +39 -0
- package/dist/docs/contracts/README.md +173 -0
- package/dist/docs/contracts/action-consent.md +92 -0
- package/dist/docs/contracts/action-registry.md +85 -0
- package/dist/docs/contracts/actor.md +100 -0
- package/dist/docs/contracts/agent-resources.md +90 -0
- package/dist/docs/contracts/agent-runtime.md +257 -0
- package/dist/docs/contracts/approvals.md +126 -0
- package/dist/docs/contracts/audit.md +75 -0
- package/dist/docs/contracts/auth-provider.md +74 -0
- package/dist/docs/contracts/calendar-provider.md +46 -0
- package/dist/docs/contracts/client-sdk.md +245 -0
- package/dist/docs/contracts/collab-document.md +151 -0
- package/dist/docs/contracts/command.md +44 -0
- package/dist/docs/contracts/connections.md +235 -0
- package/dist/docs/contracts/context-accounting.md +50 -0
- package/dist/docs/contracts/daemon.md +243 -0
- package/dist/docs/contracts/db-tx.md +53 -0
- package/dist/docs/contracts/delegation.md +68 -0
- package/dist/docs/contracts/device-control.md +103 -0
- package/dist/docs/contracts/directory-provider.md +36 -0
- package/dist/docs/contracts/directory.md +161 -0
- package/dist/docs/contracts/document-source.md +33 -0
- package/dist/docs/contracts/files.md +115 -0
- package/dist/docs/contracts/flags.md +83 -0
- package/dist/docs/contracts/host.md +68 -0
- package/dist/docs/contracts/http-api.md +43 -0
- package/dist/docs/contracts/ingestion.md +130 -0
- package/dist/docs/contracts/ingress.md +141 -0
- package/dist/docs/contracts/invocation.md +260 -0
- package/dist/docs/contracts/local-client.md +110 -0
- package/dist/docs/contracts/locale.md +56 -0
- package/dist/docs/contracts/machine-identity.md +117 -0
- package/dist/docs/contracts/mail-provider.md +49 -0
- package/dist/docs/contracts/memory.md +53 -0
- package/dist/docs/contracts/messaging.md +40 -0
- package/dist/docs/contracts/metering.md +139 -0
- package/dist/docs/contracts/model-provider.md +84 -0
- package/dist/docs/contracts/module-manifest.md +213 -0
- package/dist/docs/contracts/notification-channel.md +90 -0
- package/dist/docs/contracts/notifications.md +123 -0
- package/dist/docs/contracts/outbox.md +80 -0
- package/dist/docs/contracts/privacy.md +110 -0
- package/dist/docs/contracts/progress.md +52 -0
- package/dist/docs/contracts/query-surface.md +108 -0
- package/dist/docs/contracts/readiness.md +63 -0
- package/dist/docs/contracts/release.md +142 -0
- package/dist/docs/contracts/result-rendering.md +61 -0
- package/dist/docs/contracts/sandbox.md +186 -0
- package/dist/docs/contracts/scheduler.md +148 -0
- package/dist/docs/contracts/screen-context.md +81 -0
- package/dist/docs/contracts/search.md +120 -0
- package/dist/docs/contracts/secrets.md +74 -0
- package/dist/docs/contracts/settings.md +109 -0
- package/dist/docs/contracts/sharing.md +77 -0
- package/dist/docs/contracts/slot.md +48 -0
- package/dist/docs/contracts/space.md +67 -0
- package/dist/docs/contracts/storage-adapter.md +45 -0
- package/dist/docs/contracts/storage-backend.md +56 -0
- package/dist/docs/contracts/sync.md +213 -0
- package/dist/docs/contracts/telemetry.md +80 -0
- package/dist/docs/contracts/theme-tokens.md +50 -0
- package/dist/docs/contracts/tool-source.md +58 -0
- package/dist/docs/contracts/versioning.md +99 -0
- package/dist/docs/contracts/view.md +65 -0
- package/dist/docs/contracts/work-items.md +99 -0
- package/dist/docs/contracts/workflow.md +82 -0
- package/dist/docs/decisions.md +163 -0
- package/dist/docs/example-app.md +192 -0
- package/dist/docs/getting-started.md +927 -0
- package/dist/docs/goal.md +54 -0
- package/dist/docs/parity.md +29 -0
- package/dist/docs/performance.md +129 -0
- package/dist/docs/registry/README.md +74 -0
- package/dist/docs/registry/app.md +38 -0
- package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
- package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
- package/dist/docs/registry/calendar.md +35 -0
- package/dist/docs/registry/chat-ui-foldkit.md +30 -0
- package/dist/docs/registry/desktop-rune.md +50 -0
- package/dist/docs/registry/desktop.md +32 -0
- package/dist/docs/registry/eloxiv-action.md +25 -0
- package/dist/docs/registry/eloxiv-connector.md +25 -0
- package/dist/docs/registry/eloxiv-module.md +25 -0
- package/dist/docs/registry/eloxiv-policy.md +25 -0
- package/dist/docs/registry/eloxiv-view.md +25 -0
- package/dist/docs/registry/hello-ui-foldkit.md +29 -0
- package/dist/docs/registry/hello.md +39 -0
- package/dist/docs/registry/home-ui-foldkit.md +27 -0
- package/dist/docs/registry/home.md +29 -0
- package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
- package/dist/docs/registry/mail-ui-foldkit.md +27 -0
- package/dist/docs/registry/mail.md +34 -0
- package/dist/docs/registry/meeting-prep.md +26 -0
- package/dist/docs/registry/members-ui-foldkit.md +28 -0
- package/dist/docs/registry/mobile.md +37 -0
- package/dist/docs/registry/notes-ui-foldkit.md +27 -0
- package/dist/docs/registry/notes.md +26 -0
- package/dist/docs/registry/people-ui-foldkit.md +28 -0
- package/dist/docs/registry/people.md +38 -0
- package/dist/docs/registry/shell-foldkit.md +35 -0
- package/dist/docs/registry/theme.md +25 -0
- package/dist/docs/registry/ui-conformance.md +30 -0
- package/dist/docs/release.md +100 -0
- package/dist/docs/scaffold.md +826 -0
- package/dist/docs/security/threat-model.md +299 -0
- package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -3
- package/src/AgentSkills.ts +329 -0
- package/src/AgentWeb.ts +507 -0
- package/src/App.ts +435 -0
- package/src/Blueprint.ts +276 -0
- package/src/Brand.ts +415 -0
- package/src/Changelog.ts +136 -0
- package/src/Cli.ts +1458 -0
- package/src/DbAdmin.ts +115 -0
- package/src/Dependencies.ts +170 -0
- package/src/Deploy.ts +563 -0
- package/src/Docs.ts +309 -0
- package/src/Doctor.ts +424 -0
- package/src/Dossier.ts +148 -0
- package/src/Emit.ts +68 -0
- package/src/Errors.ts +18 -0
- package/src/Evals.ts +153 -0
- package/src/Files.ts +152 -0
- package/src/Generate.ts +402 -0
- package/src/Guards.ts +541 -0
- package/src/Inspect.ts +358 -0
- package/src/Keychain.ts +107 -0
- package/src/Lock.ts +174 -0
- package/src/Mcp.ts +159 -0
- package/src/Merge.ts +70 -0
- package/src/Migrate.ts +331 -0
- package/src/Plugins.ts +347 -0
- package/src/Postgres.ts +353 -0
- package/src/Publish.ts +64 -0
- package/src/Registry.ts +405 -0
- package/src/Remote.ts +1158 -0
- package/src/Run.ts +541 -0
- package/src/SyncGen.ts +570 -0
- package/src/Update.ts +873 -0
- package/src/bin.ts +46 -0
- package/src/index.ts +7 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Notifications
|
|
2
|
+
|
|
3
|
+
Durable notifications per recipient: in-app records each person reads, marks and dismisses (synced to their replica), delivered through channels ([NotificationChannel](notification-channel.md)) by category, according to each person's preferences, with retries and a delivery log. System email uses registered templates with variables, per-organisation overrides, preview, a one-click unsubscribe link and suppression.
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.3.0 (1.1.0: the `list`, `count` and `notify` actions, a person's own notifications read and sent from any surface; 1.2.0: push installations (`registerInstallation`, `unregisterInstallation`), push delivery through the kernel's channel, and decisions from a notification (`decide`); 1.3.0: the kernel's consent and approval texts name the action by its title (`Your agent wants to: <title>`, `Approval needed: <title>`; `approvals.decided` leads with the outcome, `{{status}}: {{action}}`, and never shows an error tag), in-app, by push and in email, where `{{action}}` is now the title and `{{actionName}}` the id; the push installation actions are offered on no agent surface).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/Notifications.json`](../../packages/contracts/schema/contracts/Notifications.json) (source [`Notifications.ts`](../../packages/contracts/src/contracts/Notifications.ts)).
|
|
7
|
+
- Implementation: [`packages/kernel/src/Notifications.ts`](../../packages/kernel/src/Notifications.ts); the kernel-provided `notifications` module ([`inbox/notifications.ts`](../../packages/kernel/src/inbox/notifications.ts), schema `eloxiv_notifications`).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/Notifications` ([source](../../packages/testing/src/conformance/Notifications.ts)), run by [`packages/testing/test/notifications.test.ts`](../../packages/testing/test/notifications.test.ts) with email delivered to a real SMTP server the test starts ([`SmtpSink.ts`](../../packages/testing/src/SmtpSink.ts)); push installations and delivery by `pushConformance` ([`Push.ts`](../../packages/testing/src/conformance/Push.ts), run by [`push.test.ts`](../../packages/testing/test/push.test.ts)); decisions by `decisionTokenConformance` ([`DecisionTokens.ts`](../../packages/testing/src/conformance/DecisionTokens.ts), run by [`decision-tokens.test.ts`](../../packages/testing/test/decision-tokens.test.ts)), both against APNs and FCM protocol fakes.
|
|
9
|
+
|
|
10
|
+
## Sending
|
|
11
|
+
|
|
12
|
+
From a handler (`ctx.notify.send`, applied with the call's transaction), a subscriber (`ctx.notify.send`, with its delivery), or kernel code (`Notifications.send`):
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
yield* ctx.notify.send({
|
|
16
|
+
recipients: [ownerId], // members of the organisation
|
|
17
|
+
category: "purchases.ordered", // preferences are per category
|
|
18
|
+
title: "Order placed",
|
|
19
|
+
body: `Your order for ${amount} was placed.`,
|
|
20
|
+
link: { module: "purchases", entity: "order", id },
|
|
21
|
+
email: { template: "purchases.receipt", variables: { item, amount } },
|
|
22
|
+
key: `ordered:${id}`, // one notification per (key, recipient)
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Operations
|
|
27
|
+
|
|
28
|
+
| Operation | Input | Output | Errors |
|
|
29
|
+
| --- | --- | --- | --- |
|
|
30
|
+
| `send` | `SendNotification` | `ids` | `InvalidInput` (a recipient is not a member), `UnknownTemplate` |
|
|
31
|
+
| `list` | action `notifications.list`: `unreadOnly?`, `category?`, `limit?` (1 to 200, default 50) | `notifications`: the caller's own in the organisation they act in, newest first, dismissed ones left out | the standard error set |
|
|
32
|
+
| `count` | action `notifications.count`: `category?` | `unread`: the caller's unread, undismissed notifications | the standard error set |
|
|
33
|
+
| `notify` | action `notifications.notify`: `title`, `body`, `recipients?` (default: the caller), `category?` (default `message`), `link?`, `email?` | `recipients` | `Forbidden` (another recipient without `notifications.send`), `InvalidInput` (a recipient who is not a member) |
|
|
34
|
+
| `markRead` | action `notifications.markRead`: `id` | `id` | the standard error set |
|
|
35
|
+
| `markUnread` | action `notifications.markUnread`: `id` | `id` | the standard error set |
|
|
36
|
+
| `dismiss` | action `notifications.dismiss`: `id` | `id` | the standard error set |
|
|
37
|
+
| `setPreference` | action `notifications.setPreference`: `category`, `channels`, optional `add` (`true`: the channels are added to the person's current ones, email when they never chose, in one write, instead of replacing them) | `id` | the standard error set |
|
|
38
|
+
| `setEmailTemplate` | action `notifications.setEmailTemplate`: `template`, `subject`, `text`, optional `html` (needs `notifications.manage`) | `id` | the standard error set |
|
|
39
|
+
| `preview` | `orgId`, `template`, `variables` | `RenderedEmail` | `UnknownTemplate` |
|
|
40
|
+
| `unsubscribe` | `token` (the link `GET`/`POST /notifications/unsubscribe?token=...`) | `category` | `InvalidInput` |
|
|
41
|
+
| `registerInstallation` | action `notifications.registerInstallation`: `installationId` (a UUID), `provider` (`apns`, `fcm`), `token`, `appId`, `environment?` (`production`, `sandbox`; APNs only, default `production`) | `installationId` | `Forbidden` (anything but the person's own signed-in session), the standard error set |
|
|
42
|
+
| `unregisterInstallation` | action `notifications.unregisterInstallation`: `installationId` | `installationId` | the standard error set |
|
|
43
|
+
| `decide` | `POST /api/notifications/decide { token, verdict }` (not an action) | `DecideResult`: `kind`, `requestId`, `verdict`, `status`, `replayed` | `InvalidDecision` (400), `DecisionExpired` (410), the action's refusal (`Forbidden` 403, `InvalidInput` 409), `RateLimited` (429), `ActionFailed` (503: nothing was decided, try again) |
|
|
44
|
+
| `deliveries` | `orgId`, `notificationId` | the delivery log | none |
|
|
45
|
+
|
|
46
|
+
The actions belong to the kernel-provided `notifications` module: on every surface, authorised by its policy (a notification's recipient alone marks it; a person sets their own preferences; `notifications.manage` overrides templates and reads the delivery log and suppression list of the organisation), and audited.
|
|
47
|
+
|
|
48
|
+
`notifications.notify` is how a person or their agent sends one (an agent's reminder, the result of unattended work): to oneself always, to other members of the organisation only with the `notifications.send` permission. It is sent with the call (idempotent on the call), delivered like any other, and as system email (the `notifications.message` template) only when `email` is true and the recipient's preferences include email.
|
|
49
|
+
|
|
50
|
+
## Delivery
|
|
51
|
+
|
|
52
|
+
`send` writes, in one transaction: one notification per recipient (the durable in-app record; with a `key`, a second send for the same recipient is skipped), and for every other channel the recipient's preference for the category names (default: `email`), a delivery in the delivery log plus an outbox event `notifications.deliver`. The kernel delivers each event through its channel (a kernel reaction run by the outbox dispatcher, see [Outbox](outbox.md)):
|
|
53
|
+
|
|
54
|
+
- accepted: the delivery is `sent`, with the provider's id and the attempt count;
|
|
55
|
+
- a retryable failure (a 4xx SMTP reply, an unreachable server): the delivery fails, so the outbox retries it with backoff, up to 8 attempts, then records it `failed`;
|
|
56
|
+
- a permanent failure (a 5xx reply, a refused recipient): recorded `failed` at once;
|
|
57
|
+
- an address suppressed for the category (or all categories): recorded `suppressed`, never sent.
|
|
58
|
+
|
|
59
|
+
Delivery is at least once: a kernel that dies after the server accepted a message and before the delivery was recorded sends it again, with the same `Message-ID` (`<delivery id>@eloxiv`), so mail systems can drop the duplicate.
|
|
60
|
+
|
|
61
|
+
In-app is always kept (it is the notification); preferences choose the other channels (`email`; `push` when the deployment configured a push provider). An empty list keeps a category in-app only.
|
|
62
|
+
|
|
63
|
+
## Push
|
|
64
|
+
|
|
65
|
+
A person's app installation registers its native APNs or FCM token with `notifications.registerInstallation` (never a relay service's token), from the person's own signed-in session: an agent (agent tools, MCP, an agent session), an API token, an OAuth grant and a device are refused. Installations are the person's across organisations (`eloxiv.push_installation`), one per `installationId` (the app install's stable id): registering it again replaces the token, app id and environment (rotation) and binds it to the calling session; when anything of it changed, it is a new registration (its `generation`), and decision tokens sent to the old one no longer redeem. A token is in one installation at a time: registered again anywhere (by anyone), it leaves where it was; registrations of one token are serialised, so many at once all succeed and the last one holds it. Tokens up to the contract's 4,096 characters register (uniqueness is kept on the token's SHA-256). Signing out of the registering session, or the kernel revoking it, deletes the installation at once (database triggers), so no device keeps receiving after its sign-out; erasure deletes every installation of the person; `unregisterInstallation` deletes one. Registration is audited (provider and app id, never the token).
|
|
66
|
+
|
|
67
|
+
A notification whose recipient's preference for its category includes `push` is delivered by the kernel's push channel to every live installation ([NotificationChannel](notification-channel.md#the-push-channel)), carrying the notification's organisation, id and category, and `link`: the [View](view.md) deep link that opens the notification's record, chosen as `recordLink` chooses (the first installed view, in module order then id, that shows the record's entity, in the notification's organisation), or null when no view shows it. A host writes the link out on its own origin or scheme. A consent request's body is replaced by fixed text: the lock screen never shows the call's input. A send is skipped when, as it is claimed, the installation is no longer the same registration of the recipient under a valid session, or the recipient is no longer a member of the organisation.
|
|
68
|
+
|
|
69
|
+
## Decisions from a notification
|
|
70
|
+
|
|
71
|
+
The kernel's own approval and consent notifications offer a decision by push (`aps.category`, or FCM's `categoryId`, `eloxiv.decision`, and `eloxiv.decision = { kind: "approval" | "consent", requestId, verdicts: ["approve", "reject"], token? }`), and only while their request is pending. The token goes to **APNs installations only**: an Android notification's data reaches its posted extras (readable by apps with notification access) and debug logs, so an FCM payload offers the decision without one. An Android notification action never decides by itself (another app with notification access can invoke it): Approve or Reject opens the exact request in the app with that verdict preselected, and the decision is sent only when the person confirms it there, through their own session with the same actions, after checking the signed-in person, the installation and the organisation (the one the app opened the request in, and the generation it was shown for) against the payload's `userId`, `installationId` and `orgId` as it dispatches. A consent's Reject sent this way is `consent.rejectPending` ([ActionConsent](action-consent.md#operations); a kernel without that action refuses it rather than withdrawing an approval): an approval made meanwhile in chat or on another device stands, as it does for a token. Nothing is minted for an FCM installation. Which notifications offer one is the kernel's to say, never the notification's category or link: a notification sent with `notifications.notify` (or by module code) offers no decision whatever it names, and a decision's push text is derived from the request (its action and requester), not from the notification. An APNs token is single use, one per notification and installation registration, stored only as its SHA-256 (`eloxiv.notification_decision`) with the person, organisation, request and verdicts it may decide, and the session and registration generation it was sent to; it expires after 24 hours, or with the approval request when sooner. Its plaintext is only in the provider payload: never in a synced row, the delivery log, the audit log, the outbox, a URL or a log.
|
|
72
|
+
|
|
73
|
+
The person's tap on Approve or Reject (a notification action, never a tap on the notification, which only navigates) posts `{ token, verdict }` to `POST /api/notifications/decide`. No session is needed; each client address may try 30 a minute; every answer is `no-store`.
|
|
74
|
+
|
|
75
|
+
1. The token must be known, offer the verdict, not have expired, and still belong to the registration it was sent to: the same installation, registered by the same session (unexpired, not signed out or revoked, and signed in by a method the organisation admits, as for any call of the person's, checked under the organisation's directory lock held shared until the decision commits, so a change to the sign-in methods waits for it or refuses it) with the same generation (signing out, unregistering, or registering the installation again from any session kills its tokens); otherwise `400 InvalidDecision` or `410 DecisionExpired`, audited (`notifications.decide`, `denied`, with a hash of the token's hash, never the token). A spent token's recorded answer is released only under the same conditions.
|
|
76
|
+
2. The decision runs through the existing action through the one invocation path, as the person (origin `person`, surface `http`) under the registering session (held while the call runs and checked again at its commit, so a sign-out either waits for the decision or is seen by it): `approvals.approve` or `approvals.reject`, `consent.approve` with `remember: "once"` (never a remembered permission) or `consent.reject`, with the chat SDK's decision key as its idempotency key (`approval:<id>:<verdict>`, `consent:<id>:<verdict>:once`). Membership, the action's Cedar policy, the approver's live eligibility, the request's status and expiry are all resolved again now; the call is audited as any of theirs. Unregistering or registering the installation again waits for a decision in progress through it.
|
|
77
|
+
3. Push decisions of one request by one person are serialised, and a consent must still be pending, its row locked: a consent the person already decided (in chat, or from another device) is not decided again from a push. The same verdict answers `200` with the request's status and `replayed: true`; the opposite one answers `409` and changes nothing. Withdrawing an approved consent stays the explicit `consent.reject` in the app or chat. Two devices answering one consent with opposite verdicts at once: one decides, the other is refused.
|
|
78
|
+
4. The token's row is held by a transaction of the route's own, in which the action runs in a savepoint: the decision and the token's recorded answer commit together, or neither does. The token's expiry is read again after every lock the decision waited for. A decision that commits, or that the action refuses for good (`403` no longer eligible or not a member, `409` no longer pending), spends the token; a transient failure (`503 ActionFailed`, also when the token's answer could not be stored, the database connection was lost or the commit is uncertain, `no-store` like every answer) leaves nothing decided and the token unspent (a commit that did happen is replayed by the next try). Any later redemption, whatever its verdict, answers the recorded outcome with `replayed: true` and decides nothing, also one racing the first.
|
|
79
|
+
5. A decision the person already made the same way elsewhere (the approval action's own idempotency, in chat or from another device, also a chat decision that carried a comment: matched against the person's vote) decides nothing and answers `200` with the request's status as it now stands (`pending` while an approval waits for its quorum) and `replayed: true`. The status is read once, its row locked until the answer commits.
|
|
80
|
+
6. It is not an action: no agent tool, MCP tool or synced row reaches it. The token is a bearer credential: whoever holds it can make the one decision it offers, as the person, until it expires or its registration ends.
|
|
81
|
+
|
|
82
|
+
The response is `200 { kind, requestId, verdict, status, replayed }` (status as the action returned it: an approval's `pending`, `approved` or `rejected`; a consent's `approved` or `rejected`), or the error as above.
|
|
83
|
+
|
|
84
|
+
## Email
|
|
85
|
+
|
|
86
|
+
Templates are registered in code: the kernel's own (`approvals.requested`, `approvals.decided`, `consent.requested`) and the app's (`KernelApp.emailTemplates`), each with an id, subject, text, optional HTML and its variables. `{{name}}` is replaced by the variable (`renderPlaceholders` in `@eloxiv/contracts`): a missing variable renders empty, a non-string is JSON, and HTML escapes every value. An organisation's override (`setEmailTemplate`) replaces subject, text and HTML for that organisation; `preview` renders either with example variables, sending nothing.
|
|
87
|
+
|
|
88
|
+
Every email carries `List-Unsubscribe: <url>` and `List-Unsubscribe-Post: List-Unsubscribe=One-Click` (RFC 8058), `X-Eloxiv-Category` and `X-Eloxiv-Notification`. The URL's token is signed (HMAC with the kernel's secret) and names the organisation, the person and the category. Following it (one-click `POST`, or `GET`) suppresses the address for that category and removes email from the person's preference; it needs no session and is audited (`notifications.unsubscribe`, surface `http`). A forged token is refused (400).
|
|
89
|
+
|
|
90
|
+
Configuration: `ELOXIV_SMTP_URL` (`smtp://user:password@host:port` or `smtps://...`) and `ELOXIV_EMAIL_FROM` (`Name <address>`), or `KernelConfig.email`. Without them the kernel has no email channel and notifications stay in-app.
|
|
91
|
+
|
|
92
|
+
## Records
|
|
93
|
+
|
|
94
|
+
- **`Notification`**: `id`, `orgId`, `recipientId`, `category`, `title`, `body`, `link` (`EntityReference` or null), `createdAt`, `readAt`, `dismissedAt`.
|
|
95
|
+
- **`EmailTemplate`**, **`RenderedEmail`**, **`SendNotification`**, **`Preference`** (`category`, `channels`).
|
|
96
|
+
- **`PushProvider`**, **`PushInstallationRegistration`**, **`DecideRequest`**, **`DecideResult`**, and the errors **`InvalidDecision`** and **`DecisionExpired`**.
|
|
97
|
+
- The delivery log's **`DeliveryRecord`** is published with [NotificationChannel](notification-channel.md).
|
|
98
|
+
|
|
99
|
+
## Sync
|
|
100
|
+
|
|
101
|
+
`notifications.mine` (from `@eloxiv/client/sync`, see [WorkItems](work-items.md#sync)) holds the person's own notifications in the organisation they act in, filtered by the module's read policy.
|
|
102
|
+
|
|
103
|
+
## Guarantees
|
|
104
|
+
|
|
105
|
+
1. A notification is durable and reaches only its recipient's replica; only the recipient marks or dismisses it.
|
|
106
|
+
2. Sending is part of the caller's transaction: a rolled-back call notifies nobody.
|
|
107
|
+
3. Channels are chosen per person and category; suppressed addresses are never sent to.
|
|
108
|
+
4. Each delivery is retried until accepted or permanently failed, and every outcome is in the delivery log.
|
|
109
|
+
5. Push goes only to installations their person registered from a session still in force; a decision from a notification is the person's, once, through the existing action under live policy.
|
|
110
|
+
|
|
111
|
+
## How an implementation is checked
|
|
112
|
+
|
|
113
|
+
`notificationsConformance(start)` registers, against the inbox conformance app: a subscriber's notification reaches the order's owner in-app; sync holds a notification for its recipient only, who alone marks it read, unread and dismissed; system email arrives at the SMTP server with the template's subject, text and escaped HTML, a stable Message-ID, the category header and one-click unsubscribe headers, and is logged `sent`; two temporary failures are retried (three attempts logged); a refused recipient is logged `failed` after one attempt; a preference without email keeps a category in-app; only managers override a template, the preview shows it (and not in another organisation), and the next email uses it; the unsubscribe link (a forged one is refused) is audited, stops email for the category, and turning email back on still finds the address suppressed.
|
|
114
|
+
|
|
115
|
+
`pushConformance(start)` checks installations: registered from the person's own session and rotated on registering again (the next push goes to the new token only); refused for an agent (agent tools, MCP, an agent session); a token moving to whoever registered it last; sign-out removing exactly what that session registered; erasure removing all; and delivery and provider answers ([NotificationChannel](notification-channel.md#how-an-implementation-is-checked)). `decisionTokenConformance(start)` checks: an FCM installation offered the decision without a token, none minted for it; an approval approved as the person through the token (vote, audit, `no-store`), with the push's link and decision; a rejection, then both verdicts again answering the recorded outcome with nothing decided; opposite verdicts at once deciding once; consent approved (no permission remembered) and rejected; an unknown, altered or malformed token refused and audited; a token expired with its approval; a token of a person who lost the approver's role refused and spent; a token whose installation's session signed out refused; no agent or MCP route to it; the token in none of the notification, delivery, audit, outbox, push-delivery or idempotency rows. It also checks that an ordinary notification naming an approval request offers no decision; that a token is refused once its installation was registered again from another session, once the registering session expired, or once the organisation no longer admits how that session signed in; that a change to the organisation's sign-in methods waits for a decision already under way to commit; that two devices answering a consent with opposite verdicts decide it once, one after the other and at once; that a consent approved in chat is not rejected from a push; that a decision already made with the same verdict answers the request's status, and that a consent withdrawn while a redemption that found it approved runs is answered from one state (409, never an approval answered with the withdrawn status); that redemptions racing the first all answer what committed; that a recorded answer is not released after sign-out or expiry; that an approval given in chat with a comment answers the push's same verdict as a replay; and that a failure to store the token's answer, or the connection lost while storing it, answers `503` `no-store`, decides nothing, and the next try decides. The route's classification of refusals (definitive ones spend, transient ones do not) and of storage failures (also a failed rollback's defect) is checked by `packages/kernel/test/push-decisions.test.ts`.
|
|
116
|
+
|
|
117
|
+
## Not yet guaranteed
|
|
118
|
+
|
|
119
|
+
- Engagement (opens, clicks) is not recorded; the delivery log records sends.
|
|
120
|
+
- Bounces and complaints do not feed the suppression list yet (only unsubscribe does).
|
|
121
|
+
- No digesting or rate limiting per person.
|
|
122
|
+
- A decision token (APNs only) is a bearer credential for its one decision until it expires or its registration ends: an app that leaks it (or a device left signed in) lets its holder make that decision as the person. Android decides in the app instead, with no token.
|
|
123
|
+
- Installations whose session expired without a sign-out get nothing (delivery checks the session), but their rows stay until the session's row is deleted.
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Outbox
|
|
2
|
+
|
|
3
|
+
The transactional outbox (decision 4): how modules react to each other's changes. An event is written in the same transaction as the change that caused it and delivered reliably, with retries, to every module that subscribes to it. A delivery that keeps failing is retried under its subscriber's delivery policy and then dead-lettered, never retried forever. "Outbox" means the pattern, not outgoing email.
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.1.0.
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/Outbox.json`](../../packages/contracts/schema/contracts/Outbox.json) (source [`Outbox.ts`](../../packages/contracts/src/contracts/Outbox.ts)).
|
|
7
|
+
- Implementation: the `Outbox` service and `OutboxDispatcher` in [`packages/kernel/src/Outbox.ts`](../../packages/kernel/src/Outbox.ts), delivery policies in [`DeliveryPolicy.ts`](../../packages/kernel/src/DeliveryPolicy.ts); tables `eloxiv.outbox`, `eloxiv.outbox_delivery` and `eloxiv.outbox_failure` (kernel migration `0016_dead_letters`).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/Outbox` ([source](../../packages/testing/src/conformance/Outbox.ts)).
|
|
9
|
+
|
|
10
|
+
## Operations
|
|
11
|
+
|
|
12
|
+
| Operation | Input | Output | What it does |
|
|
13
|
+
| --- | --- | --- | --- |
|
|
14
|
+
| `publish` | `OutboxPublish`: `invocationId`, `type`, `module`, `orgId`, `payload` | `{ id }` | Writes the event in the current transaction and wakes dispatchers at commit (`pg_notify` on `eloxiv_outbox`). The invocation path calls it for each event a handler emits (`ctx.emit`) |
|
|
15
|
+
| `dispatch` | `{}` | `{ delivered }` | One delivery pass: claims up to 50 due, unsettled events (`FOR UPDATE SKIP LOCKED`, so several dispatchers can run), runs every delivery that is due (not yet succeeded, not dead, not backing off), records each outcome; `delivered` is how many events became fully delivered. The kernel runs it continuously, woken by notifications and polling |
|
|
16
|
+
| `events` | `OutboxFilter`: `ids`, `invocationId`, `type` (all optional) | `OutboxEventStatus[]`, oldest first | Events and their delivery state |
|
|
17
|
+
| `retry` | `{ eventId }` | `{}` | Makes an unsettled event, and its retrying deliveries, due now without waiting out their backoff. It does not reopen dead letters |
|
|
18
|
+
| `deadLetters` | `DeadLetterFilter`: `orgId`, `eventId`, `subscriber`, `state` (default `dead`) | `DeadLetter[]` | Operators and trusted code: dead letters across organisations |
|
|
19
|
+
| `listDeadLetters` | `{ state? }` | `DeadLetter[]` | **Administrator:** the dead letters of the organisation the caller acts in (`discarded` lists closed ones) |
|
|
20
|
+
| `retryDeadLetter` | `{ eventId, subscriber }` | `{}` | **Administrator:** runs a dead letter again with a fresh budget (attempts and age count from the retry); the event is claimed again |
|
|
21
|
+
| `discardDeadLetter` | `{ eventId, subscriber }` | `{}` | **Administrator:** closes a dead letter without running it. It stays visible as `discarded`, with who closed it and when |
|
|
22
|
+
|
|
23
|
+
`publish`, `dispatch`, `events`, `retry` and `deadLetters` do not fail with a typed error. The administrator operations are called with the caller's request credentials (in the kernel, `Outbox.as(headers).<operation>(input)`, like the [Directory](directory.md)'s management operations). Each authenticates the caller afresh, acts only in the organisation the caller acts in, needs the `eloxiv.outbox.manage` permission there (checked against the live directory, in the operation's transaction; the built-in `admin` role grants it), and is audited (`eloxiv.outbox.<operation>`, surface `internal`): `succeeded`, or `denied` (`Unauthenticated`, `Forbidden`) or `failed` (`InvalidInput`: no such open dead letter in the organisation) after rollback. They fail with `Unauthenticated`, `Forbidden` or `InvalidInput`.
|
|
24
|
+
|
|
25
|
+
A module subscribes in its server definition: `subscribe(id, eventContract, (payload, ctx) => ..., { delivery })`, where `ctx` is the [`SubscriberContext`](db-tx.md#records), `ctx.sql` runs in the delivery's savepoint, and `delivery` is optional. Event triggers ([Scheduler](scheduler.md)) take the same `delivery` field.
|
|
26
|
+
|
|
27
|
+
## Delivery policies
|
|
28
|
+
|
|
29
|
+
`DeliveryPolicy`, every field optional:
|
|
30
|
+
|
|
31
|
+
| Field | Default | Meaning |
|
|
32
|
+
| --- | --- | --- |
|
|
33
|
+
| `maxAttempts` | 20 | Attempts before the delivery is exhausted. Must be a whole number of at least 1: nothing is retried forever |
|
|
34
|
+
| `maxAgeMs` | none | Also exhausted once this long has passed since the event occurred (or since a dead letter was retried). Checked before every attempt: a delivery past its age is closed (dead-lettered or discarded, as `onExhausted` says) without running, its attempts as they were and its last error saying so |
|
|
35
|
+
| `backoff.initialMs`, `backoff.factor`, `backoff.maxMs` | 100, 2, 60 000 | Delay before attempt n + 1: `min(maxMs, initialMs * factor^(n - 1))` |
|
|
36
|
+
| `onExhausted` | `dead-letter` | `dead-letter` keeps it for an administrator; `discard` closes it at once (recorded as `discarded`, `closedBy: "policy"`, and logged) |
|
|
37
|
+
|
|
38
|
+
The kernel refuses to start an app whose subscriber or trigger declares a policy it cannot honour (no attempts, infinite attempts, a non-positive age, a shrinking backoff), listing every problem with the app's other manifest problems.
|
|
39
|
+
|
|
40
|
+
## Records
|
|
41
|
+
|
|
42
|
+
- **`OutboxEvent`**: `id`, `invocationId` (the call that emitted it, and its audit record), `type`, `module` (the emitter), `orgId`, `payload` (encoded with the event contract's schema), `occurredAt`.
|
|
43
|
+
- **`OutboxEventStatus`**: the event plus `deliveredAt` (once every subscriber has succeeded), `settledAt` (once nothing is outstanding: each delivery succeeded, or was dead-lettered or discarded), `attempts` (passes that ran at least one of its deliveries), `lastError` (the failing deliveries' errors from the last pass that had any), `nextAttemptAt`, `deliveredTo` (subscriber ids that succeeded) and `failures` (`DeliveryFailure`: `subscriber`, `state` `retrying` / `dead` / `discarded`, `attempts`, `lastError`, `nextAttemptAt`).
|
|
44
|
+
- **`DeadLetter`**: `eventId`, `subscriber`, the event's `type`, `module`, `orgId`, `payload` and `occurredAt`; `state` (`dead` or `discarded`), `attempts`, `lastError`, `firstFailedAt`, `deadAt`, `closedBy` (a user id, `policy`, or null) and `closedAt`.
|
|
45
|
+
- **`Subscription`**: `id` (stable, recorded per delivered event), `event` (type), `module` (whose role it runs as) and `delivery`.
|
|
46
|
+
|
|
47
|
+
## Guarantees
|
|
48
|
+
|
|
49
|
+
1. **Same transaction.** An event exists exactly when the call that emitted it commits. A call that fails after emitting (in its handler, its checks or at commit), or never runs (denied, blocked for approval), leaves no event.
|
|
50
|
+
2. **At-least-once delivery to every subscriber**, in every module that subscribes, including modules other than the emitter's, and to every event trigger on its type, until the delivery succeeds or its policy is exhausted.
|
|
51
|
+
3. **A savepoint per subscriber.** Each delivery runs in its own savepoint, as the subscriber's module role, together with its delivery record: a subscriber's database effects commit exactly when its delivery is recorded. A subscriber that succeeded is never run again for that event, even while another subscriber of the same event is retried or dead-lettered.
|
|
52
|
+
4. **Failures are retried under the subscriber's policy**, with `attempts`, `lastError` and the next attempt persisted per delivery. Typed failures and defects are handled alike; a failing subscriber's effects roll back to its savepoint.
|
|
53
|
+
5. **Never forever: dead letters.** Once a delivery's attempts reach its policy's limit, or its age does (checked before each attempt, so an aged delivery never runs again), it is dead-lettered: it keeps its last error and attempt count, is not run again, and stays listed until an administrator retries it (a fresh budget) or discards it (closed, still listed as `discarded`). With `onExhausted: discard` it is closed at once instead. Either way the kernel logs one error-level line with the event id and type, organisation, subscriber, attempts and last error as structured annotations, and [Readiness](readiness.md) reports open dead letters as a degradation.
|
|
54
|
+
6. **No head-of-line blocking, and no ordering.** A failing or dead delivery never holds up other events or the event's other subscribers: later events are delivered while it waits, and an event whose only outstanding delivery is dead settles. Events are claimed in the order they were written, but nothing orders deliveries across events, or across subscribers of one event; subscribers must not depend on order.
|
|
55
|
+
7. **Subscribers stay in the event's organisation.** They act as a system actor whose row-level security admits only the event's organisation's rows. An administrator sees and manages only their own organisation's dead letters.
|
|
56
|
+
8. **Effects outside the database can repeat.** Delivery is at-least-once: a subscriber that calls an outside service must deduplicate on `ctx.eventId`.
|
|
57
|
+
9. **Subscribers feed the inbox like handlers.** `ctx.workItems` and `ctx.notify` ([WorkItems](work-items.md), [Notifications](notifications.md)) act for the event's organisation and are applied with the delivery, in its savepoint.
|
|
58
|
+
10. **Kernel reactions.** The kernel's own event-driven work (starting and resuming approval workflows on `approvals.requested` and `approvals.decided`, delivering notifications on `notifications.deliver`) is delivered like a subscriber, recorded as `kernel:<id>` (subscriber ids may not take that form), under the default delivery policy; a reaction acts with the kernel's services.
|
|
59
|
+
|
|
60
|
+
## How an implementation is checked
|
|
61
|
+
|
|
62
|
+
`outboxConformance(start)` registers, against the fixture app with its dispatcher running:
|
|
63
|
+
|
|
64
|
+
- an event carries its call's invocation id, module and organisation, and the call's audit record has the same invocation id;
|
|
65
|
+
- calls that crash after emitting, or are blocked for approval, leave no event; nor does a call whose transaction fails at commit, after its events were written (a deferred constraint trigger the kit installs);
|
|
66
|
+
- `dispatch` reports each pass as the contract's `{ delivered }`;
|
|
67
|
+
- one event reaches all five subscribers (four in `docs`, one in `peer`), and `peer`'s ran as `eloxiv_mod_peer` in the event's organisation;
|
|
68
|
+
- with the fixture's fault switch on, a poison event fails and is retried while later events are delivered, with its error recorded and its succeeded subscribers recorded;
|
|
69
|
+
- the retries back off rather than running on every pass;
|
|
70
|
+
- once the fault is fixed and the event retried, it is delivered without re-running subscribers that had succeeded (their rows are not duplicated, and the failed attempts' rows rolled back);
|
|
71
|
+
- a subscriber reaching into another organisation changes nothing there;
|
|
72
|
+
- **dead letters**, with the `docs.poison` subscriber (a policy of 3 attempts, tens of milliseconds apart): a poison delivery is dead-lettered after exactly its policy's attempts with its last error, while a later event and the event's other subscribers are delivered and the event settles; further passes do not run it; a member without the permission is refused (`Forbidden`) on all three administrator operations, an administrator of another organisation neither sees it nor can close it, a caller without a session is `Unauthenticated`, and each call is audited; an administrator's retry re-runs it with a fresh budget (it dead-letters again while the fault is on, and is delivered once it is fixed, without re-running the subscribers that had succeeded); a discarded dead letter is listed as `discarded` with who closed it, cannot be retried, is never run again and leaves its event settled.
|
|
73
|
+
|
|
74
|
+
The Eloxiv kernel runs it in `packages/testing/test/outbox.test.ts`. `packages/testing/test/dead-letters.test.ts` adds: an event trigger whose start keeps failing is dead-lettered under its own policy while the module's own trigger is delivered, with exactly one structured error log; unusable policies are refused before the kernel starts; the default policy dead-letters; a retry that falls due after its maximum age is dead-lettered (or discarded) without running. `registry/test/surfaces.test.ts` proves an event per call on every surface, delivered to the `notes` module's subscriber.
|
|
75
|
+
|
|
76
|
+
## Not yet guaranteed
|
|
77
|
+
|
|
78
|
+
- **The administrator operations are in-process.** They are called through the kernel (`Outbox.as(headers)`); no HTTP route, action or shell screen exposes them yet.
|
|
79
|
+
- **Finer subscriber authorisation**: subscribers act as a system actor limited to the event's organisation; per-subscriber policies are not modelled.
|
|
80
|
+
- **Write-log housekeeping without a dispatcher**: the dispatcher also cleans the invocation write log; a kernel run without one accumulates its rows from writes outside invocations.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Privacy
|
|
2
|
+
|
|
3
|
+
Consent categories per person with regional rules, and data-subject export and erasure across modules, files and connectors (decisions.md "Added 2026-11-02 from the feature ledger's gaps"; the ledger's A-107, B-070, C-026).
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.1.0 (1.1.0: visitors' consent and attribution before sign-in, and their claim).
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/Privacy.json`](../../packages/contracts/schema/contracts/Privacy.json) (source [`Privacy.ts`](../../packages/contracts/src/contracts/Privacy.ts), including `applyConsent`, `regionOf` and the EEA lists); the manifest's `dataSubjects` and its checks in [`Manifest.ts`](../../packages/contracts/src/Manifest.ts).
|
|
7
|
+
- Implementation: the `Privacy` service in [`packages/kernel/src/Privacy.ts`](../../packages/kernel/src/Privacy.ts); the kernel module `privacyModule` ([`privacy/module.ts`](../../packages/kernel/src/privacy/module.ts)); the request workflow `eloxiv.privacy-request` and its reaction ([`privacy/Flow.ts`](../../packages/kernel/src/privacy/Flow.ts)); the client's sync tables and `consentFromReplica` in [`@eloxiv/client/sync`](../../packages/client/src/ServicesSync.ts).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/Privacy` ([source](../../packages/testing/src/conformance/Privacy.ts)).
|
|
9
|
+
|
|
10
|
+
Install `privacyModule` with `progressModule` (requests report through [Progress](progress.md)) and the inbox modules (an agent's erasure request waits for the person's consent).
|
|
11
|
+
|
|
12
|
+
## Consent
|
|
13
|
+
|
|
14
|
+
Categories: `necessary` (always granted; only `true` is accepted), `functional`, `analytics`, `marketing`. Consent is per person **per organisation** (each organisation is its own controller). A person's choice for a category wins; without one, the person's region decides: in an **opt-in** region nothing is granted until chosen, in an **opt-out** region everything is until refused. A person no region places gets the deployment's default mode (`opt-in` unless configured), so the kernel fails closed.
|
|
15
|
+
|
|
16
|
+
Regions are configured on the app (`KernelApp.privacy`): `{ regions: { <id>: { countries?, timeZones?, mode } }, defaultMode? }`. The default is one opt-in region, `eea` (the EEA, Monaco, San Marino, Åland and France's overseas regions, by country and by time zone, ported from agent-native's consent rules). `privacy.setConsent` takes a region hint (`{ country }` from a trusted edge, or the browser's `{ timeZone }`) and records the region it places the person in.
|
|
17
|
+
|
|
18
|
+
`Privacy.allows(org, person, category)` is the gate [Telemetry](telemetry.md) asks before any analytics event leaves; an error reading consent is a refusal.
|
|
19
|
+
|
|
20
|
+
## Visitors, before they sign in
|
|
21
|
+
|
|
22
|
+
A visitor's consent and the touch that brought them are kept by the kernel on their **visit** ([`privacy/Visits.ts`](../../packages/kernel/src/privacy/Visits.ts), table `eloxiv.privacy_visit`, migration `0112_privacy_visits`), named by the cookie `__Host-eloxiv_visit` on HTTPS (HttpOnly, SameSite=Lax, Secure, `Path=/`, no `Domain`, a year: a browser accepts it only from the kernel's own host, so a page on a sibling subdomain cannot plant a visit of its own on a visitor; an unprefixed `eloxiv_visit` is ignored there) and `eloxiv_visit` on plain HTTP (development); the table keeps the cookie's SHA-256, never the cookie. No session is needed.
|
|
23
|
+
|
|
24
|
+
- `POST /privacy/visit` (`VisitRequest`: optional `choices`, `region` hint, `touch`; JSON only) records the visitor's choices (merged with earlier ones; `necessary` is always granted) and the region the hint places them in, and answers `VisitState`: their consent as applied (`applyConsent`, with the deployment's regions: in an opt-in region, the default, nothing is granted until chosen), their attribution and their `claim`. `GET /privacy/visit` answers the same.
|
|
25
|
+
- **A touch is kept only with the visitor's marketing consent as it applies then** (`VisitTouch`: UTM source, medium, campaign, term and content; the referrer, of which only the host is kept; the landing path, without its query or fragment; which ad-click ids were present, never their values). The first touch is kept, the last replaced; each gets a channel (`paid` for an ad-click id or a paid medium, `campaign` for UTM parameters, `referral` for a referrer, else `direct`). Refusing marketing forgets every touch the visit holds.
|
|
26
|
+
- `POST /privacy/visit/claim` (`{ claim }`), by a person's own signed-in session, in one transaction under that session's asserted authority (Authority, with its check at commit: a claim does not commit after a sign-out or a removal from the organisation): the visit becomes theirs; its choices are carried into their consent in the organisation they act in **for the categories they have not chosen themselves** (theirs always win), and its region if they have none; with an analytics destination, the kernel's event `eloxiv.visit_claimed` (`channel` only, category `marketing`) is queued once, so it leaves only with their marketing consent. The claim is audited (`eloxiv.privacy.claimVisit`) and answers the person's consent in the organisation as it now applies. A visit another person claimed is refused (403); once claimed, a visit's attribution is its person's and is no longer shown to an anonymous `GET` or `POST` of the visit. The `claim` is the visit's reference sealed with a key derived from the kernel's secret (a request with a bearer credential reaches the kernel without its cookies, see [Invocation](invocation.md)); the cookie stays HttpOnly.
|
|
27
|
+
- A visit not seen for a year is deleted (a hundred at a time, whenever a visit is recorded). An erasure deletes the visits the person claimed in the organisation; an export holds their choices and touches (the inventory's `eloxiv.privacy_visit`).
|
|
28
|
+
|
|
29
|
+
The client SDK's `consentController({ baseUrl, region?, fetch? })` ([`Consent.ts`](../../packages/client/src/Consent.ts)) is the headless side: `load`, `choose(choices)`, `touch(touchFromLocation(location.href, document.referrer))`, `granted(category)`, `register({ category, load, unload })` (a script loaded once its category is granted and unloaded once withdrawn: the app's analytics, a chat widget, an ad pixel), `subscribe(listener)` (every new state: a banner, or a consent-mode adapter such as Google's, which calls `gtag("consent", "update", ...)` from it) and `claim(token)` after sign-in, after which the controller follows the person's own consent (a category they refused unloads its scripts). Its region defaults to the browser's time zone. On another origin than the kernel's, the kernel must trust the app's origin (`ELOXIV_TRUSTED_ORIGINS`) for the cookie to travel. The banner is the app's; the reference shell has a thin one: with `consent: { scripts?, region? }` in its config it loads the visitor's consent at start, asks (Allow all, or Only necessary) while an optional category is unchosen, and claims the visit at sign-in. Without that config it asks nothing, since an app that loads nothing needing consent has nothing to ask about ([`shell-foldkit-lifecycle.test.ts`](../../registry/test/shell-foldkit-lifecycle.test.ts)).
|
|
30
|
+
|
|
31
|
+
## Data subjects in the manifest
|
|
32
|
+
|
|
33
|
+
Every module declares, for every one of its entities, whether its records are about a person and what erasure does to them:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
dataSubjects: {
|
|
37
|
+
entry: { fields: ["authorId"], erase: { kind: "delete" } },
|
|
38
|
+
task: { fields: ["creatorId", "assigneeId"], erase: { kind: "anonymise", set: { creatorId: "erased", assigneeId: "erased" } } },
|
|
39
|
+
invoice: { fields: ["customerId"], erase: { kind: "retain", reason: "Invoices are kept for ten years under tax law" } },
|
|
40
|
+
rate: { none: "Exchange rates: about nobody" },
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`fields` hold the person's user id (a record is about everyone any of them names). Erasure is `delete`, `anonymise` (fixed values for named fields; every subject field must be among them, the primary key may not) or `retain` (with a reason, reported with the outcome). The entity needs exactly one organisation attribute. `deleteRecordsAbout(entities, overrides)` declares delete for every entity with user fields. The kernel's own modules declare theirs (settings, flags, inbox, notifications, consent, approvals and votes retained as evidence, sharing requests, the scheduler, the agent, devices, progress, privacy).
|
|
45
|
+
|
|
46
|
+
**Completeness is enforced**: with `privacyModule` installed, the kernel refuses to start an app in which **any entity is undeclared** (whatever its fields' types), an entity is declared without all of its user-typed fields (`Eloxiv::User` columns), or an entity is declared `{ none }` while a field is user-typed or named for a person (`userId`, `ownerId`, `author_id`, `createdBy`, `assignee`, `customer`, `recipient`...). And **setup refuses a table in a module's schema that is not one of its entities**: a module cannot keep records the declarations do not cover. So no module's records about a person can be left out by omission. `fields` are field names of the entity's Drizzle table (decision 9: the table is the only declaration of its fields). The kernel's modules and the registry's (`hello`, `notes`) declare every entity, so they install beside the privacy module (`registry/test/manifest.test.ts` checks the registry's).
|
|
47
|
+
|
|
48
|
+
**MAKE modules** ([Sandbox](sandbox.md#make)) declare theirs in the manifest's JSON form (`manifest.dataSubjects`, the same entries, by entity name), held to the same checks and the same completeness rule: with the privacy module installed, a draft, a preview and an install of a MAKE module any of whose entities is undeclared, half-declared or declared about nobody while a field holds a person's id are refused, saying so. MAKE's rule is stricter, since nothing about a MAKE manifest is trusted to name its fields well, and no name is guessed from: with the privacy module installed, **every field of a MAKE entity that could hold an identifier is classified explicitly**, among the declaration's `fields` (which hold every user-typed field) or in the entry's `notPersonal` list; an entity about nobody is `{ none: reason, notPersonal: [...] }` with every such field listed. Fields that could hold an identifier are its string, JSON (arrays and objects) and user-typed fields, except its primary key and its organisation; numbers, booleans, dates and times cannot (an identifier is a string). What a field is comes from **one source, its column's SQL type** (`storedKind`: text, varchar, char and uuid are strings; integers and other numbers; boolean; dates and times; json and jsonb), which setup holds the database to: its transport type, whether it is exempt, and how a request matches it all follow from it, a declared `type` that disagrees with its `sqlType` is refused (at draft, preview, install and upgrade), and a type MAKE does not store (an SQL array: a collection is `jsonb`) is refused. The refusal names each unclassified field, so a manifest is fixed in one step. A declared field may be a JSON array or object: a record names the person when the id is anywhere inside it (`eloxiv_guard.json_without`, kernel migration `0032_json_subjects`).
|
|
49
|
+
|
|
50
|
+
## Requests
|
|
51
|
+
|
|
52
|
+
`privacy.requestExport` and `privacy.requestErasure` are about yourself, or, with `eloxiv.privacy.manage` (which the built-in `admin` role grants), about a member of the organisation. A request is recorded (`eloxiv_privacy.request`), a Progress task is started for the requester, and the kernel's reaction to `privacy.requested` starts the kernel workflow `eloxiv.privacy-request`, as the organisation's system actor, with the request's id as its only input: who asked and about whom are read from the request record each time it runs, never journalled, so the engine's journal names nobody (the Progress task is still the requester's). It visits every source that takes part in its kind of request, **one journalled step per source in a transaction of its own, which also records the source as done** (`eloxiv.privacy_step`, keyed by request and source): a crash after a source committed, before the workflow journalled it, finds it done and repeats nothing, neither its effects nor its audit record. The sources, in order:
|
|
53
|
+
|
|
54
|
+
1. every installed module's declared entities (`<module>.<entity>`), as the module's system actor in the request's organisation (row-level security confines every statement to it): an export reads the records (`to_jsonb` of each row) its declaration exports, an erasure deletes, anonymises or counts them as declared; exports of other people that hold copies of records naming the person are deleted too (`privacy.exportCopies`); then the declared entities of the **MAKE modules installed in the organisation** (made at runtime, so found when the request starts; their names, never a person's, are journalled, so a restart visits the same ones), the same way: the kernel's statements, with the declaration's person-field predicates, run as the MAKE module's runtime role under its own row-level security (the only role that reaches its tables), never through its code. A MAKE module's schema keeps every column and table each installed version added (a rollback keeps them), so each of its tables is one source covering **every column any installed version declared personal**, and exporting every column any version exports: the current version's erasure applies (else the newest declaring version's), and an anonymisation without a value for a column another version declared deletes the record instead (fail closed). A MAKE anonymisation replaces the person only where they are: a declared field is set to its value where it is the person's id (others' ids in the record stay), and in a JSON field the declaration names as holding identifiers each occurrence of the id is replaced by the declared value, or removed from arrays when that value is `null` (an object entry keyed by the id is removed); every other field in `set` is set exactly as declared (`null` clears it, JSON content included). With the privacy module installed, a rollback to a version that lacks a table a later version created is refused before setup, saying which (every table of a module is an entity, so requests reach it). MAKE's drafts keep no one's data either: a preview stores only whether it passed (its calls' outputs, rows and events go back to the caller), and an erasure removes the sample rows of the person's drafts and installed versions, and of anyone's whose sample or (earlier) stored preview names them; an export holds the source and preview outcome of the drafts they made, and, of anyone's draft whose sample or stored preview names them, the sample rows naming them and that preview (never the draft's source);
|
|
55
|
+
2. further sources the kernel was given (`KernelOptions.privacySources`);
|
|
56
|
+
3. **every kernel store that can hold personal data**, from the inventory (below): each a source `eloxiv.<table>` that exports the person's rows (never credential material), deletes or scrubs them, and pseudonymises the person's id where they acted on someone else's rows. Among them: the person's Connections, revoked in custody and deleted with their sync state (a shared Connection they added is the organisation's: it stays, its adder pseudonymised, and only their own grants go), usage and cooldowns, consent flows and secrets (so two accounts at one provider go the same way); their agent sessions, API tokens, OAuth grants, codes and tokens, devices and pairings, linked identities, share grants and redemptions, idempotency records; every outbox event whose payload names them, delivered or not, replaced (`{"erased": true}`), with its failures' errors; **record history** (`eloxiv.history`): an export holds every version of every record about the person, deleted records included, and the person's other changes as metadata; an erasure purges every version about the person of every entity whose declaration does not retain the records, and replaces their id as the actor of the rest; **files and ingested content** ([Files](files.md), [Ingestion](ingestion.md)): an export holds the metadata of the files the person uploaded (never a storage key or the bytes) and the items they ingested; an erasure deletes the person's staged files (attached to no record; their bytes are purged by the files sweep after retention and any hold) and replaces their id as the uploader of attached files and the submitter of ingested items, which belong to their record: when the record's module deletes it, its files, search documents, chunks and items' text go in the same transaction (`eloxiv.track_record`), and when it keeps the record they stay with it; **collaborative documents** ([CollabDocument](collab-document.md#privacy)): an export holds the documents of the records about the person and their contributions to any document; a document goes with its record when the module deletes it, and stays with a kept record with the person's updates attributed to their pseudonym; **saved provider answers** (`eloxiv.effectAnswers`, erasure only): an external effect's provider answer (`eloxiv.connection_effect.result`: an event with its attendees) is its owner's, deleted with their effects, but can mention others; the kernel keeps it only while the scheduling module may need it ([Invocation, "External effects"](invocation.md#external-effects): until its callback ran, at once when it has none, at most `ELOXIV_EFFECT_ANSWER_RETENTION_DAYS`, default 7, when the callback was refused), and an erasure clears every answer in the organisation that mentions the person (their user id, their email as a whole token, their full name as whole words when it has two or more), whoever owns the effect, keeping the outcome with why (`result_cleared = 'erased'`; `registry/test/effects.test.ts`, "clears every saved answer that mentions an erased person, whoever owns the effect"); and the audit log (below);
|
|
57
|
+
4. **zero-cache's stores** (`eloxiv.syncChangeLog`, erasure only), when zero-cache keeps them in the app's database: its change log keeps every change it replicated until a backup lets it purge them, which a deployment without backups never does. The source waits until zero-cache has logged everything committed before it (the erasure's own changes included; at most 30 s, else the request fails and can be made again: it fails closed), then deletes the logged inserts and updates that name the person of rows in the organisation that no longer name them (deleted or anonymised since). Those are superseded by later changes, which the log or the replication slot holds, so no replica, however far behind, ends differently; changes of rows that still name the person (records retained) stay, as the rows do. It deletes the mutation results of the person's clients too. **The deployment grants the kernel's role** `USAGE` on zero-cache's shard schemas (`<app>_<shard>`, `<app>_<shard>/cdc`), `SELECT, DELETE` on `changeLog` and `mutations`, and `SELECT` on `clients`: without them an erasure fails rather than leave the log.
|
|
58
|
+
|
|
59
|
+
Each step writes an audit record (`eloxiv.privacy.export` or `eloxiv.privacy.erase`, invocation id the request's id, `detail` with the source, count, outcome and reason; an erasure's names the person by its pseudonym, and so does its actor when they asked for it themselves). Before each source, and before finishing, the workflow checks the Progress task: the requester's `progress.cancel` stops it there (sources already done stay done) and the request ends `cancelled`. A failure ends it `failed` with the failure's tag. The request's own Progress task is left alone by an erasure of its requester.
|
|
60
|
+
|
|
61
|
+
**The pseudonym** that replaces the person's id where a record of what they did is kept (`erased_<32 hex>`) is drawn at random for the request, the same for every record that request changes so its trail stays consistent, and held only while the request runs (`eloxiv.privacy_pseudonym`, deleted in the transaction that ends it): afterwards nothing links it to the person, it cannot be recomputed from their id, and two requests (in two organisations, say) never share one.
|
|
62
|
+
|
|
63
|
+
**The audit log keeps that something happened, never a personal payload**: on erasure, every audit record of the person's (and every record whose detail names them) loses its `detail`, and their id as the actor is replaced by the pseudonym. The privacy requests' own records keep their detail (ids and counts only), with the person as their subject replaced by the pseudonym too.
|
|
64
|
+
|
|
65
|
+
**Where a person's id remains** after they erased their data in an organisation they are still a member of, and why (the kit checks this list exactly, before they act again): the account (`auth.user`, `auth.account`, `auth.session`: deleting it is the operator's, across organisations); their membership, roles and groups, and the sync facts derived from them (offboarding is the administrators'); the request record itself (evidence it was made and carried out) and its Progress task (so they see it finish); records their modules retain by declaration; zero-cache's logged changes of those kept rows, and the account's zero clients' mutation counters; and workflow executions that run as them, which need their identity to resume (`eloxiv.workflow_execution.identity` and the engine's journal). Nothing names them next to their pseudonym.
|
|
66
|
+
|
|
67
|
+
**An export never holds other people's request contents**: the requests it holds are those about the person (ids and outcomes), whoever made them; export parts are never exported.
|
|
68
|
+
|
|
69
|
+
Requests are scoped to the organisation they are made in. Deleting the account itself (Better Auth's user and every membership) is the deployment operator's.
|
|
70
|
+
|
|
71
|
+
## The inventory of the kernel's stores
|
|
72
|
+
|
|
73
|
+
[`packages/kernel/src/privacy/Inventory.ts`](../../packages/kernel/src/privacy/Inventory.ts) (`KERNEL_STORES`) lists every table the kernel creates (its schemas, Better Auth's, the workflow engine's, every kernel-provided module's) with every column classified (`meta`, `subject`, `actor`, `personal`, `secret`) and a decision: `delete` or `scrub` the person's rows (with the SQL that finds them), leave it to the module's `dataSubjects` (`module`), `history`, `retain` with a reason, `transient` (gone within a transaction, an expiry or a retention window), `operator` (the account itself) or `none` (nothing personal); actor columns are pseudonymised; `export` says which of the person's rows and columns an export holds. [`packages/testing/test/kernel-inventory.test.ts`](../../packages/testing/test/kernel-inventory.test.ts) reads the database catalog of an app with every kernel-provided module and fails on any table or column not in the inventory (or in it but gone), on any store that can hold personal data without a decision or a reason, on any actor column left in place, on a module table not covered by its module's declarations, and on any export of credential material. So nothing that can hold personal data is added to the kernel without an erasure and export decision.
|
|
74
|
+
|
|
75
|
+
**zero-cache's client view records** (its CVR: the queries a person's replica ran, with their arguments, its desires and rows) of every client group the person used are deleted by the erasure at once (source `zero.cvr`, `privacy/ZeroCvr.ts`): the groups claimed for them (`eloxiv.sync_client_group`, kernel migration `0217_sync_client_groups`), each in its own shard's CVR schema (`<shard>/cvr`) and no other, in the app's database or the CVR's own (`ZERO_CVR_DB`, which the kernel reaches with `ELOXIV_ZERO_CVR_URL`). Whose group is whose comes from zero-cache, never from a client's word: a replica's queries are transformed when it connects, and every write is a push; the kernel records a group only from a transform or push carrying zero-cache's API key (`ELOXIV_ZERO_API_KEY`, zero-cache's `ZERO_QUERY_API_KEY` and `ZERO_MUTATE_API_KEY`; required in production, where the kernel refuses calls without one), which zero-cache makes for the group of the connection, whose replica holds the person's token, naming the group and the user the connection advertised (zero-cache's own word, a patch of it: `registry/app/patches`). A transform's claim commits under its session's hold, in the transaction that records the session's live fact, so a transform that resumes after a sign-out records nothing (`zero-cvr-erasure.test.ts`, "records no ownership for a transform that resumes after its session signed out"). So a replica's group is the person's from its first connection (one opened offline claims it once it connects), and the replica pushes nothing of its own: a push refused after a sign-out would make zero-cache drop the connection before the sign-out's withdrawal reached it ([Sync](sync.md), guarantee 8). A call whose credential is another person's than that user is refused before anything is recorded (zero-cache itself checks the user only on the answer). A group belongs to the first person and organisation it was claimed for; a push naming it as anyone else is refused, with the key or without, and a push without the key claims nothing, so erasing someone who named another's group never purges it. Queries are admitted the same way: a transform for a group another person claimed is refused, so a group's queries are only ever its owner's. Where the key is required (production, or whenever `ELOXIV_ZERO_API_KEY` is set), a push or transform without it, or with another, is refused before anything else ([`zero-api-key.test.ts`](../../packages/testing/test/zero-api-key.test.ts)). The records stay gone while the person's data changes, and zero-cache serves every other group on, open replicas and new ones ([`zero-cvr-erasure.test.ts`](../../packages/testing/test/zero-cvr-erasure.test.ts)). A replica of the purged group still open, or opened again from its storage, is answered by timing: served on while zero-cache's syncer still holds the group (which records what it syncs again), or refused as "client not found" (its cookie is ahead of the empty record; a browser then reloads into a new group). Either way it is the person's own replica and serves no one else's data; a person who stays a member and keeps the replica open has their later activity recorded again, as any new activity is. A replica opened without an organisation claims nothing, and leaves its group to zero-cache's own collection (a week of inactivity).
|
|
76
|
+
|
|
77
|
+
zero-cache's stores are in it too, under its app id and shard (`{app}`, `{app}_{shard}`, `{app}_{shard}/cdc`, `{app}_{shard}/cvr`), and the test runs zero-cache so the catalog holds them: its change log and its clients' mutation results (erased by the sync source above), its clients' mutation counters (retained with the account), its client view records (row keys and versions, queries and their arguments: transient, deleted with the client group by zero-cache's garbage collection once inactive, 168 hours by default) and its replication bookkeeping (nothing personal). Its SQLite replica is not a database store: it is rebuilt from the database when lost, and every deletion and anonymisation reaches it within the replication lag (the kit searches it).
|
|
78
|
+
|
|
79
|
+
Retained, with reasons stated there: memberships, roles and groups (offboarding is the administrators'), the durable execution journal (workflow inputs, signals, steps and engine messages, which carry ids; an event trigger's execution journals the event's id and type, never its payload, which the kernel reads from the outbox, where erasure reaches it, each time the work runs; a failed step's journal entry keeps its error tag, never its message; modules keep personal data out of workflow inputs, signals and step results), service principals and e-mail templates (the organisation's), registered OAuth clients, the suppression list (an unsubscribe outlives an erasure), approval requests and votes (evidence). Transient: invocation scratch tables, a running request's pseudonym, inbound deliveries (deleted at the end of the ingress retention window), authorisation requests and rate-limit counters.
|
|
80
|
+
|
|
81
|
+
## Operations
|
|
82
|
+
|
|
83
|
+
| Operation | Action | Input | Output | Who |
|
|
84
|
+
| --- | --- | --- | --- | --- |
|
|
85
|
+
| `getConsent` | `privacy.getConsent` (read-only) | `{}` | `ConsentState`: region, mode, per category `{ granted, source, decidedAt }` | yourself |
|
|
86
|
+
| `setConsent` | `privacy.setConsent` (audited with before and after) | `{ choices, region? }` | `ConsentState` | yourself |
|
|
87
|
+
| `allows` | in process | `{ userId, category }` | boolean | Telemetry |
|
|
88
|
+
| `requestExport` | `privacy.requestExport` | `{ subject? }` | `{ id, taskId }` | yourself; a member with `eloxiv.privacy.manage` |
|
|
89
|
+
| `requestErasure` | `privacy.requestErasure` (destructive: an agent's call needs consent) | `{ subject? }` | `{ id, taskId }` | as above |
|
|
90
|
+
| `requests` | `privacy.requests` (read-only) | `{}` | requests you made or that are about you | requester, subject |
|
|
91
|
+
| `download` | `privacy.download` (read-only) | `{ id }` | `DataExport`: `{ requestId, orgId, subjectId, generatedAt, sources: [{ source, records }] }` | requester, subject; `InvalidInput` otherwise, and while not finished |
|
|
92
|
+
| `visit` | `POST` and `GET /privacy/visit` (no session) | `VisitRequest` | `VisitState`: `consent`, `attribution` (`{ first, last }` or null), `claim` | the visitor |
|
|
93
|
+
| `claimVisit` | `POST /privacy/visit/claim` | `{ claim }` | `VisitClaimed`: the categories `carried`, the `attribution` | a person's own signed-in session; 403 for a visit someone else claimed |
|
|
94
|
+
|
|
95
|
+
## Sync
|
|
96
|
+
|
|
97
|
+
A person's replica holds their own consent choices and region in the organisation (`privacy.consent`, `privacy.region`, in `servicesQueries`); `consentFromReplica` applies them as the kernel does, given the deployment's mode.
|
|
98
|
+
|
|
99
|
+
## How an implementation is checked
|
|
100
|
+
|
|
101
|
+
`privacyConformance(start)` takes a `ServicesSubject` (see [Progress](progress.md#how-an-implementation-is-checked)) serving four fixture modules: `journal` (deleted, with record history and events naming the author, and a trigger whose work starts on each of them), `tasks` (anonymised; creator and assignee), `billing` (retained with a reason), `mailbox` (connector data, deleted), beside the kernel's settings, progress and privacy modules, a stand-in file store as the further source (proving the extension point; the kernel's own files are among the planted stores), and controls to plant data in the implementation's own stores (a secret, a second Connection with its sync state and a consent flow, a staged file and an attached one, an ingested item and the storage quota). It plants unique canary values for the person, for another person and for the person in another organisation. The kit checks: consent defaults, choices, regions by country and time zone, `necessary` not refusable, audit and sync to the person only; refusal of an undeclared or half-declared entity (one whose person's id is a plain string included, and one declared about nobody while a field holds a person's id), a retained record without a reason and an anonymisation that keeps the id, and setup's refusal of a table a module creates without declaring it; an export holding, per source, **exactly** the rows about the person (compared row for row with each table), the full history of a record since deleted, the Connections and secret names and never a credential, nothing about anyone else or another organisation, every visited source reported and audited, the Progress task at 100 percent; an administrator's own export never holding an export they made of someone else; only requester and subject reading, the permission for others, a non-member refused, an agent's erasure held for consent; cancellation through Progress stopping at the next source; and an erasure after which **a search of every table of the database finds none of the person's canaries** (records, a deleted record's history, a setting and its audit record, an event's payload, Connections, flows, sync state, secrets, files), nor does a search of zero-cache's replica (the reference runs zero-cache: its change log is among the tables searched), the person's id remains only in the stores listed above, the deleted record cannot be restored, what is retained is as declared, and the other person's and other organisation's canaries remain; a second erasure, in the other organisation, names the person by a different pseudonym, and no table holds a pseudonym next to the person's id. The Eloxiv kernel runs it in [`packages/testing/test/privacy.test.ts`](../../packages/testing/test/privacy.test.ts); [`privacy-restart.test.ts`](../../packages/testing/test/privacy-restart.test.ts) SIGKILLs a kernel between a source's commit and its journal entry and proves the source is not done again; [`kernel-inventory.test.ts`](../../packages/testing/test/kernel-inventory.test.ts) enforces the inventory; [`make-privacy.test.ts`](../../packages/testing/test/make-privacy.test.ts) installs a MAKE module with declared entities beside the privacy module, refuses a draft without declarations, and exports and erases the person's records of it (deleted and anonymised as declared), after which a search of every table finds none of the person's canaries while another person's remain.
|
|
102
|
+
|
|
103
|
+
## Not yet guaranteed
|
|
104
|
+
|
|
105
|
+
- **A file attached to someone else's record**, and content ingested into one, stays with that record when the person who uploaded it is erased (by a pseudonym): the record's module decides, as for the record itself. An export lists such files' metadata, not their bytes (the person downloads what they may read).
|
|
106
|
+
- **Backups** are outside the kernel: an erasure does not reach database backups, zero-cache's replica backups, or client replicas on devices (which lose the rows when they next sync). SQLite and PostgreSQL may keep a deleted row's bytes in free pages until they are reused or vacuumed.
|
|
107
|
+
- **A visitor's consent is per visit, not per organisation**: it is carried into the organisation the person claims it in (and again in any other they claim it in later); the cookie banner and the scripts' tags are the app's. A same-site page of another origin could send a visitor's choices for them (the route takes only JSON, so a cross-origin page needs the kernel's CORS approval); choices are a visitor's preferences, not a credential.
|
|
108
|
+
- **Records outside declared entities** (free text in other people's records that mentions the person, an event payload that holds their data without their id) cannot be found by id.
|
|
109
|
+
- **The durable execution journal** keeps workflow inputs, signals and step results as the work gave them (retained, with the reason in the inventory): the kernel puts no person's data there itself, but a module's own inputs and results are its responsibility.
|
|
110
|
+
- **Operator logs** (the kernel's stdout) are the operator's, outside the database: a step's or an action's failure is logged with its cause, which can carry what the work was about. They follow the deployment's log retention, not erasure.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Progress
|
|
2
|
+
|
|
3
|
+
Records of long-running work (workflows, ingestion, agent runs, imports, exports, erasures) that the person whose work it is follows live and can cancel (decisions.md "Kernel contracts"; the ledger's A-092, C-039).
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.0.0.
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/Progress.json`](../../packages/contracts/schema/contracts/Progress.json) (source [`Progress.ts`](../../packages/contracts/src/contracts/Progress.ts)).
|
|
7
|
+
- Implementation: the `Progress` service in [`packages/kernel/src/Progress.ts`](../../packages/kernel/src/Progress.ts); the kernel module `progressModule` ([`progress/module.ts`](../../packages/kernel/src/progress/module.ts)); the client's sync table in [`@eloxiv/client/sync`](../../packages/client/src/ServicesSync.ts) (`servicesTables`, query `progress.mine`).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/Progress` ([source](../../packages/testing/src/conformance/Progress.ts)).
|
|
9
|
+
|
|
10
|
+
## Records
|
|
11
|
+
|
|
12
|
+
A task (`ProgressTask`, table `eloxiv_progress.task`) has an owner (the person whose work it is), the organisation it was started in, a `kind` (`workflow`, `ingestion`, `agent-run`, `import`, `export`, `erasure`, `action`), the module that started it (`source`), a title, the current step and message, a percentage (or `null` while the work cannot tell) or a `done`/`total` count from which the percentage is derived, a `status` (`running`, `succeeded`, `failed`, `cancelled`), whether the owner asked to cancel, a redacted error, the workflow execution it reports for, and its times. Text is cut to 500 characters. A finished task never changes again.
|
|
13
|
+
|
|
14
|
+
## Reporting from work
|
|
15
|
+
|
|
16
|
+
**Handlers** use `ctx.progress`: `start({ title, kind?, step?, total?, notify? })` returns the task's id at once; `update(id, { step?, message?, percent?, done?, total? })`, `complete(id, message?)` and `fail(id, message)` are applied **when the call commits**, after its own writes are checked (a call that fails leaves no task). A task records the call that started it.
|
|
17
|
+
|
|
18
|
+
**Workflows** use `ctx.progress` too, where each report **commits at once**, so the owner's replica follows the work live: `start(name, start)` (keyed by the execution and the name, so a resumed execution continues the same task), `update` and `checkpoint` (each answers `{ cancelled, finished }`), `complete`, `fail`.
|
|
19
|
+
|
|
20
|
+
**Who may report on what.** Every write is confined to tasks of the work's own organisation, its own module and its own actor (the person, or the system actor for system work). A workflow's module is the module that declares it (its name must be `<module>.<name>`, and a module's triggers and ingress sources start only its own workflows), never what its name claims. One exception, bound by the kernel and nothing a module can name: a workflow **the emitting module's own trigger** started for an event may also report on the tasks the call that **emitted that event** started, in the same organisation and module. The hand-off is bound when the execution starts, from the event's outbox row (already committed), and journalled with it, so it holds under any load and across restarts. So a person's call starts a task and hands it to the background work it asked for (`journal.import` in the conformance app), and nothing else can: another module's trigger on the same event gets no hand-off, and a module emits only the events its manifest declares (`ctx.emit` of any other is refused), so it cannot pass off an event as another module's. A module's workflow body gets no kernel-only property on its context (no way to report as another identity, organisation or module). Writes run as the `progress` module's system actor in the task's organisation, under row-level security.
|
|
21
|
+
|
|
22
|
+
Without `progressModule` installed, reports are accepted and dropped: work never fails for want of a progress display.
|
|
23
|
+
|
|
24
|
+
**Telling the owner.** A task started with `notify: true` tells its owner when it ends: a notification (category `progress`, linked to the task, in-app and by their preferences) when it succeeds (its message) or fails (its error), once: only the report that ends the task sends it, in the same transaction (a workflow's) or with the call (a handler's). A cancellation, which the owner asked for, tells no one. `notify` is not synced. Delivery is the [Notifications](notifications.md) contract's: the in-app notification is durable, email goes through the outbox with retries.
|
|
25
|
+
|
|
26
|
+
## Cancellation
|
|
27
|
+
|
|
28
|
+
Cooperative. The owner calls `progress.cancel`; the task records the request (the work keeps running until it looks). A workflow's next `update` or `checkpoint` sees it: the task ends `cancelled` (with `finishedAt`), the report answers `{ cancelled: true }`, and the workflow returns. Nothing is recorded after that. Cancelling a finished task changes nothing. The kernel's own long work honours it (the privacy request workflow checks before each source; see [Privacy](privacy.md)).
|
|
29
|
+
|
|
30
|
+
## Operations
|
|
31
|
+
|
|
32
|
+
| Operation | Action | Input | Output | Who |
|
|
33
|
+
| --- | --- | --- | --- | --- |
|
|
34
|
+
| `list` | `progress.list` (read-only, rendered as a table) | `{ active?, limit? }` | `{ tasks }`, newest first | the owner (their own tasks in the organisation) |
|
|
35
|
+
| `get` | `progress.get` (read-only) | `{ id }` | the task | the owner; anyone else gets `InvalidInput` (the two are not told apart) |
|
|
36
|
+
| `cancel` | `progress.cancel` (audited with `{ task, status, cancelRequested }`) | `{ id }` | `{ id, cancelRequested }` | the owner; others `Forbidden` |
|
|
37
|
+
| `remove` | `progress.remove` | `{ id }` | `{ id }` | the owner, finished tasks only (`InvalidInput` for a running one) |
|
|
38
|
+
| `start`, `update`, `checkpoint`, `complete`, `fail` | in process (`ctx.progress`) | as above | | the work |
|
|
39
|
+
|
|
40
|
+
## Sync
|
|
41
|
+
|
|
42
|
+
Each person's replica holds their own tasks in the organisation they act in (`progress.mine`, newest first, at most 200), by the module's read policy (`resource.owner == principal`). Add `servicesTables` and `servicesQueries` from `@eloxiv/client/sync` to the app's sync configuration (the tables are generated from the module's Drizzle table; the kernel infers each query's entity from the table it reads).
|
|
43
|
+
|
|
44
|
+
## How an implementation is checked
|
|
45
|
+
|
|
46
|
+
`progressConformance(start)` takes a `ServicesSubject` ([`ServicesSubject.ts`](../../packages/testing/src/conformance/ServicesSubject.ts)): a running kernel serving the **platform-services conformance app** ([`studio/app.ts`](../../packages/testing/src/conformance/studio/app.ts)), whose `journal.import` starts a task and hands it to an event-started workflow that reports one entry at a time, and whose `journal.forge` starts a workflow that tries to report on other people's tasks. The kit checks: the task is the caller's, appears when the call commits, is in their replica and nobody else's, and a failed call leaves none; reports are live and the task ends at 100 percent; a cancelled import stops at its next report, ends `cancelled` and never changes again, audited; only the owner reads, cancels and removes, and a running task cannot be removed; a module's background work cannot touch a task in another organisation and module (through any property of its context) nor another person's task in its own module; a finished task never changes. The Eloxiv kernel runs it in [`packages/testing/test/progress.test.ts`](../../packages/testing/test/progress.test.ts); [`workflow-ownership.test.ts`](../../packages/testing/test/workflow-ownership.test.ts) proves the ownership rules: a workflow named outside its module, and a trigger starting another module's workflow, are refused at start; sixty imports started at once all hand their tasks over and finish; another module's trigger on the same event cannot touch the task; an event the emitting module does not declare is refused; a failed step's journal entry keeps its tag, never its message.
|
|
47
|
+
|
|
48
|
+
## Not yet guaranteed
|
|
49
|
+
|
|
50
|
+
- **The kernel's own agent runs and connection syncs do not report through Progress yet**; the kinds exist (`agent-run`, `ingestion`) and the privacy requests do.
|
|
51
|
+
- **No forced stop.** A workflow that never reports or checkpoints runs to its end; cancellation is cooperative.
|
|
52
|
+
- **Retention.** Finished tasks stay until their owner removes them (or a privacy erasure).
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# QuerySurface
|
|
2
|
+
|
|
3
|
+
Read-only SQL for the agent, and for any authorised client, over the published query views of installed modules (decision 6). Each row is filtered by its entity's read policy for the caller, exactly as sync filters it. Every write goes through actions.
|
|
4
|
+
|
|
5
|
+
- Kind: kernel service. Version 1.0.0.
|
|
6
|
+
- Schema: [`packages/contracts/schema/contracts/QuerySurface.json`](../../packages/contracts/schema/contracts/QuerySurface.json) (source [`QuerySurface.ts`](../../packages/contracts/src/contracts/QuerySurface.ts)).
|
|
7
|
+
- Implementation: the `QuerySurface` service in [`packages/kernel/src/QuerySurface.ts`](../../packages/kernel/src/QuerySurface.ts); the kernel module `queryModule` ([`query/module.ts`](../../packages/kernel/src/query/module.ts)); the surface's views and read role in [`db/Bootstrap.ts`](../../packages/kernel/src/db/Bootstrap.ts) (`publishSurfaceViews`, `QUERY_ROLE`); the shared tree checks in [`db/QueryViewCheck.ts`](../../packages/kernel/src/db/QueryViewCheck.ts).
|
|
8
|
+
- Kit: `@eloxiv/testing/conformance/QuerySurface` ([source](../../packages/testing/src/conformance/QuerySurface.ts)).
|
|
9
|
+
|
|
10
|
+
## Installing it
|
|
11
|
+
|
|
12
|
+
Add the kernel's `queryModule` to the app's modules. It owns no tables; its two actions are served by the kernel:
|
|
13
|
+
|
|
14
|
+
| Action | MCP and agent tool | Input | Output |
|
|
15
|
+
| --- | --- | --- | --- |
|
|
16
|
+
| `eloxiv.query` | `eloxiv_query` | `QueryRequest`: `sql`, optional `limit` (1 to 1000) | `QueryResult` |
|
|
17
|
+
| `eloxiv.queryViews` | `eloxiv_queryViews` | `{}` | `QueryViews` |
|
|
18
|
+
|
|
19
|
+
Both are hinted read-only and are open to every member of the organisation the caller acts in; what a query returns is what the views' read policies give the caller. Being actions, they are on every surface (typed client, HTTP, MCP, agent tools, the CLI) through the one invocation path ([Invocation](invocation.md)): identity, the credential's scope, policy, audit.
|
|
20
|
+
|
|
21
|
+
## Operations
|
|
22
|
+
|
|
23
|
+
### `query`
|
|
24
|
+
|
|
25
|
+
Run one read-only `SELECT` over the query surface for the caller.
|
|
26
|
+
|
|
27
|
+
A published query view `<module>.<view>` is the relation `<module>_<view>` on the surface (`hello.greetings` is `hello_greetings`), named unqualified. Joins across modules' views, CTEs, subqueries, `VALUES`, aggregates, window functions, `DISTINCT`, `GROUP BY`, `ORDER BY`, `LIMIT` and the built-in side-effect-free functions are allowed.
|
|
28
|
+
|
|
29
|
+
Output `QueryResult`:
|
|
30
|
+
|
|
31
|
+
| Field | Meaning |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| `columns` | `{ name, type }` in order; `type` is Postgres's (`format_type`), for example `text`, `integer`, `bigint`, `timestamp with time zone` |
|
|
34
|
+
| `rows` | one JSON object per row, keyed by column name, values as Postgres's `to_json` renders each built-in type: numbers (including `bigint` and `numeric`, so values beyond 2^53 lose precision in JavaScript) as JSON numbers, timestamps as ISO 8601 text, JSON as JSON |
|
|
35
|
+
| `rowCount` | rows returned |
|
|
36
|
+
| `truncated` | more rows matched than `limit` (default 1000) |
|
|
37
|
+
| `views` | the published views (`<module>.<view>`) the query read |
|
|
38
|
+
|
|
39
|
+
Output column names must be unique (alias them: `SELECT a.id AS a_id, b.id AS b_id`), since rows are objects. Every output column must be of a built-in base type (the type allowlist: `bool`, the text, integer, `numeric`, float, date and time, `interval`, `uuid`, `json`, `jsonb` and `bytea` types, and arrays of them): a column of a module's enum, a row or a composite is refused, so convert it (`visibility::text`, or select the row's fields).
|
|
40
|
+
|
|
41
|
+
Errors: `InvalidInput` when the query is refused (the message says why); `ActionFailed` when it fails while running (a statement timeout: "The query ran longer than 5000 ms"; a division by zero; a [limit](#limits) reached: the result's or one value's size, temporary file space, too many queries at once); `Unauthenticated` and `Forbidden` from the invocation path.
|
|
42
|
+
|
|
43
|
+
### `describe`
|
|
44
|
+
|
|
45
|
+
The surface's views (`eloxiv.queryViews`, the agent's `\d`): for each, `name` (the relation to query), `id`, `module`, `description`, `entity` (whose read policy filters it) and `columns`, each with its Postgres `type`, its `description` from the view's declared row (a field annotated `description`), and its JSON Schema.
|
|
46
|
+
|
|
47
|
+
## How a query is verified
|
|
48
|
+
|
|
49
|
+
Two real parsers check a query before any row is read; both must accept it.
|
|
50
|
+
|
|
51
|
+
1. **Postgres's grammar.** [libpg-query](https://github.com/pganalyze/libpg-query-node) (Postgres 17's parser compiled to WebAssembly, pinned to `17.8.2`, runs on Bun and Node) parses the text. It must be exactly one statement, a `SELECT` with no `INTO`, no row locking and no recursive CTE. Every node must be of a kind on an allowlist (selects, targets, column references, constants, expressions, function calls, casts, relations, subqueries, joins, CTEs, sorting, windows, `CASE`, `COALESCE`, `NULLIF`, row and array constructors, date and time keywords), which leaves out XML, SQL/JSON, table sampling, functions in `FROM`, parameters, `CURRENT_USER` and the like. Relations and columns may not be schema-qualified; functions may be qualified only by `pg_catalog` and must be on the built-in allowlist; casts must be to a type on the type allowlist; operators may not be qualified.
|
|
52
|
+
2. **Postgres's analysed tree.** The statement, exactly as the grammar delimited it, becomes a temporary view, created as the read role with the search path `eloxiv_surface, pg_catalog, pg_temp`. Postgres resolves every name in it to an object; the view's stored tree (`pg_rewrite`) is then checked as published views are ([ModuleManifest](module-manifest.md)): every relation must be a view of the query surface (system catalogs, `information_schema` and everything else are refused even when they resolve), every function called, operator, support function and coercion must be an allowlisted immutable or stable `pg_catalog` built-in, no function may return a set, and every constant must be of an allowed type (so `'pg_authid'::regclass` is refused although Postgres converts it while parsing), and every argument of a function that encodes its arguments as JSON or text (`to_json`, `to_jsonb`, `row_to_json`, `array_to_json`, the `json_build_*` and `jsonb_build_*` functions, `json_agg`, `jsonb_agg`, `json_object_agg`, `jsonb_object_agg`, `quote_literal`, `quote_nullable`, `concat`, `concat_ws`, `format`, `string_agg`) must be of a built-in base type (its type read from the analysed tree, as a direct value, an aggregate's, a row, an array or a subquery's). The view's output columns must be built-in base types too.
|
|
53
|
+
|
|
54
|
+
Why the last two: Postgres's JSON functions convert a value of a type outside the built-in range with that type's cast to `json` if one exists (`quote_literal(anyelement)` with its cast to `text`), and they call the cast's function without an EXECUTE check, outside every tree check. A module that owns an enum could `CREATE CAST (its_enum AS json) WITH FUNCTION its_function(...)` and have the read role run it for anyone who reads the column. So no such value reaches an encoding function, in the query or in the kernel's own encoding of the result. Setup also refuses module-defined casts and types with custom I/O (the published-view and manifest checks); the surface's own check does not rely on that.
|
|
55
|
+
|
|
56
|
+
Then that same temporary view, not the text again, is read: in a read-only scope (`transaction_read_only`), as the read role, with the [limits](#limits) below, at most `limit + 1` rows. The kernel encodes the rows itself, in that same statement: each column with `to_json` (of a built-in base type, so no one's cast runs), each row as a JSON array of its values, measured as the rows stream. The whole transaction runs on the surface's own connection pool and is always rolled back.
|
|
57
|
+
|
|
58
|
+
## Limits
|
|
59
|
+
|
|
60
|
+
| Limit | Setting (`KernelConfig.query`, environment) | Default | When reached |
|
|
61
|
+
| --- | --- | --- | --- |
|
|
62
|
+
| Running time of each statement | `timeoutMs`, `ELOXIV_QUERY_TIMEOUT_MS` | 5000 ms | `ActionFailed`: "The query ran longer than 5000 ms" |
|
|
63
|
+
| Rows | the request's `limit` (1 to 1000) | 1000 | `truncated: true` |
|
|
64
|
+
| Bytes of the whole result, as JSON | `maxResultBytes`, `ELOXIV_QUERY_MAX_BYTES` | 4 MiB | `ActionFailed`: "The query's result is larger than ... bytes" |
|
|
65
|
+
| Bytes of one value (one column of one row), as JSON | `maxValueBytes`, `ELOXIV_QUERY_MAX_VALUE_BYTES` | 1 MiB | `ActionFailed`: "A value in the query's result is larger than ... bytes" |
|
|
66
|
+
| Memory per sort or hash (`work_mem`) | `workMemKb`, `ELOXIV_QUERY_WORK_MEM_KB` | 4096 kB | spills to temporary files |
|
|
67
|
+
| Temporary file space (`temp_file_limit`) | `tempFileLimitKb`, `ELOXIV_QUERY_TEMP_FILE_LIMIT_KB` | 65536 kB | `ActionFailed`: "The query needed more temporary file space than its limit" |
|
|
68
|
+
| Queries at once, in all | `connections`, `ELOXIV_QUERY_CONNECTIONS` | 4 | `ActionFailed`: "The query surface is busy" |
|
|
69
|
+
| Queries at once, per person | `perActor`, `ELOXIV_QUERY_PER_ACTOR` | 2 | `ActionFailed`: "You already have 2 queries running" |
|
|
70
|
+
|
|
71
|
+
- **Size is measured in Postgres, and the read stops at the limit.** A running sum of the encoded rows' sizes (a window over the rows in order) and each row's largest value are checked as each row is produced; the first row over either limit ends the statement with an error, so the kernel never receives much more than `maxResultBytes`, and a refused result is refused whole (no partial rows).
|
|
72
|
+
- **The statement settings are the transaction's own** (`SET LOCAL statement_timeout`, `work_mem` and `temp_file_limit`), set by the kernel before it switches to the read role; setup grants the kernel role `SET` on `temp_file_limit`, which only a superuser may otherwise set. (On a managed Postgres whose administrator may not grant it, setup warns and the surface runs without that one limit, warning once.) (A per-role setting on `eloxiv_query` would not apply: Postgres applies role settings at login, and the kernel reaches the role with `SET ROLE`.)
|
|
73
|
+
- **A query never holds a connection of the kernel's pool while it waits.** The invocation that runs a query holds a connection of the kernel's pool for the length of its transaction. The surface admits at most `connections` queries at once, as many as its own pool has for them, and refuses the rest at once instead of queuing them, so a burst of slow queries holds at most `connections` of the kernel's connections, each for at most the timeout, and every other invocation goes on. The counts are per kernel process.
|
|
74
|
+
- **What a limit does not bound.** One built-in function call can still allocate up to Postgres's own limit for one value (about 1 GB, `repeat('x', 1000000000)`) before the value check sees it; the timeout, `work_mem`, the temporary file limit and the number of queries at once bound how long and how many.
|
|
75
|
+
|
|
76
|
+
## How the policy applies
|
|
77
|
+
|
|
78
|
+
Setup creates schema `eloxiv_surface` (owned by the superuser that runs setup, no access for `PUBLIC`) and in it one view per published query view, with the view's own SQL, as a `security_barrier` view that is **not** `security_invoker` and is owned by the module's runtime role. Reading it reads the module's tables as the runtime role, so the tables' row-level security applies: the entity's compiled read policy ([Sync](sync.md) and [Invocation](invocation.md) use the same compilation) for the user and organisation the query's transaction records in its invocation context, with the action `eloxiv.query`, which no module's policy names, so nothing but the read policy admits a row. Being a security barrier, the caller's own predicates cannot run on a row before the policy has admitted it.
|
|
79
|
+
|
|
80
|
+
The read role `eloxiv_query` (NOLOGIN, NOBYPASSRLS, NOINHERIT; the kernel may `SET ROLE` to it and inherits nothing) has `USAGE` on `eloxiv_surface`, `SELECT` on its views, `TEMPORARY` on the database and `EXECUTE` on the invocation-context functions row-level security calls. It has no privilege on any module schema, the kernel's schemas or Better Auth's. Each surface view is checked at setup like the module's own published view (the same allowlist, the module's own tables only); setup drops the surface's views before module migrations and creates them again after hardening.
|
|
81
|
+
|
|
82
|
+
## Records
|
|
83
|
+
|
|
84
|
+
`QueryRequest`, `QueryResult`, `QueryColumn`, `QueryViews`, `QueryViewDescription`, `QueryViewColumn`, `QueryAuditDetail`, all in the published schema's `types`.
|
|
85
|
+
|
|
86
|
+
## Guarantees
|
|
87
|
+
|
|
88
|
+
1. **Only published views.** A query reads nothing but the query surface's views: not a base table, not another module's tables, not the kernel's or Better Auth's tables, not a system catalog, whatever quoting, qualification, CTE, subquery, `LATERAL`, comment or statement separator it uses. The read role could not read them anyway; the analysed-tree check refuses them before anything runs.
|
|
89
|
+
2. **Only allowlisted built-ins.** Nothing outside the allowlist is called: no `pg_catalog` function off the list (`set_config`, `current_setting`, `query_to_xml`, `pg_read_file`, `pg_sleep`, `lo_*`, `dblink`, ...), no module or extension function, no cast that calls a function outside it (`regclass`, `regproc`, `xml`, or a module's cast named in the query), no set-returning function, and no type's own cast to `json` or `text` reached through a JSON or text-encoding function or the result's encoding (every value they encode is of a built-in base type).
|
|
90
|
+
3. **Exactly the caller's rows.** Each row is admitted by its entity's read policy for the caller in the organisation they act in: the same query gives each person exactly the rows their replica syncs.
|
|
91
|
+
4. **Read-only and bounded.** The query runs where Postgres refuses every write, under the [limits](#limits): a statement timeout, a row limit, the size of the result and of each value (measured in Postgres, stopping there), `work_mem` and temporary file space, and how many queries run at once, in all and per person, without ever holding a connection of the kernel's pool while it waits; its transaction is rolled back, so even the temporary view it was checked as does not survive.
|
|
92
|
+
5. **Audited.** Every call has one audit record ([Audit](audit.md)) whose `detail` is `QueryAuditDetail`: `queryHash` (sha256 of the query text), `views`, `rowCount`, `truncated`, and for a refusal `refused` (why). The query text itself is not stored.
|
|
93
|
+
6. **One path.** The query is an action: every surface gives the same result and the same refusal.
|
|
94
|
+
|
|
95
|
+
## How an implementation is checked
|
|
96
|
+
|
|
97
|
+
`querySurfaceConformance(start)` takes a `PlatformSubject` ([`PlatformSubject.ts`](../../packages/testing/src/conformance/PlatformSubject.ts)): a running kernel serving the **platform conformance app** ([`crm/app.ts`](../../packages/testing/src/conformance/crm/app.ts)). Its `crm` module publishes `crm.deals` (deals readable by the organisation unless private, and their owner), keeps a table no view publishes (`crm.note`) and a function of its own (`crm.shout`); its `team` module publishes `team.members`. The subject runs queries with a 1.5 s statement timeout.
|
|
98
|
+
|
|
99
|
+
The kit checks: typed columns and rows; each of three people (two organisations) getting exactly the rows the sync endpoint's scoped query selects for them; joins across modules, CTEs, subqueries, aggregates and window functions, each view filtered; the row limit and truncation; the statement timeout; the audit record of a query and of a refusal; the same answer and refusal on the internal path, RPC, HTTP, MCP and agent tools, and `eloxiv.queryViews` on three of them; an unauthenticated caller refused; and **every adversarial query refused** (`ADVERSARIAL` in the kit, 115 queries in twelve groups: base tables, quoted identifiers, schema qualification, system catalogs, CTEs, subqueries, `pg_catalog` and other functions, casts that call functions, set-returning functions, multiple statements, comment tricks, and `COPY`, `DO`, `SET` and every other statement kind), after which every table is unchanged and no temporary view survives.
|
|
100
|
+
|
|
101
|
+
The Eloxiv kernel runs it in [`packages/testing/test/query-surface.test.ts`](../../packages/testing/test/query-surface.test.ts) against [`PlatformReference.ts`](../../packages/testing/src/conformance/PlatformReference.ts). Its own limits and its encoding are proven in [`query-surface-limits.test.ts`](../../packages/testing/test/query-surface-limits.test.ts) (the result's and one value's size, temporary file space, queries per person, and an ordinary write going through while sixteen slow queries run) and [`query-surface-casts.test.ts`](../../packages/testing/test/query-surface-casts.test.ts) (a module enum with casts to `json` and `text` whose functions raise: every output column and encoding-function argument of it refused, in nineteen shapes, and no cast ever run).
|
|
102
|
+
|
|
103
|
+
## Not yet guaranteed
|
|
104
|
+
|
|
105
|
+
- **Precision of large numbers**: `bigint` and `numeric` values are JSON numbers; beyond 2^53 a JavaScript client loses precision.
|
|
106
|
+
- **Aggregate views**: a published view must return its entity's primary key (so its rows can be filtered), so aggregates are written in queries, over row views.
|
|
107
|
+
- **Cost**: the [limits](#limits) bound each query and how many run at once; there is no per-caller budget over time yet (Metering), and the counts of running queries are per kernel process, not per deployment.
|
|
108
|
+
- **Rows as values**: a whole row (`SELECT d FROM crm_deals d`, `row_to_json(d)`) or an enum is refused rather than encoded; select its fields, or convert it to text.
|