Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 41 minutes ago History
doc_pages.tsv · 799.2 KB · 10613 lines
1id title category nav_order summary content
2why Why DBBASIC — The Advantages, Honestly Stated Start Here 100 A plain-spoken case for DBBASIC's design — live changes, apps as data, one permission engine — with its current boundaries stated just as plainly. "DBBASIC is a small server with strong opinions. This page states the
3advantages plainly, and the boundaries next to them, because a claim
4without its boundary is marketing.
5
6## Change is live
7
8Objects load per execution: edit an object and the next request serves
9the new code. Schemas, permission rules, routes, and site pages are
10data, changed over HTTP. Only changes to the server file itself need a
11restart (seconds). There is no build, no deploy pipeline, no migration
12ceremony.
13
14Safety comes from **reversibility instead of ceremony**: object source
15is versioned with rollback, schemas keep history, records keep
16changelogs, permission changes and admin actions are audited. Ship in
17steps of one; undo in steps of one.
18
19## Apps are data
20
21An application is a package: schema + permission rules + optionally one
22page object ([the app suite](/docs/app-packages)). The server grows only
23when a genuinely new *kind* of capability appears — search, sharing,
24file storage, AI — and each lands once, generically, then every app
25uses it by declaring so in its schema.
26
27The consequence: **capability grows with data, not code.** Add a
28schema for any obscure domain and it immediately has validated writes,
29generated forms, search, sharing, MCP tools, and AI conversation about
30it. Nobody ships function-calling for your beekeeping records; here it
31is free.
32
33## One permission engine, every surface
34
35Browser pages, the records API, MCP agents, global search, file
36downloads, and AI tool calls all pass the same policy: role rules, row
37filters (`$user_id`, `$accessible_projects`, `$owned_projects`), field
38redaction, audit. A rule written once binds everywhere — no surface can
39leak what another surface hides. Sharing is records (`project_access`
40rows), so granting and revoking are audited record writes.
41
42## Fast because it does less
43
44A request here is: a dict-router match, a TSV read the OS page cache
45already holds, permission string-checks, JSON out. No ORM, no
46connection pool, no query planner, no middleware stack, no signal
47cascade. At personal-and-team data sizes (thousands of rows per
48collection), scanning a hot file in-process beats an indexed query
49across a socket.
50
51**Boundary:** this inverts somewhere past hundreds of thousands of rows
52in one collection. Collections are per-file, so a hot one can gain an
53index later without changing the platform; the search contract promises
54no ranking, so an index can slot in behind it.
55
56## AI-native without AI lock-in
57
58The whole admin surface is MCP; agents operate the server with their
59own identities and audited sessions. Users store their own provider
60keys (write-only), pick their own models, and hand the AI a chosen
61subset of tools ([the shell](/docs/shell-and-ai)). The server never meters
62your tokens or requires a vendor. An AI acting for a user is exactly as
63powerful as the user — no more.
64
65## Yours
66
67Stdlib-only Python plus uvicorn; one VM; data in human-readable TSV and
68JSON files you can grep, back up, and take elsewhere. Small enough for
69one person to read. MIT licensed, with the operator console
70(Scroll) open source
71too. Multi-domain hosting means one instance serves many sites with one
72identity store and one audit trail.
73
74## Current boundaries, plainly
75
76- One VM; no cluster correctness claims.
77- Realtime push is live over one permission-filtered websocket (`/ws`);
78 the durable event log remains as the poll fallback.
79- A background-job runtime exists (`app-runner`, plus the daemon's
80 scheduler and queue); what it lacks is handlers for long media work
81 such as PDF extraction and thumbnails.
82- Untrusted arbitrary code execution is not offered; object writes are
83 operator/admin actions, and the worker pool isolates processes without
84 CPU or memory limits.
85- Self-service signup and password reset exist, off by default; signup
86 refuses to turn on until enforcement is on and no rule gives every
87 signed-in user unscoped access. Strangers still cannot run their own code.
88- Permission enforcement is opt-in per deployment rather than the shipped
89 default (staging runs with it on).
90
91The direction on each is recorded in status. The rule for
92new capability is unchanged: it must pass the same permission engine,
93audit trail, and reversibility bar as everything before it.
94"
95quickstart Quickstart — From a Fresh VM to Your First App Start Here 110 A linear, thirty-minute path from a bare Debian/Ubuntu VM to a running DBBASIC Object Server with login, HTTPS, and your first app installed. "This is the linear path: a bare Debian/Ubuntu VM to a running object
96server, a login, a public domain, and a first app installed — in one
97sitting, about thirty minutes, most of it waiting on `apt`. Every step
98is a real command you can paste.
99
100For the full reference (systemd hardening, journald caps, backups,
101permission rollout, per-route proxy allowlists), see
102[single-vm deployment](/docs/single-vm-deployment). This page is the happy
103path; that one is the operator's manual.
104
105```mermaid
106flowchart LR
107 A[""Fresh VM<br/>+ a domain""] --> B[""Run the installer""]
108 B --> C[""Create your admin user<br/>+ enable login""]
109 C --> D[""Caddy: domain + TLS""]
110 D --> E[""Enable package installs""]
111 E --> F[""Install an app<br/>→ live at /notes""]
112```
113
114## 0. What you need
115
116- A small VM (a $5–$7 droplet is plenty) running Debian 12 or Ubuntu
117 22.04+, with root or `sudo`.
118- Optional but recommended: a domain name with an `A` record pointing at
119 the VM's IP, so Caddy can get you automatic HTTPS.
120
121## One-click installs
122
123An installer such as GitStable's ""Install on DigitalOcean"" runs
124`scripts/one-click-install.sh <release>` through the server's cloud-init
125(`cloud-init.yaml`, `DBBASIC.md`). It does steps 1 to 3 below for you, installs
126the apps to start with (home and menu, projects, notes, tasks,
127files), with two
128differences: HTTPS comes on the server's bare IP address (a Let's
129Encrypt IP certificate) until you add a domain, and no admin is created.
130Its permission policy is the rules those apps ship, enforced from the first start.
131The server answers only `/health` and `/setup` until you open `/setup` with
132the one-time setup code the installer showed you and choose your own email
133and password (`object_setup.py` says why it works that way). Lost the code?
134SSH in and do step 2: once an admin exists, setup is over.
135
136## 1. Run the installer
137
138`--version 2026.11v1` installs that release instead of the newest `main`,
139and `/health` then names the release and commit.
140
141
142The installer is a readable script — download it, read it, run it. It
143installs dependencies, creates the service user and layout, builds a
144virtualenv, generates an admin token, and starts a systemd service on
145`127.0.0.1:8001`. It is idempotent, so re-running it is safe.
146
147```bash
148git clone <repository-url> dbbasic-object-server
149cd dbbasic-object-server
150less scripts/install.sh # read it first
151sudo bash scripts/install.sh
152```
153
154When it finishes you have a running server. Confirm:
155
156```bash
157curl http://127.0.0.1:8001/health
158```
159
160Your admin token lives in `/etc/dbbasic-object-server.env` as
161`DBBASIC_ADMIN_TOKEN` (readable by root and the service group only).
162Everything the installer did on purpose *not* to do — login, a public
163domain, app installs — is below, as short deliberate steps.
164
165## 2. Create your admin user and turn on login
166
167```bash
168cd /opt/dbbasic-object-server
169sudo -u dbbasic DBBASIC_DATA_DIR=/var/lib/dbbasic-object-server/data \
170 .venv/bin/python object_identity_cli.py create-superuser \
171 --user-id you --email you@example.com
172```
173
174It prompts for a password twice (no echo) and stores only a scrypt hash
175under the runtime data directory. Now enable password login and restart:
176
177```bash
178sudo sed -i 's/^DBBASIC_ENABLE_PASSWORD_LOGIN=false/DBBASIC_ENABLE_PASSWORD_LOGIN=true/' \
179 /etc/dbbasic-object-server.env
180sudo systemctl restart dbbasic-object-server
181```
182
183## 3. Put a domain and HTTPS in front
184
185Keep uvicorn bound to localhost and let Caddy terminate TLS. If a domain
186points at the VM, this is all it takes:
187
188```bash
189sudo apt install -y caddy
190sudo tee /etc/caddy/Caddyfile >/dev/null <<'EOF'
191your-domain.com {
192 handle / {
193 rewrite * /objects/site_home
194 reverse_proxy 127.0.0.1:8001
195 }
196 handle {
197 reverse_proxy 127.0.0.1:8001
198 }
199}
200EOF
201sudo systemctl reload caddy
202```
203
204Caddy fetches a certificate automatically. Visit `https://your-domain.com`
205— you should see the home object, and `https://your-domain.com/login`
206should accept the user you just created.
207
208> The catch-all `handle` above proxies every path to the server, which
209> relies on the permission policy as the gate. For a locked-down public
210> staging box that instead exposes only named routes, use the per-route
211> allowlist in [single-vm deployment](/docs/single-vm-deployment#https-proxy).
212
213## 4. Enable app installs and install your first app
214
215Apps are packages that ship in the repo under `packages/`. Turn on
216installs, then ask the server to install one. (Installs are gated by the
217admin token, so this stays an operator action.)
218
219```bash
220sudo sed -i 's/^DBBASIC_ENABLE_PACKAGE_INSTALLS=false/DBBASIC_ENABLE_PACKAGE_INSTALLS=true/' \
221 /etc/dbbasic-object-server.env
222sudo systemctl restart dbbasic-object-server
223
224TOKEN=$(sudo grep -oP 'DBBASIC_ADMIN_TOKEN=\K.*' /etc/dbbasic-object-server.env)
225
226# Projects is the hub other apps relate to; install it first, then notes.
227for app in app-projects app-notes; do
228 curl -s -X POST http://127.0.0.1:8001/packages/$app/install \
229 -H ""Authorization: Token $TOKEN"" -H 'Content-Type: application/json' -d '{}'
230 echo
231done
232```
233
234`app-notes` includes a page object. To turn permission enforcement on so
235each user sees only their own notes, follow the audit-then-enforce
236rollout in [permissions](/docs/permissions-model#route-enforcement); on a
237single-operator box you can leave it open to start.
238
239Visit `https://your-domain.com/notes`, sign in, and you have a working
240notes app — quick capture, projects, search, public sharing — that you
241never wrote a line of server code for. Browse
242[the app suite](/docs/app-packages) for the rest (tasks, contacts,
243articles, calendar, files, the shell) and install the ones you want.
244
245## 5. Optional: the talk-to-everything shell
246
247Install `app-shell`, then store an AI provider key and chat with your
248data — see [the shell and AI guide](/docs/shell-and-ai). Storing a key is
249one command in the shell (`/key anthropic sk-...`), and the AI operates
250the server with your permissions.
251
252## What to do next
253
254- **Back it up.** All state is files under
255 `/var/lib/dbbasic-object-server/data`; see [backup and restore](/docs/backup-restore).
256- **Harden it.** systemd sandboxing, journald caps, and the readiness
257 gates are in [single-vm deployment](/docs/single-vm-deployment).
258- **Understand the model.** [Why DBBASIC](/docs/why) and
259 [comparisons](/docs/comparisons) explain what you are and are not
260 signing up for.
261- **Build.** Copy `app-notes` to make your own app
262 ([package authoring](/docs/package-authoring)), or add a system-tool
263 object ([capability objects](/docs/capability-objects)).
264
265## Upgrading later
266
267```bash
268cd /opt/dbbasic-object-server
269sudo -u dbbasic git pull --ff-only
270sudo -u dbbasic .venv/bin/python -m pip install -e '.[server,scheduler]'
271sudo systemctl restart dbbasic-object-server dbbasic-object-daemon
272```
273
274Changes to live objects and schemas need no deploy at all — that is the
275point. Only server-code upgrades need the pull-and-restart above.
276"
277architecture Architecture — The Layers, and Where Each Doc Fits Start Here 120 A map of the DBBASIC Object Server stack, from storage through access surfaces, with pointers to the focused doc for each layer. "DBBASIC is a small stack. Everything is a record or an object in a
278human-readable store; each layer above adds capability without hiding the one
279below. This page is the map — read it first, then branch into the focused doc
280for whichever layer you care about.
281
282```mermaid
283flowchart TB
284 A[""Access surfaces — Web · HTTP API · Shell / AI / MCP · Files""]
285 P[""Permission engine — one policy enforced on every surface""]
286 G[""Generative UI — list / table / board / tree / calendar · forms · detail · filters · search""]
287 C[""Capabilities — comments · attachments · sharing""]
288 D[""Data — schemas (types · validation · relations · transitions) + collections""]
289 R[""Runtime — ASGI object execution · realtime change log · daemon (triggers · schedules)""]
290 S[""Storage — human-readable TSV + object source / state / logs / files / versions""]
291
292 A --> P --> G
293 G --> C
294 G --> D
295 C --> D
296 D --> R --> S
297 R -. live updates .-> G
298```
299
300Every app is a **package** installed onto this stack — a schema, permission
301rules, and at most one page object, with no app-specific server code. The same
302stack serves the web page, the API, search, files, and the AI.
303
304## The layers, bottom to top
305
306**Storage.** Collections are plain TSV you can `grep`, in one of two modes
307(classic overwrite, or append-only with tombstones + compaction). Each object
308keeps its source, state, logs, files, and version trail next to it.
309→ [`storage-modes.md`](/docs/storage-modes),
310[`append-only-storage-design.md`](/docs/append-only-storage),
311[`durability-and-recovery.md`](/docs/durability-and-recovery),
312[`backup-restore.md`](/docs/backup-restore)
313
314**Runtime.** A long-running ASGI server executes objects in-process, pooled, or
315in a subprocess. A daemon runs scheduled passes, compaction, and
316trigger→target automation. A websocket change log lets any surface re-render
317live.
318→ `runtime-contract.md`,
319[`realtime.md`](/docs/realtime),
320[`asgi-realtime-direction.md`](/docs/asgi-realtime-direction),
321[`object-authoring.md`](/docs/object-authoring),
322[`capability-objects.md`](/docs/capability-objects)
323
324**Data & schema.** A collection's schema declares its fields — types, enums,
325relations (validated pointers), bounds, defaults, and status transitions — and
326those are enforced on every write, not just in the form.
327→ [`schema-forms.md`](/docs/schema-forms),
328[`validation-and-logic.md`](/docs/validation-and-logic),
329[`business-logic-patterns.md`](/docs/business-logic-patterns),
330[`logic-decisions.md`](/docs/logic-decisions)
331
332**Permissions.** One engine decides access for every surface: access modes,
333role/object/action rules, ownership, row and field filters, temporary paid
334access, and record sharing. Routing maps URLs; the policy decides what a
335caller may see or write.
336→ [`permissions-model.md`](/docs/permissions-model),
337[`site-routing.md`](/docs/site-routing),
338[`secrets-and-credentials.md`](/docs/secrets-and-credentials)
339
340**Generative UI.** One renderer turns a schema into a live
341list/table/board/tree/calendar, a form, and a composed detail page — with
342filters, sort, search, relation labels, and realtime updates — no per-app UI
343code. The design system is a semantic contract, not prescribed widgets.
344→ [`generative-ui.md`](/docs/generative-ui),
345[`design-system.md`](/docs/design-system),
346[`ui-decisions.md`](/docs/ui-decisions)
347
348**Capabilities.** Generic per-collection *behaviors* on top of the display
349layer: a schema flag grows a comment thread, attachment list, or owner-checked
350sharing, with no per-app table.
351→ [`capabilities.md`](/docs/capabilities)
352
353**Access surfaces.** The same records reach a web page, the HTTP API,
354cross-collection search, file up/download, MCP agents, and a talk-to-everything
355shell — all behind the one permission engine.
356→ [`http-api-contract.md`](/docs/http-api-contract),
357[`rest-and-object-messages.md`](/docs/rest-and-object-messages),
358[`shell-and-ai.md`](/docs/shell-and-ai)
359
360**Packages.** Apps are installable packages with a data-preserving upgrade
361system (provenance baselines, three-way reconcile, override objects, feature
362flags).
363→ [`app-packages.md`](/docs/app-packages),
364[`package-authoring.md`](/docs/package-authoring),
365[`upgrade-and-customization.md`](/docs/upgrade-and-customization)
366
367## Operating it
368
369→ [`quickstart.md`](/docs/quickstart) (fresh VM to first app),
370[`single-vm-deployment.md`](/docs/single-vm-deployment),
371[`docker-deployment.md`](/docs/docker-deployment),
372[`traffic-limits.md`](/docs/traffic-limits),
373`status.md`
374
375## Why it's shaped this way
376
377→ [`why-dbbasic.md`](/docs/why) (the advantages, honestly stated),
378[`comparisons.md`](/docs/comparisons) (what DBBASIC deletes vs Django/Rails/
379no-code, and the cost of each deletion)
380"
381zero-to-code From Zero Code to Some Code Start Here 130 The staged path every app on the DBBASIC Object Server follows, from a schema with no code at all through hooks, event handlers, verbs, scheduled runners, and hand-written pages. "The question every generative system eventually gets asked: *fine, the
382metadata builds the app — but when I need real code, where does it go?*
383This page is the known path. Every app on this server grows through the
384same stages, in the same order, and the order is the point: **code enters
385through the write path first and the page last** — the exact reverse of
386the classic web framework, where code entered through the controller
387first and that is where the logic rotted.
388
389## Stage 0 — an app with no code at all
390
391A schema (`schemas/notes.json`), permission rules, and two seeded view
392records (an index at `/notes`, a detail at `/notes/{id}`). From those
393alone: list, search, sort, create/edit forms, a detail page, realtime
394updates, the JSON API, MCP tools for agents, and global search. All of it
395reads the schema; none of it is emitted as code
396([`generative-ui.md`](/docs/generative-ui), including why this is *not*
397scaffolding).
398
399`app-notes` ships this way today: a package registering zero objects.
400
401## Stage 1 — logic as declarations (still no code)
402
403Most business rules are not code and never should be:
404
405- shape, bounds, required, enums, FK-exists → **schema validation**
406- who may do what, whose rows are whose → **permission rules**
407- legal state moves and who may make them → **`transitions` + `when`**
408- same-record derivations → **`formula` fields**
409- sums over children → **`rollup` fields**
410- ""how many of these are waiting for somebody"" on the home page → an
411 **`attention` declaration** (`collection` + `where`, counted per viewer
412 through the permission rules; [`package-authoring.md`](/docs/package-authoring#declared-counts-collection--where))
413
414Every surface enforces these because they live on the shared write path,
415not in a page. A large fraction of real apps end here.
416
417## Stage 2 — the first line of Python is a gate
418
419The first rule that *cannot* be declared is almost always a cross-record
420check: ""a payment may not exceed the invoice balance"", ""a journal must
421balance before posting"", ""a loss move cannot have a destination"". That is
422a **pre-write hook** — one file, one function:
423
424```python
425# objects/hook/payments.py schema: ""hooks"": {""before_write"": ""hook_payments""}
426def BEFORE_WRITE(request):
427 if too_much(request[""record""]):
428 return {""error"": ""..."", ""status"": 409} # reject
429 record = dict(request[""record""]); record[""rate""] = looked_up # or stamp
430 return {""record"": record}
431```
432
433Hooks run on the shared write path, so the form, the API, and an AI agent
434all hit the same gate. They fail closed. This is where code enters the
435system, and it enters *enforcing*, not rendering.
436
437## Stage 3 — reactions
438
439Something should *happen* after a write: a status flips, a journal is
440composed, someone is notified. Notifications are data (`notify_rules`);
441follow-on writes are an **event handler** — a `system/` object with
442`HANDLES = [""payments.record.created""]` and an `EVENT(request)` function.
443Reactions are post-commit and best-effort: they may never block the write
444that already happened ([`logic-decisions.md`](/docs/logic-decisions) #6), and
445anything they generate is idempotent by provenance (#7).
446
447## Stage 4 — verbs
448
449Users (and agents) do things that are not CRUD: *reverse this journal*,
450*apply this count*, *import this statement*, *resolve this bank line*.
451Each is an **action object** — `objects/action/<verb>.py` with a `POST`
452that checks identity, validates, and writes through the same records
453layer. A verb is the honest home for anything a button should do that a
454form cannot.
455
456## Stage 5 — time
457
458Aging, dunning, recurring entries, escalation: time-driven state belongs
459to the **daemon** (#2), as a runner object registered on the scheduler
460(the `/scheduler` board shows every run's outcome) or a message on the
461queue (delay, retry, backoff — already built). A runner is just an object
462with a `POST`; it is callable by hand for testing and by the clock in
463production.
464
465## Stage 6 — presentation code, last of all
466
467Only when a page must *show* something no generic block can express:
468
469- first an **`object` block** — one hand-written panel inside an otherwise
470 generated page (`{""kind"": ""object"", ""object_id"": ""site_my_panel""}`);
471- then, rarely, a **full page object** — `site/notes.py` overrides the
472 generated `/notes` by convention the moment the file exists, and
473 deleting it reverts. Reports are the legitimate case: the trial balance,
474 the statements, the reconciliation tie-out are folds across collections
475 with audit-grade warnings, and they stay hand-written on purpose.
476
477The rule that keeps stage 6 safe: **a page may never be the only place a
478rule exists.** A gate written into a page does not gate the API or an
479agent — it provably does not hold — so enforcement stays in stages 1–2
480where every surface shares it. Pages show; they never decide.
481
482## The whole path at a glance
483
484| stage | you add | it lives in | enforced for |
485|---|---|---|---|
486| 0 | schema + rules + 2 view rows | data | every surface |
487| 1 | declarations (transitions, formulas, rollups) | schema | every surface |
488| 2 | a gate | `hook/` on the write path | every surface |
489| 3 | a reaction | `system/` handler, `notify_rules` | post-commit |
490| 4 | a verb | `action/` | its callers |
491| 5 | a schedule | runner + scheduler/queue | the clock |
492| 6 | a panel, then a page | `object` block → `site/` | presentation only |
493
494## Where this page came from
495
496This path was not designed and then implemented — it was **extracted**. A
497week of building real modules concretely (payments, the books spine, bank
498reconciliation, inventory losses, cash counts) kept producing the same
499placement decisions, and once every kind of business rule had exactly one
500home, the homes sorted themselves into the order an app acquires them.
501The taxonomy is the load-bearing thing; the path is its corollary.
502
503That is also why earlier frameworks never had a page like this. They
504documented their *mechanisms* (models, controllers, middleware, signals)
505but never fixed where *logic* lives — any rule could go anywhere, so there
506was no gradient from zero code to some code, only a cliff. ""Fat models,
507skinny controllers"" was a slogan, not a placement table with enforcement
508behind it. A path only exists where placement is decided.
509
510The runtime twin of this page is [`write-pipeline.md`](/docs/write-pipeline):
511once logic is placed, that page says exactly when it runs, in what order,
512and what can stop a write.
513
514Placement questions beyond this page: the flowchart in
515[`business-logic-patterns.md`](/docs/business-logic-patterns) decides where
516any individual rule goes, and [`logic-decisions.md`](/docs/logic-decisions)
517records why.
518"
519object-authoring Object Authoring Building on DBBASIC 200 How to write DBBASIC objects: source layout, HTTP-style methods, request identity, runtime helpers, response shapes, and public deployment safety. "This document describes the object shape supported by the current public server
520slice. It is intentionally small and should stay compatible with the working
521private runtime while the hardened runtime moves into this repository.
522
523## Source Location
524
525Object source lives under `objects/` by default:
526
527```text
528objects/site/home.py
529objects/basics/counter.py
530objects/users/42/deals.py
531```
532
533The source root can be changed for deployments:
534
535```text
536DBBASIC_OBJECTS_DIR=/var/lib/dbbasic-object-server/objects
537```
538
539Object IDs are derived from paths:
540
541- `objects/site/home.py` becomes `site_home`
542- `objects/basics/counter.py` becomes `basics_counter`
543- `objects/users/42/deals.py` becomes `u_42_deals`
544
545## Methods
546
547An object is a Python file that can define HTTP-style methods:
548
549```python
550def GET(request):
551 return {""status"": ""ok""}
552
553def POST(request):
554 return {""status"": ""created"", ""payload"": request}
555```
556
557`GET` receives query parameters. `POST`, `PUT`, and `DELETE` receive the parsed
558request body plus query parameters where the HTTP contract allows it.
559
560## Request Identity
561
562Every request payload includes a server-controlled `_identity` key describing
563the resolved caller, so objects can render per-user pages and make per-user
564decisions without hand-rolling auth:
565
566```python
567def GET(request):
568 identity = request[""_identity""]
569 if identity[""user_id""] is None:
570 return {""status"": 401, ""error"": ""Sign in first""}
571 return {""hello"": identity[""user_id""], ""roles"": identity[""roles""]}
572```
573
574`_identity` contains `user_id`, `account_id`, `roles`, `subscriptions`, and
575`auth_method` (`admin_token`, `session_token`, `session_cookie`,
576`trusted_headers`, or `anonymous`). The server overwrites any client-supplied
577`_identity` value before the object runs, so it cannot be spoofed through the
578request body or query string. Anonymous requests still receive the key with
579`user_id` set to `None`.
580
581## Runtime Helpers
582
583Loaded object modules receive a small set of runtime helpers. The current public
584runtime injects:
585
586```python
587_state_manager.get(key, default=None)
588_state_manager.set(key, value)
589_state_manager.increment(key, delta=1) # -> new value; missing key starts at 0
590_state_manager.get_all()
591_state_manager.reload()
592
593_logger.debug(message, **fields)
594_logger.info(message, **fields)
595_logger.warning(message, **fields)
596_logger.error(message, **fields)
597```
598
599State is stored under `data/state/{object_id}/state.tsv`. Writers
600(`set`, `delete`, `increment`, ...) hold a per-file lock (thread lock plus an
601`flock` on `state.tsv.lock`), so `increment` is exact across threads, warm
602pool workers and spawned processes. A non-numeric existing value raises
603`TypeError` and is left unchanged. Logs are stored under
604`data/logs/{object_id}/log.tsv`. The active log is plain TSV. Rotated logs are
605gzip-compressed by default and can still be read by the server.
606
607User-namespace objects (`u_<uid>_*`) get these same helpers as proxies
608across a sandbox boundary, with a few deliberate differences (`files_dir`,
609`update(after_set=...)`, and loaded *system* objects expose only `execute`);
610see runtime-contract.md ""User Object Isolation"".
611
612### `_files`: per-object file storage
613
614```python
615_files.put(filename, content: bytes) -> None # create or replace
616_files.get(filename) -> bytes # FileNotFoundError if missing
617_files.delete(filename) -> None # a missing file is not an error
618_files.list() -> [{""name"": str, ""size"": int, ""modified"": float}, ...]
619_files.exists(filename) -> bool
620_files.files_dir # pathlib.Path of the directory
621```
622
623Files live in `<DBBASIC_DATA_DIR>/files/<object_id>/` and are the same files
624the HTTP object-file API serves (`object_files.py` does all path handling).
625Each object's `_files` is bound to its own object id and cannot name another's.
626Names may contain `/` subdirectories; `..`, absolute paths, NUL, empty names
627and symlinks that leave the directory raise `ValueError`. `put` accepts bytes
628only (`TypeError` otherwise) and refuses content larger than
629`DBBASIC_MAX_OBJECT_FILE_BYTES` (default 1 MiB, the same limit as the HTTP
630file API) with `ValueError`. `list()` includes files in subdirectories (names
631are relative, `a/b.txt`); the old server listed only the top level.
632
633### `_runtime`: calling another object
634
635```python
636other = _runtime.load_object(""tools_ocr"") # an object id, not a path
637result = other.execute(""POST"", {""image"": ""...""}) # whatever the method returns
638other.state_manager, other.file_manager, other.logger, other.object_id
639```
640
641Ids resolve exactly as for HTTP requests (`object_namespace.resolve_object_id`).
642Paths such as `examples/x.py` are not accepted. Errors, all subclasses of
643`object_runtime_helpers.CompositionError`: `CompositionNotFoundError`
644(`LookupError`), `CompositionDeniedError` (`PermissionError`) and
645`CompositionDepthError`.
646
647Namespace rule (fail closed): an object in a user namespace (`u_<uid>_...`)
648may load only objects in its own namespace (`u_<same uid>_...`) and non-user
649(system or package) objects. It can never load `u_<other>_*`; the refusal is
650the same whether or not the target exists. Non-user objects may load any
651object. The loaded object runs inside the caller's process with the caller's
652isolation (pool worker, spawned child, or in-process) and its own `_files` and
653`_state_manager`. A locked check may not load objects at all.
654
655Call depth is limited to `object_runtime_helpers.MAX_COMPOSITION_DEPTH` (8)
656nested executions per call chain, counting the outermost request; an object
657that calls itself, or A -> B -> A, fails with `CompositionDepthError`. This is
658not a sandbox: an object can still import modules and touch the filesystem.
659
660### `_schedule` / `_unschedule`: running a method on a timer
661
662```python
663_schedule(1800, ""refresh"") # run refresh() every 30 minutes; returns the task row
664_unschedule(""refresh"") # stop that one; returns how many tasks went
665_unschedule() # stop every method this object scheduled
666```
667
668The earlier object server's signatures, so ported objects (weather and RSS caches, the scan
669processor, `basics/ticker.py`) run unchanged, including their
670`if _scheduler_registered or not _schedule:` guards. Each call writes one
671`interval` task on the daemon's scheduler board (`object_schedule.py`), keyed
672by (object id, method): calling again is an update, and calling again with the
673same interval changes nothing -- so calling it on every request is safe. The
674daemon (`object_daemon.py`, which must be running: see the deployment docs)
675calls the method by its exact name with **no arguments** (or the empty payload
676if its signature requires one), through the normal execution path. It runs as
677itself: no caller's identity is attached.
678
679Rules: the method must be a public function the object defines (a name not
680starting with `_`; checked when you schedule); intervals are whole seconds, at
681least `DBBASIC_SCHEDULE_MIN_INTERVAL_SECONDS` (default 5). User objects
682(`u_<uid>_*`) may schedule only themselves, at least every
683`DBBASIC_SCHEDULE_USER_MIN_INTERVAL_SECONDS` (default 60), and one user's
684objects hold at most `DBBASIC_SCHEDULE_USER_MAX_TASKS` (default 10)
685schedules. Refusals raise `ValueError`. If the object or the method later
686disappears, the daemon skips the task and logs it once; destroying the object
687(`DELETE ?destroy=true`) removes its tasks. Unlike the old server, schedules
688survive restarts, appear in `GET /daemon/scheduler/tasks`, and an interval
689counts from the last run, so a stopped daemon does not owe a backlog.
690
691## Default Storage And Integrations
692
693The default DBBASIC object should not need a separate database. Source, state,
694logs, files, and versions are file-backed so a useful app can start on one VM
695with normal Unix paths and backups.
696
697Objects can still connect to SQL databases, SQLite files, HTTP APIs, AI APIs, or
698other services when a workload needs them. Those integrations should be explicit
699object behavior or package behavior, not hidden platform requirements.
700
701This keeps the base stack small while leaving room for:
702
703- SQL/reporting objects
704- schema and relationship inspectors
705- API connector objects
706- migration objects
707- AI-assisted query and data tools
708
709DBBASIC Scroll can expose SQL, schema, and diagram screens, but those should be
710capabilities of the object system rather than proof that every app needs a
711database tier by default.
712
713Schema still matters. The difference is that DBBASIC should let schemas,
714validation rules, relationships, and generated admin screens live close to the
715objects and packages that use them. That avoids forcing every small app through
716an external database, migration, ORM, admin, and deployment loop before the app
717has proved it needs that weight.
718
719```mermaid
720flowchart LR
721 subgraph DB[""Database-first loop""]
722 D1[""Design schema""] --> D2[""Run migration""]
723 D2 --> D3[""Update model/ORM""]
724 D3 --> D4[""Update route/view/controller""]
725 D4 --> D5[""Deploy""]
726 D5 --> D6[""Inspect errors""]
727 D6 --> D1
728 end
729
730 subgraph OBJ[""DBBASIC object loop""]
731 O1[""Edit object or package metadata""] --> O2[""Run it""]
732 O2 --> O3[""Read output, logs, state, errors""]
733 O3 --> O4[""Fix source or schema metadata""]
734 O4 --> O5[""Keep versions""]
735 O5 --> O1
736 end
737
738 O3 -.-> I[""Optional integrations: SQL, SQLite, HTTP APIs, AI APIs""]
739```
740
741## JSON Object
742
743```python
744def GET(request):
745 count = int(_state_manager.get(""count"", 0)) + 1
746 _state_manager.set(""count"", count)
747 _logger.info(""counter served"", count=count)
748 return {
749 ""status"": ""ok"",
750 ""count"": count,
751 }
752```
753
754Normal dictionaries return JSON.
755
756## HTML Object
757
758```python
759def GET(request):
760 count = int(_state_manager.get(""count"", 0)) + 1
761 _state_manager.set(""count"", count)
762 _logger.info(""home served"", count=count, response_type=""html"")
763
764 html = f""""""<!doctype html>
765<html lang=""en"">
766<head>
767 <meta charset=""utf-8"">
768 <meta name=""viewport"" content=""width=device-width, initial-scale=1"">
769 <title>DBBASIC Object</title>
770</head>
771<body>
772 <h1>DBBASIC Object</h1>
773 <p>This object has been served {count} times.</p>
774</body>
775</html>
776""""""
777
778 return {
779 ""content_type"": ""text/html; charset=utf-8"",
780 ""body"": html,
781 }
782```
783
784Dicts with `content_type` and `body` become raw HTTP responses. This is the
785shape used for pages, generated views, images, and other non-JSON object
786responses.
787
788Plain strings also return `text/html; charset=utf-8`. Plain bytes return
789`application/octet-stream`.
790
791## HTML Form Object
792
793Forms are how design changes ship without a deploy: the page, the handler, and
794the state live in one object. `GET` renders the form; `POST` receives the
795submitted fields (form posts from a signed-in browser carry the session cookie,
796so `request[""_identity""]` identifies the user in both methods):
797
798```python
799def GET(request):
800 identity = request[""_identity""]
801 if identity[""user_id""] is None:
802 return (303, [(""Location"", ""/login?next=/objects/notes_quick"")], b"""")
803
804 saved = _state_manager.get(f""note:{identity['user_id']}"", """")
805 html = f""""""<!doctype html>
806<html lang=""en"">
807<body>
808 <h1>Quick note for {identity['user_id']}</h1>
809 <form method=""post"">
810 <textarea name=""note"">{saved}</textarea>
811 <button type=""submit"">Save</button>
812 </form>
813</body>
814</html>""""""
815 return {""content_type"": ""text/html; charset=utf-8"", ""body"": html}
816
817
818def POST(request):
819 identity = request[""_identity""]
820 if identity[""user_id""] is None:
821 return {""status"": 401, ""error"": ""Sign in first""}
822
823 _state_manager.set(f""note:{identity['user_id']}"", str(request.get(""note"", """")))
824 _logger.info(""note saved"", user_id=identity[""user_id""])
825 return (303, [(""Location"", ""/objects/notes_quick"")], b"""")
826```
827
828Cookie-authenticated form posts are origin-checked by the server (same-site
829only), so objects do not need their own CSRF plumbing for basic forms. Records
830and schemas are the step up from object state when the data needs listing,
831validation, and change history — see the collections sections of
832[`http-api-contract.md`](/docs/http-api-contract).
833
834## Upload Forms
835
836`multipart/form-data` posts (forms with `enctype=""multipart/form-data""`) are
837parsed for you: text fields arrive as plain payload keys, and each uploaded
838file arrives under `request[""_files""]` with its content base64-encoded so the
839payload survives the subprocess execution boundary:
840
841```python
842import base64
843
844def POST(request):
845 upload = request[""_files""][""document""]
846 content = base64.b64decode(upload[""content_base64""])
847 _logger.info(""upload received"", filename=upload[""filename""], size=upload[""size""])
848 return {""saved"": upload[""filename""], ""bytes"": len(content)}
849```
850
851Each `_files` entry has `filename`, `content_type`, `size`, and
852`content_base64`. Upload size is bounded by `DBBASIC_MAX_REQUEST_BYTES`.
853
854An object that receives an upload can process it with system tools —
855OCR, transcode, thumbnail, extract — by shelling out to binaries like
856`tesseract` or `ffmpeg`. See [capability objects](/docs/capability-objects)
857for the subprocess model, worked examples, and the trust boundary.
858Store durable uploads through the object file APIs so they inherit
859permissions and change history.
860
861## Low-Level Response
862
863When an object needs exact status and headers, return a tuple:
864
865```python
866def POST(request):
867 return (201, [(""Content-Type"", ""text/plain"")], [b""created""])
868```
869
870The tuple shape is:
871
872```text
873(status, headers, body)
874```
875
876`body` may be bytes, text, or a list of bytes/text parts.
877
878## Authoring Rule
879
880Keep each object small enough to inspect, run, log, fix, and version quickly.
881The point of DBBASIC is the short loop:
882
883```mermaid
884flowchart LR
885 A[""edit object""] --> B[""run""]
886 B --> C[""read output, logs, state, errors""]
887 C --> D[""fix""]
888 D --> E[""keep version""]
889 E --> A
890```
891
892Objects can call other objects, emit events, handle jobs, serve pages, or expose
893APIs, but the first rule is the same: make the running object easy to inspect.
894
895## Public Deployment Safety
896
897Until role, object, and row-level permissions are enforced, do not expose the
898full `/objects` API on a public hostname.
899
900For public staging:
901
902- keep `DBBASIC_ENABLE_SOURCE_WRITES=false`
903- generate a deployment-specific `DBBASIC_ADMIN_TOKEN` outside the source tree
904- bind uvicorn to `127.0.0.1`
905- allowlist explicit public object routes in a reverse proxy
906- keep object source, state, logs, versions, and object listing private from
907 normal public users
908"
909package-authoring Package Authoring Building on DBBASIC 210 Practical guide to building and installing a DBBASIC package: manifest structure, install semantics, navigation and attention registries, and the authoring workflow. "This is the practical guide for building a DBBASIC package: one installable
910directory that ships an app piece — objects, schemas, and seed data — without
911a deploy pipeline. It is written for humans and AI tools that generate
912packages. The runtime contract details live in `runtime-contract.md#packages`;
913this page is the authoring workflow.
914
915## Find Your Task
916
917| I want to... | Go to |
918|---|---|
919| upgrade a package without losing data, and test it | [Upgrading a package](#upgrading-a-package-data-backfill-and-an-upgrade-test) |
920| know what a field permission does on a write | [permissions-model.md](/docs/permissions-model#field-permissions-on-writes-what-is-checked-and-the-known-limits) |
921| start a new package that already works | [Start from a scaffold](#start-from-a-scaffold) (`scripts/new_package.py`) |
922| check a change as different people, with permissions enforced | [Try Your Change](#try-your-change) (`scripts/try_package.py`) |
923| see which rows and labels a page would list for someone | [Try Your Change](#try-your-change), `--rows` |
924| let a role read every row while only owners write | [Recipes](#a-role-reads-every-row-while-only-owners-write) |
925| let staff enter records owned by members, donors or patients | [permissions-model.md](/docs/permissions-model#who-owns-a-record-you-create) (`""on_behalf"": true`) |
926| make a person's records show up in a subject access export | [Personal data](#personal-data-the-subject-export) (`""subject""`) |
927| count ""my queue"" on the menu or home page | [Recipes](#a-count-over-rows-i-own-or-am-assigned), [Attention](#attention-attention) |
928| freeze fields once a record is settled | [Recipes](#freeze-some-fields-once-a-record-is-settled) |
929| add a field and show it in a list | [Recipes](#add-a-field-and-show-it-in-a-list-page) |
930| make a value unique, required only in some state, or bounded | [Add a field](#add-a-field-and-show-it-in-a-list-page) links each rule |
931| compare a datetime with now in a check (aware or naive, UTC, unparseable values) | [Comparing a datetime with now](#comparing-a-datetime-with-now) |
932| refuse a write on the date, on another field, or on another collection | [What can't be declared](#what-cant-be-declared) |
933| require a field when a row of another collection says so (a category, a type) | [A requirement another collection decides](#a-requirement-another-collection-decides) |
934| see a whole app built that way (expenses, mileage, a register) | expense-substantiation.md |
935| change a page or route I already shipped | [Changing a seeded row in a new version](#changing-a-seeded-row-in-a-new-version) |
936| decide what to bump in `version` | [Which version to bump](#which-version-to-bump) |
937| know why an integer comes back as `""4""` | [What a record looks like on the wire](#what-a-record-looks-like-on-the-wire) |
938| my test failed after I added a field, a dependency or a version | [A failing pin on a pure addition is a test bug](#what-a-schemas-version-does) |
939| install, dry-run, restore | [What install does](#what-install-actually-does-today), [Authoring workflow](#authoring-workflow) |
940
941## What A Package Is
942
943A package is a directory under `packages/` (or `DBBASIC_PACKAGES_DIR`) with a
944manifest and package-relative content:
945
946```text
947packages/{package_id}/
948 dbbasic-package.json
949 objects/ # object source files
950 schemas/ # collection schema JSON files
951 seed/ # initial records, TSV files (new ids are added on every install)
952 permissions/ # rule fragments: merged into the deployment policy on install
953 migrations/ # declared, not run: install refuses a package that lists any
954```
955
956`permissions/` is installed: each file is `{""rules"": [...]}`, and install
957validates the rules, tags them with this package's id and appends the ones the
958policy does not already hold ([What install does](#what-install-actually-does-today)
959has the detail, including how a rule is retired). `seed/` is merged by record
960id, not written once ([same section](#what-install-actually-does-today)).
961
962A good package is one app primitive: contacts, notes, tasks, articles,
963invoices. Small enough to review, complete enough to install and use.
964
965## The Manifest
966
967`dbbasic-package.json` is plain JSON:
968
969```json
970{
971 ""dron"": ""0.2"",
972 ""id"": ""contacts"",
973 ""name"": ""Contacts"",
974 ""version"": ""0.1.0"",
975 ""description"": ""Contact records with a browse/edit page"",
976 ""compatibility"": {""dbbasic_object_server"": "">=0.1.0""},
977 ""dependencies"": [],
978 ""objects"": [
979 {""id"": ""contacts_directory"", ""path"": ""objects/contacts/directory.py""}
980 ],
981 ""schemas"": [
982 {""collection"": ""contacts"", ""path"": ""schemas/contacts.json""}
983 ],
984 ""seed"": [
985 {""collection"": ""contacts"", ""path"": ""seed/contacts.tsv""}
986 ],
987 ""permissions"": [],
988 ""migrations"": [],
989 ""schedules"": [
990 {""id"": ""contacts_dedupe_nightly"",
991 ""object_id"": ""contacts_directory"",
992 ""schedule"": ""10 6 * * *"",
993 ""description"": ""Flag likely duplicate contacts overnight.""}
994 ],
995 ""nav"": [
996 {""id"": ""contacts"", ""label"": ""Contacts"", ""path"": ""/contacts"",
997 ""blurb"": ""People, the organizations they belong to, and interactions"",
998 ""surface"": ""member"", ""group"": ""Work"", ""order"": 60}
999 ]
1000}
1001```
1002
1003Rules the server enforces:
1004
1005- `id` must be a safe package identifier; object ids and collection names are
1006 validated with the same rules as the rest of the server.
1007- All paths are package-relative. Absolute paths, null bytes, and `..`
1008 traversal are rejected at parse time.
1009- `dron` (optional) names the DRON version the package was written for, as
1010 `""MAJOR.MINOR""` text. A server installs it if it reads that version or a
1011 later minor of the same major; a later minor, another major, or a value
1012 that is not `""MAJOR.MINOR""` text refuses the install (and the dry run)
1013 before anything is written, naming the version asked for and the version
1014 the server reads: `Package app-tickets dbbasic-package.json: the package
1015 was written for DRON 0.3 and this server reads DRON 0.2, ...; upgrade the
1016 server ...`. Leave it out and the package installs as it always did. The
1017 scaffold writes the server's version. See dron.md.
1018- **A key DRON does not define refuses the install.** A misspelt section
1019 (`schedule` for `schedules`), a `nav` entry's `lable`, a schema field's
1020 `requird` or a rule's `row_filtr` is refused when the package is loaded,
1021 before anything is written, and the message names the file, the entry or
1022 rule, the key and the closest spelling: `Package permission rule is
1023 invalid: permissions/rules.json rule 3: unknown key 'row_filtr' (did you
1024 mean 'row_filter'?)`. (Until this was tightened such a key was dropped and
1025 the install succeeded; a rule whose `row_filter` was misspelt covered every
1026 row.) The same goes for values the loader used to coerce or re-case
1027 (`""required"": ""no""`, a text `version`, `""nav_optional"": ""no""`, `""type"":
1028 ""Integer""`, `""effect"": ""Allow""`, `""surface"": ""Public""`), for an unknown
1029 field type, and, in permission rules and transition guards, for an unknown
1030 action, principal, operator or `$`-variable (`$userid`) and a boolean filter
1031 value (write `""true""`). The engine-only synonyms (`readonly`, `readOnly`,
1032 `computed: true`, `validation.regex`, `validation.required`,
1033 `validation.choices`, `validation.in`, `{""values"": [...]}`) are refused with
1034 the DRON spelling. So are values that used to install and then fail the
1035 first write or render that touched them, or do nothing: a `validation.min`
1036 or `max` that is not a number, a field `permissions` level other than `edit`,
1037 `read` or `hidden` (`write` and `readonly` are the engine's spellings, not
1038 DRON's), a `relation` with no collection, a `formula` or `rollup` on a field
1039 that is not `""type"": ""computed""`, a rollup with no `collection`, `fk_field`
1040 or `op`, an `op` other than `sum`, `count`, `min`, `max` or `avg`, or an op
1041 other than `count` with no `field`, a `hooks.before_write` that is not an
1042 object id, and a `views.list_mode` other than `table`, `board`, `tree`,
1043 `calendar`, `cards` or `feed`: `Package schema is invalid:
1044 schemas/orders.json: orders: views.list_mode 'grid' is not a list mode; write
1045 one of table, board, tree, calendar, cards or feed`. Schemas already stored on
1046 a box, ones saved through the schema API, and the deployment's own policy
1047 file are read as before: only a package declaration is held to DRON.
1048 The DRON JSON Schema, [below](#editor-help-the-dron-schemas), catches the
1049 same mistakes earlier, in your editor or through `tests/test_dron_schema.py`,
1050 which validates every shipped manifest, schema and rules file against it (it
1051 needs no `jsonschema` package; it carries its own small validator). A package
1052 of your own is checked the same way once it sits under `packages/`:
1053 `python -m pytest tests/test_dron_schema.py -k your-package-id`. The dry run
1054 (`GET /packages/{package_id}?dry_run=true`) lists a refused declaration in
1055 its `warnings`, with the same reason, before you install.
1056
1057## What Install Actually Does Today
1058
1059Installs are deliberately conservative:
1060
1061- `objects` entries are written under the configured objects root. Existing
1062 objects require `allow_replace`.
1063- `schemas` entries are validated and written under `data/schemas/`. Existing
1064 schemas require `allow_replace`; with it, an unedited schema is replaced
1065 (`updated`), and one an operator has customised is merged field by field
1066 (`merged`) or parked as a conflict to resolve. See
1067 [What a schema's `version` does](#what-a-schemas-version-does).
1068- `seed` TSV is **merged by `id`**: a collection with no records takes the
1069 whole file; a collection that already holds records gets only the seed rows
1070 whose `id` it does not have (reported `status: ""merged""`, or `""skipped""`
1071 when nothing was new). A row that is already there is never overwritten
1072 with something an operator changed, so a reinstall never destroys live
1073 data and never blocks the install. A column the package itself changed in
1074 the new version, and nobody has edited since the install wrote it, is
1075 refreshed; an edited one is kept and reported (`replaced` / `kept` on the
1076 seed entry): see [Changing a seeded row in a new
1077 version](#changing-a-seeded-row-in-a-new-version). A row the collection refuses (a `unique` key live data already
1078 holds, a value its schema rejects) is listed under `rejected` in the result
1079 and the rest still merge. This is what makes an in-place upgrade safe:
1080 reinstall with `allow_replace` to ship new object code, a migrated schema,
1081 and re-merged permissions while every existing record is preserved. Live
1082 records live outside the package, in `data/collections/<name>/records.tsv`
1083 keyed by collection, so an upgrade has no reason to touch them. (Evolving a
1084 schema across an upgrade — backfilling a newly added field on old rows — is
1085 the separate `migrations` story below, not yet implemented; adding a
1086 field is safe because old rows simply read as empty for it, and a `default`
1087 applies to rows written from then on, not to old ones.)
1088- `permissions` entries MERGE: each fragment file is
1089 `{""rules"": [ ... ]}` using the same rule shape as the policy document
1090 (`effect`, `principal`, `actions`, optional `collection`/`object_id`,
1091 row filters, field lists). On install the rules are validated, stamped
1092 with `""package"": ""<package_id>""` provenance, and appended to the
1093 deployment policy — skipping any rule that already exists, so reinstalls
1094 are idempotent. This is how a site package makes its own pages public:
1095 ship the grant with the code instead of hand-editing policy after install.
1096 Invalid fragments block the whole install.
1097- **Deleting or changing a rule is a retirement, and an upgrade performs
1098 it.** Two rules are the same rule when everything but `reason` matches,
1099 so adding a row filter to a grant, or dropping an action from it, ships a
1100 NEW rule and withdraws the old one. Every install records the rules the
1101 package shipped (`permissions` in `data/package_baselines/<id>.json`);
1102 the next install removes from the policy any rule that is in that record,
1103 is no longer shipped, and is still tagged as this package's. Nothing to
1104 write: delete the rule from `rules` and it goes on upgrade.
1105
1106 A box installed before 2026-11-28 has no such record, so for it (and for
1107 any rule you want gone whatever the box's history) list the withdrawn
1108 rule in the fragment's optional `retracted` array, in the same shape,
1109 with a `reason` that says why it was withdrawn:
1110
1111 ```json
1112 {
1113 ""retracted"": [
1114 {""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read""],
1115 ""collection"": ""template_runs"",
1116 ""reason"": ""replaced by the owner-filtered read""}
1117 ],
1118 ""rules"": [ ... ]
1119 }
1120 ```
1121
1122 **When you delete or tighten a shipped rule, add the old rule to
1123 `retracted` in the same commit** and leave it there: it is how every
1124 older install finds out. A rule may not be in both lists (the install is
1125 refused). `tests/test_package_permission_retraction.py` reads this
1126 checkout's git history and fails, printing the entries to paste, when a
1127 rule that was once shipped is neither shipped nor retracted.
1128
1129 Either way a live rule is removed only if it is tagged as this package's
1130 AND identical to the withdrawn one. A rule the operator edited no longer
1131 matches and a rule the operator wrote has no tag; both stay, and the
1132 install reports them (`permission_retractions` in the dry run and the
1133 install response; removed rules are kept whole in the package change
1134 log). `GET /permissions/unshipped` lists every rule in the policy that no
1135 installed package ships. See ""Package Rules And Upgrades"" in
1136 [`permissions-model.md`](/docs/permissions-model).
1137- **A grant you leave out is not a refusal for the row's owner.** With no
1138 rule matching, the engine's owner fallback lets whoever `owner_id`,
1139 `user_id` or `created_by` names read, update and delete the row. If the
1140 people a collection's rows belong to must not change or remove them
1141 (a ledger, a log, a run history, anything whose rule says ""no delete""),
1142 ship the rule that says so:
1143
1144 ```json
1145 {""effect"": ""deny"", ""principal"": ""owner_fallback"",
1146 ""actions"": [""update"", ""delete""], ""collection"": ""wallet_entries"",
1147 ""reason"": ""the ledger is the balance: entries are never edited or deleted""}
1148 ```
1149
1150 It switches the fallback off and nothing else: your explicit grants still
1151 grant, admins and in-process writers are unaffected. Details and where the
1152 fallback reaches: ""Ownership"" in
1153 [`permissions-model.md`](/docs/permissions-model).
1154 `tests/test_owner_fallback_opt_out.py` fails until a new collection whose
1155 owners get update or delete from the fallback alone is either opted out,
1156 granted explicitly, or listed there as a deliberate decision.
1157- `migrations` are accepted in the manifest and reported in dry-runs, but
1158 install rejects them until explicit run semantics land.
1159- `schedules` become `task_<id>` rows in the scheduler trigger's state,
1160 which is where `object_daemon.process_scheduler` reads the board from.
1161 **If your app needs a recurring pass, declare it here.** A schedule that
1162 exists only in a running server's state is invisible to review, absent
1163 from a fresh install, and gone the next time the box is rebuilt — that
1164 is precisely how a demo server ended up with four nightly passes that
1165 appeared nowhere in this repository. Fields: `id` (becomes the state
1166 key, `[a-z][a-z0-9_]*`), `object_id`, `schedule`, and optional `type`
1167 (`cron` — the default — or `onetime`), `method` (default `POST`),
1168 `payload`, `description`.
1169
1170 Three properties make declaring a schedule safe to do repeatedly:
1171
1172 - **Run history survives.** `last_run`, `run_count` and `next_run`
1173 belong to the daemon and are never reset by an install. An upgrade
1174 that forgot when a pass last worked would make ""is this actually
1175 running?"" unanswerable.
1176 - **A pause is honoured.** The package declares what *should* run; an
1177 operator decides what *does* right now. A reinstall never restarts a
1178 task somebody deliberately paused.
1179 - **A changed expression reschedules.** Editing the cron clears
1180 `next_run` so the daemon recomputes it; leaving it alone keeps
1181 tonight's firing exactly where it was, so shipping a patch does not
1182 skip a run.
1183
1184 Two things are refused outright, at install time rather than at 3am:
1185 an unparseable cron (the daemon reads that as ""no next run"" and moves
1186 on in silence — a pass that never runs and never complains), and a
1187 schedule aimed at an object neither this package nor the server
1188 provides. Removing a schedule from a manifest does **not** delete the
1189 task, matching the rest of install: deregistering never destroys.
1190- `nav` entries become rows in the `nav_entries` collection, which every
1191 navigation surface folds over. **If your app serves a page, declare its
1192 door here.** See the section below.
1193- `attention` entries become rows in the `attention_sources` collection,
1194 which the daemon's rollup pass reads its list of providers from.
1195 **If your app has a queue that waits on a person, declare it here.**
1196 See the section below.
1197- The HTTP install route creates a restore point first and appends changelog
1198 rows under `data/package_changes/{package_id}/changes.jsonl`.
1199
1200## Navigation (`nav`)
1201
1202A menu maintained by hand rots the moment somebody ships without editing
1203it, and the rot is invisible — nothing fails, the front door just
1204advertises a server that no longer exists. This repository had three such
1205lists of the same apps: the app switcher's JS array in `site_nav` (25
1206entries), the home page's tile grid in `site_home` (21), and a
1207collection-to-URL map for search hits. They disagreed with each other and
1208between them named none of the eight newest apps. Worse, `site_home`
1209existed in no package at all — it lived only on a running server, so a
1210rebuilt box came back with no front door and said nothing about it, which
1211is precisely the failure the `schedules` section was built to end for
1212cron.
1213
1214So a door is declared by the app that owns it, and every navigation
1215surface becomes a fold over one registry:
1216
1217```json
1218""nav"": [
1219 {""id"": ""shop"", ""label"": ""Shop"", ""path"": ""/shop"",
1220 ""blurb"": ""Browse what is for sale and buy it"",
1221 ""surface"": ""public"", ""group"": ""Commerce"", ""order"": 400}
1222]
1223```
1224
1225- `id` becomes the `nav_entries` record id, so `[a-z][a-z0-9_]*`. It must
1226 be unique across every installed package: two packages writing one row
1227 is two packages fighting over one door.
1228- `label` and `path` are required. `path` starts with `/` and holds no
1229 whitespace.
1230- `blurb` is one honest line in the present tense saying what the app
1231 does — it is rendered under the label on the home grid. No marketing.
1232- `surface` is `public` | `member` | `operator` | `hidden`, default
1233 `member`. This governs the MENU and is not access control: permissions
1234 decide who may open a page, and leaving a door off the menu hides
1235 nothing that was not already protected. `/shop` and the public
1236 product/pay/portal pages are `public`; ordinary app pages are `member`;
1237 `/scheduler`, `/flow`, `/urls`, `/dashboard` and other admin or debug
1238 pages are `operator`.
1239- `group` is free text, default `Apps`. The house groups are **Work**,
1240 **Publishing**, **Money**, **Commerce**, **Warehouse** and **System**.
1241- `order` is an integer, default `100`. Packages band it by group (Work
1242 in the 0s, Publishing the 200s, Money the 300s, Commerce the 400s,
1243 Warehouse the 500s, System the 600s) because a group sorts where its
1244 earliest entry sorts — that way the reading order of the groups falls
1245 out of the same number, instead of a seventh list holding it.
1246
1247Three properties make declaring a door safe to do repeatedly:
1248
1249- **The operator's `hidden` survives.** `operator_hidden` is a separate
1250 boolean column and an install never writes it on an existing row. The
1251 package says what the app IS; the operator says what they want to SEE.
1252 An upgrade that silently put back a page somebody deliberately removed
1253 would be the same class of incident as one that restarts a paused
1254 nightly pass — so an operator flips `operator_hidden` (a `role:manager`
1255 update on `nav_entries`) instead of editing somebody else's manifest.
1256- **Unchanged means unwritten.** Every package-owned field — label, path,
1257 blurb, group, surface, order — is compared before anything is written,
1258 so a plan that reports `unchanged` is one where nothing at all is about
1259 to happen. A dry run that under-reports is worse than no dry run.
1260- **Removing an entry does not delete the row.** Same as the rest of
1261 install: deregistering never destroys.
1262
1263Two things are refused, and one deliberately is not:
1264
1265- A **duplicate id inside one manifest**, and an **invalid surface, path
1266 or order**, fail at parse time.
1267- A **collision with another package** blocks the install: an id already
1268 registered by a different package, or a path a different package
1269 already claims. Whichever installed last would otherwise silently win,
1270 and the loser's menu entry would point somewhere its own package never
1271 chose.
1272- Whether a path is actually **served** is NOT checked. Routing has three
1273 sources (convention, `site_routes` records, `views` records) and two of
1274 them are data the same install may be about to seed, so resolving a
1275 route here would produce false blockers. The registry records the door
1276 the package intends; `/urls` is where you go to see what the server
1277 actually answers.
1278
1279If the `nav_entries` collection does not exist yet (app-nav is not
1280installed), nav entries (and `attention` sources) are reported as `skipped`
1281with a reason and the install proceeds, with a line in the result's
1282`warnings` saying they were NOT registered. A package must never fail because
1283the navigation app is absent, and **install order does not matter**: the
1284install records what the package declared (in its baseline), and installing
1285`app-nav` registers the nav entries and attention sources of every package
1286already installed, listed in its result as `registered_for_others`. Only
1287missing rows are written, as their own package's; an existing row (an
1288operator's `operator_hidden` or `operator_muted`, another package's id) is
1289left as it is. A box installed before declarations were recorded falls back
1290to the package's manifest, only when that is the installed version, and
1291otherwise names the package in `warnings` (reinstall it).
1292`tests/test_install_order_nav.py` checks both orders.
1293
1294The same holds on an upgraded box whose `app-nav` is still the previous
1295release's. Its installed `attention_sources` schema can be older than the one
1296this tree ships (before declared counts it required `object_id`), and a row
1297written under the old schema would be refused, failing the install of the
1298package that declares the count. An install that finds the owner's installed
1299schema behind the one in this tree does not write those attention rows: they
1300are `skipped` with `stale_schema_owner` naming the package, the install
1301succeeds, and `warnings` says the rows wait for it. Installing `app-nav`
1302refreshes the schema and registers them (`registered_for_others`). A real
1303validation error against a current schema still refuses the install.
1304`tests/test_install_order_after_upgrade.py` installs `app-nav` from the
1305previous tag, then a package from this tree.
1306
1307### Depend on app-nav
1308
1309**The rule: a package that declares `nav` or `attention` lists `""app-nav""` in
1310`dependencies`.** The installer does not resolve dependencies (it records
1311them), but `scripts/try_package.py` installs a package's dependencies first, so
1312the declaration makes `app-nav` land first and the entries land with the
1313package itself; it also tells a reader what the package needs. `scripts/new_package.py`
1314writes it. It is a ""should"", not a ""must"": nothing refuses a manifest without
1315it, because install must never fail on the navigation app's absence, and an
1316app-nav installed later registers the entries anyway (above). Most of the
1317packages shipped before this rule was written do not declare it (a gap the
1318next version bump of each is the time to close, not a reason to copy it).
1319
1320### The opt-out
1321
1322`tests/test_package_nav.py` asserts that every package shipping a `site_*`
1323object or a `site_routes` seed declares at least one nav entry. That test
1324is the thing that stops the drift coming back. Some packages legitimately
1325serve a URL that is not a door — a mounted widget (`site_thread`,
1326`site_share`), a fragment inside another page
1327(`site_materialize_run_button`), a POST endpoint (`site_timer_actions`),
1328or a per-record document reached from the record itself
1329(`site_packing_slip`, `site_receiving_sheet`, `site_return_form`). Those
1330declare:
1331
1332```json
1333""nav_optional"": true
1334```
1335
1336which makes ""this app has no front page"" a reviewable claim in the
1337manifest rather than an omission nobody notices.
1338
1339## Attention (`attention`)
1340
1341A menu answers ""where can I go"". The only question a home screen is
1342actually asked is **does anything need me?**, and this server is unusually
1343well placed to answer it, because it is built almost entirely out of gates
1344and derived states. Every one of them produces a queue of things a machine
1345deliberately refused to decide: scans sitting at `extracted` waiting to be
1346confirmed into expenses, time entries `submitted` waiting for an approver
1347who is by design not the person who logged them, invoices past their due
1348date, bank lines nothing matched, POs a supplier shorted, orders committed
1349and not yet in a box, returns that arrived and were never judged.
1350
1351The system already computes all of it, on a schedule, and throws it away
1352at the end of each pass. `system_scan_processor` has been returning a
1353field literally named `needing_a_human` since the day it was written and
1354no surface has ever read it. The arithmetic was never missing; a place to
1355declare that the arithmetic *means* something was — and that declaration
1356can only honestly live in the package that owns the domain, because
1357nobody else knows that `extracted` is a waiting room and `confirmed` is
1358not.
1359
1360So it is declared, third use of the pattern that already fixed cron
1361(`schedules`) and navigation (`nav`):
1362
1363```json
1364""attention"": [
1365 {""id"": ""orders_to_pick"", ""object_id"": ""system_order_attention"",
1366 ""reads"": [""orders"", ""order_lines"", ""shipments"", ""shipment_lines""],
1367 ""label"": ""Orders to pick"", ""path"": ""/orders"",
1368 ""nav_id"": ""orders"", ""group"": ""Commerce"", ""severity"": ""normal""}
1369]
1370```
1371
1372Or, when the queue is ""rows of one collection in a waiting state"" (it
1373usually is), declare the count instead of writing a provider — see
1374[Declared counts](#declared-counts-collection--where):
1375
1376```json
1377""attention"": [
1378 {""id"": ""scans_to_confirm"", ""collection"": ""scans"",
1379 ""where"": {""status"": ""extracted""},
1380 ""detail"": {""op"": ""count"",
1381 ""where"": {""created_at"": {""op"": ""older_than_days"", ""value"": 7}},
1382 ""text"": ""{value} over a week old""},
1383 ""label"": ""Receipts to confirm"", ""path"": ""/scans"",
1384 ""nav_id"": ""scans"", ""group"": ""Money"", ""severity"": ""normal""}
1385]
1386```
1387
1388- `id` becomes the `attention_sources` record id, so `[a-z][a-z0-9_]*`,
1389 and it must be unique across every installed package.
1390- `object_id` names the provider (below), or `collection` names the
1391 collection a declared count reads — exactly one of the two. Checked: a
1392 counter aimed at an object (or a collection) neither this package nor
1393 the server provides **blocks the install**, exactly as a schedule does. A counter pointing
1394 at nothing reads zero forever, and a queue that reads zero forever is
1395 indistinguishable from a queue that is empty — the silent failure this
1396 whole section exists to end.
1397- `reads` (providers only) lists the collections the provider folds its
1398 number from. The number is computed with no viewer, so it is shown only
1399 to a viewer who may read **every row** of each listed collection the box
1400 has — see [Who sees a provider's number](#who-sees-a-providers-number).
1401 Leave it out and only admins see the count.
1402- `label` is what a person calls the queue, in their words: ""Receipts to
1403 confirm"", not ""scans.status=extracted"".
1404- `path` is where the count clicks through to. Required, starts with `/`,
1405 no whitespace. **A number that cannot be acted on in one click does not
1406 belong on a home page.** Whether anything actually serves the path is
1407 not checked, for the same reason `nav` does not check it.
1408- `nav_id` is optional: the `nav_entries` row this count decorates, so the
1409 app list itself reads ""Invoices — 5 overdue"" with no second surface to
1410 maintain. Omit it when the package ships no door at all (app-intake).
1411 **Two queues may name one door, and its badge is their sum**: a person with
1412 one deal they own and one assigned to them, as two sources on `nav_id:
1413 ""deals""`, sees `2` on the Deals entry (the entry's `severity` is the
1414 loudest of the two and its `detail` joins theirs). Before 2026-11 the
1415 louder queue won and the other was silently dropped. Each queue still has
1416 its own row, with its own count, in `attention`. Because they are added, a
1417 row that matches both queues is counted twice on the badge: make the
1418 queues disjoint, or put the union in one provider.
1419- `group` is free text, default `Apps`, and uses the same house groups as
1420 `nav`.
1421- `severity` is `normal` | `warning` | `urgent`, default `normal`, and is
1422 the first sort key on the home band. `normal` is work waiting;
1423 `warning` is work that is already late (an overdue invoice); `urgent`
1424 is something broken (a scheduler pass that failed). Three steps,
1425 because a scale with more is a scale nobody calibrates.
1426
1427### Declared counts (`collection` + `where`)
1428
1429Ten of the first sixteen providers were the same fifteen lines: read one
1430collection, keep the rows in the waiting state, return `len()` and a
1431sentence. A declaration says that instead, and `object_attention.count`
1432is the one function that evaluates every declaration.
1433
1434- **`where` is the permission row-filter language**, the same one a
1435 rule's `row_filter` uses and `object_permissions.record_matches_filter`
1436 decides — not a second one. Each value is a literal (`eq`), a
1437 `$`-variable, one `{""op"", ""value""}` condition (`eq`, `ne`, `in`, `gte`,
1438 `lte`, `gt`, `lt`), or a list of conditions ANDed. Membership is
1439 `{""op"": ""in"", ""value"": [""unmatched"", """"]}`; a bare list is refused,
1440 because in a row filter it is not membership. ""Not one of these"" is a
1441 list of `ne` conditions.
1442- **One operator is added**, for attention only: `{""op"":
1443 ""older_than_days"", ""value"": 7}`, which is **inclusive**: a row matches when
1444 its age is 7 or more days (`age >= 7`). A `YYYY-MM-DD` value is aged in
1445 calendar days against the server's local date; any other value is an ISO
1446 datetime (`Z` accepted, naive read as UTC) aged in elapsed whole days. An
1447 empty or unparseable value is never older than anything. ""Due before
1448 today"" is `{""op"": ""older_than_days"", ""value"": 1}` on a date.
1449- **Its threshold may be a setting**: `{""op"": ""older_than_days"", ""value"":
1450 {""setting"": ""carrier.stuck_days"", ""default"": 10}}` reads the first
1451 `app_settings` row with exactly that key and a non-blank value, once per
1452 count, through the key index. A value that is not a whole number of days
1453 ≥ 0 (`soon`, `7.5`, `-3`), or a box without app-settings, reads as the
1454 default. That is the only thing a declaration reads from settings: a
1455 number of days, by key — never an expression.
1456- **At least one literal equality is required** (`""status"": ""submitted""`,
1457 or `in`). The rows are fetched through the records cache's field index on
1458 it, so counting costs the queue, not the collection. A `where` made only
1459 of `ne` / ranges is refused at install.
1460- **""My own rows"" is `$user_id`** — `{""status"": ""draft"", ""owner_id"":
1461 ""$user_id""}` — resolved for the viewer. There is no separate scope switch.
1462
1463`detail` is optional: one part, or a list of parts joined with "", "".
1464
1465| Part | Value |
1466|---|---|
1467| `{""op"": ""count"", ""where""?: {...}, ""text"": ""{value} over a week old""}` | the counted rows, or those also matching `where` |
1468| `{""op"": ""sum"", ""field"": ""amount_cents"", ""format""?: ..., ""text"": ...}` | an integer field summed; an unparseable cell adds 0 |
1469| `{""op"": ""max_age_days"", ""field"": ""requested_on"", ""text"": ""oldest {value} days""}` | the oldest dated row's age; undated and future rows add nothing |
1470
1471A part whose value is 0 is left out unless it says `""show_zero"": true`; a
1472`max_age_days` with no dated rows is always left out. `{value}` is
1473optional: a `text` without it is a fixed sentence shown exactly when the
1474part would have been (`{""op"": ""count"", ""text"": ""failed 3 or more syncs in a
1475row""}`). `format` (sums only): `integer` (default), `cents` (`1,234.56`),
1476`dollars` (`$1234.56`), `hours` (seconds as hours, one decimal). Integer
1477arithmetic throughout.
1478
1479**Booleans need no case-insensitive operator.** The write path stores a
1480`boolean` field as exactly `true` or `false` (or blank), so ""enabled,
1481where blank means enabled"" is `{""op"": ""in"", ""value"": [""true"", """"]}` and
1482""failed"" is `""ok"": ""false""`. **""Not one of these"" over an `enum`** that
1483must also serve as the index is the complement written out — `""status"":
1484{""op"": ""in"", ""value"": [""sent"", ""partial"", ""overdue"", """"]}` — with a test
1485that the list plus the excluded values is the enum plus blank, so a value
1486added to the enum later fails a test instead of silently dropping out of
1487the count (`tests/test_app_invoices_package.py`).
1488
1489**Counted for the viewer, through the permission engine.** A declared
1490count is the number of matching rows *the person looking* may read
1491(`object_access.Access.visible`, the same per-row question the record API
1492asks), and the detail is computed over the same rows. An admin sees the
1493whole queue; a manager whose rule grants the collection sees the rows that
1494rule grants; a member with an owner-filtered read sees their own; someone
1495with no grant sees nothing. It fails closed wherever `object_access` does:
1496no identity, an unreadable policy. Project and share grants count, as they
1497do for the record API.
1498
1499**Counted from the fields the viewer may read**, when permissions are
1500enforced (`DBBASIC_ENABLE_PERMISSION_ENFORCEMENT`). Reading a row is not
1501reading all of it: a rule's `fields` / `denied_fields` or a schema field's
1502`permissions` can hide a field from someone who reads the row. Each row is
1503therefore judged as the record API would serve it to the viewer
1504(`object_access.Access.readable`), and:
1505
1506- a `where` condition on a field the viewer cannot read in a row is
1507 **false for that row**, whatever the operator (`ne` included). The count
1508 becomes ""rows where this field, which you can see, matches"": a support
1509 agent who reads every ticket but not `salary_band` sees `0` for a queue
1510 declared `""where"": {""status"": ""open"", ""salary_band"": ""A""}`, not the
1511 number of band-A tickets. If a queue is meant for people who cannot read
1512 the field it filters on, filter on a field they can read;
1513- a `sum` or `max_age_days` adds nothing from a row whose `field` the
1514 viewer cannot read, and a detail part's own `where` follows the rule
1515 above. When a field is hidden on some rows only (a field hidden from the
1516 row's `owner`), the sentence covers the rows where it is readable;
1517- a detail part that depends on a hidden field in **every** counted row is
1518 left out, even with `""show_zero"": true`: ""0.00 awaiting approval"" would
1519 be a statement about a field the viewer cannot read. The other parts of
1520 the sentence are kept.
1521
1522With enforcement off or audit-only nothing is redacted anywhere, and
1523counts and sentences are the row-level ones described above, unchanged. If
1524the mode cannot be determined, nothing is counted. A viewer who reads
1525every field a declaration names sees the same numbers either way. Being an
1526admin is not the same thing: the schema can hide a field from an admin as
1527from anyone. Among the shipped packages (audited 2026-12-03) exactly two
1528queues change, `thread_comments_to_moderate` and
1529`profile_comments_to_moderate`: their `status` is hidden from everyone but
1530the comment's owner and the `moderator` role, so with enforcement on an
1531admin who is not also a moderator is no longer shown those counts (the
1532record API does not show them `status` either). Moderators, and admins who
1533are also moderators, see what they did. The threshold a `{""setting"": ...}` reads from `app_settings` is
1534the box's configuration, the same for every viewer, and is not redacted.
1535
1536A code provider's number, by contrast, is computed with no viewer, so it
1537reaches only viewers who may read every row it was folded from
1538([below](#who-sees-a-providers-number)) — which is why a queue that can be
1539declared should be: a member then sees their own share instead of nothing.
1540
1541Declared counts are therefore **not rolled up**: the daemon skips them,
1542and removes any number a replaced provider left in `attention_counts`, a
1543global count being exactly what a per-viewer one must not leak. The index read is what keeps
1544this inside the rule below: the cost of a home render is each queue's
1545candidate rows, not a fold over the collection. (A collection over
1546`DBBASIC_RECORDS_CACHE_MAX_ROWS` has no index and is read whole, exactly as
1547every API list of it already is.)
1548
1549Write a provider instead when the number needs another collection (a
1550quantity still owed across order and receipt lines), arithmetic between
1551fields (how far below its reorder point the worst shelf is), one field
1552standing in for another (a run's `started_at`, else its `created_at`), or
1553a comparison the row-filter language does not have (a naive local
1554datetime against the wall clock, in minutes). Those are loops, functions
1555and expressions, and configuration never gets them. The five providers
1556that remain, and why:
1557
1558| Provider | Why it is code |
1559|---|---|
1560| `orders_to_pick` | ordered minus shipped, across orders, order lines, shipments and shipment lines |
1561| `pos_short_received` | the detail folds receipts and receipt lines against order lines |
1562| `products_to_reorder` | the detail is `reorder_point - on_hand` |
1563| `pickup_orders_overdue` | ""not ready"" has no index-able equality (it is the whole order history), `promised_at` is local wall-clock time, and the detail is in minutes |
1564| `scheduler_failures` | `started_at` falling back to `created_at`, distinct tasks by `task_id` falling back to `object_id`; scheduler runs are admin-read only, so gating it loses nobody |
1565
1566### Who sees a provider's number
1567
1568A provider's count was computed by the daemon over every row of the
1569collections it reads, with no viewer, and until 2026-11 it was shown to
1570every signed-in user — so a member with no grant on purchase orders saw how
1571many were short. Now `object_attention.provider_shown_to` decides, fail
1572closed:
1573
1574- an admin sees it;
1575- anyone else sees it only when the entry's `reads` names at least one
1576 collection the box has, and for **each** of them the viewer may read
1577 every row, whole (`object_access.Access.reads_every_row`): no deny rule
1578 that applies to them (filtered or not), and either the access mode allows
1579 the read or some allow rule grants it with no row filter and no field
1580 restriction. An own-rows grant is not enough — the number is everybody's
1581 rows;
1582- an entry with no `reads`, a `reads` that does not parse, or a stored
1583 count whose source row is gone: admins only;
1584- a listed collection the box does not have holds no rows and is skipped.
1585- with permissions enforced, a listed collection whose **schema** could
1586 hide any field from the viewer in some row hides the number from them,
1587 admins included (`object_field_permissions.may_hide_a_field`). The rule
1588 check above looks at rules only, and a provider does not say which
1589 fields it folds, so any field the record API would redact for this
1590 viewer might be one it counted or described. ""Could hide"" is decided
1591 without a row and fails closed: a field hidden from a principal the
1592 viewer matches, hidden from `owner` (anyone can own a row), hidden by
1593 `default` unless a role or other row-independent principal the viewer
1594 matches grants read or edit, or a `permissions` that does not parse. With
1595 enforcement off no field is redacted and this check is skipped; if the
1596 mode cannot be determined the number is shown to nobody. No shipped
1597 provider reads a collection with field permissions today.
1598
1599`attention_counts` itself is readable by nobody but an admin: the menu
1600reads it in process (`action_nav_entries`), and app-nav retracts the
1601`registered` read rule it used to ship, so an upgraded box drops it too.
1602
1603### The COUNT contract
1604
1605A provider is an ordinary object exposing:
1606
1607```python
1608def COUNT(request):
1609 return {""count"": 3, ""detail"": ""1 over a week old""}
1610```
1611
1612`COUNT` and not `GET` or `POST`, deliberately: a distinct verb means the
1613same object stays free to answer a human on the other methods without
1614either use accidentally serving the other. `count` must be a real
1615non-negative integer — the rollup refuses to coerce a string or a float,
1616because every coercion here is a way for a broken provider to look like
1617an empty queue. `detail` is optional and is the sentence a bare number
1618cannot say (""62 hours awaiting approval"", ""18 units still owed"").
1619
1620A provider reads its own collections and **degrades to `{""count"": 0}`
1621when they are absent** — a deployment that never installed your app
1622should not produce an error every five minutes. A provider that genuinely
1623fails should raise; see below for what happens then.
1624
1625### Counts are a rollup, not a live fold
1626
1627`object_daemon.process_attention` executes every code provider on an
1628interval (`DBBASIC_ATTENTION_INTERVAL_SECONDS`, default 300) and writes
1629the answers to the `attention_counts` collection. The home page and the
1630app list read that one small table.
1631
1632This is not an optimisation, it is a rule. Folding a dozen collections on
1633every home render is how a home page becomes the slowest page, and worse:
1634this box went to 675MB resident and started swapping because something
1635folded a big collection on a timer. A home screen that folds a dozen
1636collections per render is that same mistake with a nicer name, and it
1637makes the front page's cost grow with the number of installed packages —
1638the one place cost must not grow. Staleness is bounded by the interval
1639and **stated on the page** (""as of 6 minutes ago"") rather than pretended
1640away.
1641
1642Two consequences worth knowing when you write a provider:
1643
1644- **A broken provider must look broken, never look calm.** One that
1645 raises, or answers with a non-integer count, has its `error` written
1646 and its *previous* count kept, with `computed_at` left where it was.
1647 Zeroing it would report an empty queue when what happened is that
1648 nobody looked.
1649- **Do not do expensive work per row.** The pass runs every five minutes
1650 on the same box that serves requests. A full scan of your own
1651 collections is the intended cost; calling out to a network is not.
1652
1653### Zeros disappear
1654
1655A count of zero is stored (the absence of a row means the provider has
1656never run, which is a different fact) and **rendered nowhere**. When
1657every queue is empty the home page's ""Needs you"" band is absent entirely
1658— not ""0 pending"", not an empty panel with a heading: gone.
1659
1660This is the rule that separates an inbox from a dashboard. A board that
1661says ""0 pending approvals"" every day trains people to stop reading it,
1662and once they have stopped they do not start again on the day it says
1663three. A page that is EMPTY when nothing needs them, and short when
1664something does, gets read every time. ""Nothing needs you"" is a complete
1665and welcome answer, and blank space gives it better than any sentence
1666would.
1667
1668### Idempotency and the operator
1669
1670The same three properties `nav` has:
1671
1672- **The operator's `operator_muted` survives.** A deployment that does
1673 not work a queue mutes it (a `role:manager` update on
1674 `attention_sources`) instead of editing somebody else's manifest, and
1675 an install never writes that column. A muted source is not executed at
1676 all and its stored count is removed, so it costs nothing and shows
1677 nothing.
1678- **Unchanged means unwritten.** Every package-owned field —
1679 `object_id`, `collection`, `where`, `detail`, `label`, `path`, `nav_id`, `group`, `severity` — is
1680 compared before anything is written.
1681- **Removing an entry does not delete the row.** Deregistering never
1682 destroys.
1683
1684A **collision with another package** on an `id` blocks the install: two
1685packages writing one row is two definitions of what needs a human, and
1686whichever installed last would silently win. Unlike `nav` there is no
1687path-collision rule — two queues legitimately point at one list, and
1688blocking that would be a false blocker.
1689
1690If the `attention_sources` collection does not exist (app-nav is not
1691installed) the entries are reported as `skipped` with a reason and the
1692install proceeds, exactly as `nav` entries are.
1693
1694## Personal data: the subject export
1695
1696`action_export_subject_data` (app-privacy, admin-only) answers a subject
1697access request: everything the server holds about one email address, in one
1698document. It does not have its own list of collections. Each schema declares
1699what in it is personal, and the export folds every installed collection by
1700those declarations (three schema files, shown together):
1701
1702```text
1703{""name"": ""patients"", ""fields"": [
1704 {""name"": ""id""},
1705 {""name"": ""email"", ""subject"": ""email""}]}
1706
1707{""name"": ""appointments"", ""fields"": [
1708 {""name"": ""id""},
1709 {""name"": ""patient_id"", ""subject"": ""relation"", ""relation"": {""collection"": ""patients""}}]}
1710
1711{""name"": ""treatment_notes"", ""fields"": [
1712 {""name"": ""id""},
1713 {""name"": ""appointment_id"", ""subject"": ""relation"", ""relation"": {""collection"": ""appointments""}}]}
1714```
1715
1716- `""subject"": ""email""` — this field holds the person's email address. A row
1717 whose value is their address (case and surrounding spaces ignored) is
1718 theirs.
1719- `""subject"": ""relation""` — this relation points at a record already proven
1720 to be theirs, so the row is theirs too. Relations are followed to any depth
1721 (notes → appointments → patients), and only in that direction: from the
1722 person's own rows to rows that point at them. A relation to a shared record
1723 (a product, a fund) is not declared and is never a way in.
1724- `""subject_exempt"": ""<why>""` at the schema root — no field identifies a
1725 person (rows keyed by an anonymous visitor token, the operator's own
1726 mailboxes). The sentence is returned under `not_searchable`.
1727
1728The loader refuses any other `subject` value, and a `relation` declaration
1729without a relation, because a typo there would leave a person's records out of
1730their own request. A collection with an email-like field (a name containing
1731`email`, or `to` / `sent_to`) that declares nothing is still named in the
1732export's `not_searchable`, with `""undeclared"": true` and the fields, and is
1733not searched. `tests/test_privacy.py` fails when a shipped schema has such a
1734field and no declaration. The export also lists what it `searched`, and under
1735`unavailable` any collection a declaration points at that the box doesn't have,
1736or that could not be read.
1737
1738A box upgraded from before these keys existed keeps its installed schemas until
1739the upgrade reinstalls the packages. Until then the export names those
1740collections as undeclared rather than guessing.
1741
1742The declarations say what is personal. They say nothing about what may be
1743**erased** or how long it is **kept**. The export offers no erasure: orders,
1744invoices and payments are business records with statutory retention, and
1745deleting a row an invoice references breaks the ledger rather than
1746anonymising anyone. Which fields are contact details (redactable) and which are
1747evidence (kept), and for how long, is an open decision for the owner, to be
1748made per collection before any erasure code is written.
1749
1750## Editor Help: The DRON Schemas
1751
1752Everything a package declares (schemas, manifest, permission rules) is
1753described by JSON Schema files in `dron/`, the formal side of
1754DRON. Point an editor at them and it completes keys, shows each
1755key's description on hover, and underlines the mistakes the installer would
1756refuse (a misspelt `row_filter`, `maxlength` for `validation.max_length`,
1757`""surface"": ""private""`) before you get as far as installing.
1758
1759| File | Schema |
1760|---|---|
1761| `packages/*/schemas/*.json` | `dron/dron-collection.schema.json` |
1762| `packages/*/dbbasic-package.json` | `dron/dron-package.schema.json` |
1763| `packages/*/permissions/*.json` | `dron/dron-permissions.schema.json` |
1764
1765Two more schemas describe files that are not part of a package: the
1766deployment's own policy, `data/permissions/policy.json` (what
1767`PUT /permissions/policy` stores), by `dron/dron-policy.schema.json`, and the
1768signed envelope boxes exchange, by `dron/dron-document.schema.json`. Map them
1769the same way in your own deployment's editor settings; a box reads its own
1770policy more loosely than the schema (see `dron.md`), so run an
1771operator-written policy through the schema before saving it.
1772
1773**VS Code, no change to any package file.** In `.vscode/settings.json`:
1774
1775```json
1776{
1777 ""json.schemas"": [
1778 {""fileMatch"": [""packages/*/schemas/*.json""],
1779 ""url"": ""./dron/dron-collection.schema.json""},
1780 {""fileMatch"": [""packages/*/dbbasic-package.json""],
1781 ""url"": ""./dron/dron-package.schema.json""},
1782 {""fileMatch"": [""packages/*/permissions/*.json""],
1783 ""url"": ""./dron/dron-permissions.schema.json""}
1784 ]
1785}
1786```
1787
1788**Or per file**, a `$schema` key at the top of the file, relative to it:
1789
1790```json
1791{""$schema"": ""../../../dron/dron-collection.schema.json"", ""name"": ""invoices""}
1792```
1793
1794The loaders ignore a `$schema` key (a collection's is dropped when the schema
1795is normalized, the manifest's and a rules file's are never read), and the DRON
1796schemas allow it, so adding one never breaks an install
1797(`tests/test_dron_schema.py` proves it through the real loaders). The
1798shipped packages do not carry one: it would change every file's content hash
1799and restore-point baseline for no change in behaviour, so they rely on the
1800editor mapping above.
1801
1802`tests/test_dron_schema.py` validates every shipped file against these
1803schemas, so a file that an editor flags is a file CI flags. A fragment that
1804the schema cannot judge on its own (a `required_when` naming a field the
1805collection does not have, two nav entries with one id) is still refused by the
1806loader at install; the test lists each such case.
1807
1808## Start From A Scaffold
1809
1810```sh
1811python scripts/new_package.py app-tickets
1812python scripts/try_package.py app-tickets --user ann --user bob --brief \
1813 --call 'ann POST /collections/tickets/records {""title"": ""first"", ""owner_id"": ""ann""}' \
1814 --call 'bob GET /collections/tickets/records' --rows 'ann /tickets'
1815```
1816
1817`scripts/new_package.py <id>` (standard library, writes only the new
1818directory, refuses to overwrite one) creates `packages/<id>/` with a working
1819package: a manifest, one schema (collection name = the id without `app-`, dashes
1820to underscores; `--collection` overrides), the owner rule from the recipes
1821below, a seeded list page at `/<collection>` and a menu entry. It depends on
1822`app-nav` and `app-views` because it ships both. It installs as it stands and
1823passes `tests/test_dron_schema.py`'s checks, so every later edit starts from a
1824package that works: change one thing, run `try_package.py`, repeat. Next steps
1825are the [recipes](#recipes) (add a field, a role, a queue, a freeze), then the
1826workflow below. Pass `--dir` to write somewhere other than `packages/`; give the
1827same directory to `try_package.py --packages-dir`.
1828
1829## Authoring Workflow
1830
18311. Create the package directory and manifest (or start from the
1832 [scaffold](#start-from-a-scaffold)).
18332. Write the objects (see [`object-authoring.md`](/docs/object-authoring) for method shape, state, logs,
1834 `request[""_identity""]`, and HTML form patterns).
18353. Write each schema JSON (`{""fields"": [{""name"": ""id""}, ...]}` — see the
1836 schemas section of [`http-api-contract.md`](/docs/http-api-contract) for validation and field
1837 permission options).
18384. Seed TSV: first row is the header, tab-separated, and must include `id`.
18395. Try it before you install anywhere real:
1840 [`scripts/try_package.py`](#try-your-change) installs the package into a
1841 scratch directory and calls it as users with roles, enforcement on.
1842 Then dry-run:
1843
1844 ```http
1845 GET /packages/{package_id}?dry_run=true
1846 Authorization: Token <token>
1847 ```
1848
1849 The plan reports what would be created, replaced, merged, applied, or
1850 skipped, with warnings. Nothing is written.
18516. Install (requires `DBBASIC_ENABLE_PACKAGE_INSTALLS=true` plus the admin
1852 gate):
1853
1854 ```http
1855 POST /packages/{package_id}/install
1856 Authorization: Token <token>
1857 ```
1858
18597. Verify: run the objects, read the records, check
1860 `GET /packages/{package_id}/changes` for the install changelog, and use
1861 `POST /packages/{package_id}/restore` if the install needs to be rolled
1862 back (requires `DBBASIC_ENABLE_PACKAGE_RESTORE=true`).
1863
1864## What A Schema's `version` Does
1865
1866`""version"": 7` in a collection schema is a **label**, a whole number you
1867raise by hand. Exactly what it does:
1868
1869- It is stored and echoed: `GET /schemas/<collection>` (admin) and the schema
1870 listings report it, so a person can tell which shipped shape a box holds.
1871 It is absent from `GET /api/schema/<collection>`, the public structure-only
1872 view the generated forms read. A schema with no `version` reads as `1`; one
1873 that is not a whole number of at least 1 is refused when the schema loads.
1874- **Nothing compares it.** Install decides what to do by comparing content
1875 hashes of the shipped file, the live file and the last installed copy, so an
1876 edit you forgot to bump still installs (the number is part of the content,
1877 so a bump alone installs too, as an update). It runs no migration, rewrites
1878 no record, and does not touch a cache (the schema cache follows the file
1879 itself).
1880- On an upgrade of a customised schema (`merged`, above), fields are merged
1881 and everything else, the number included, is taken from the shipped file.
1882- It is not the schema history. `PUT /schemas/<collection>` records a numbered
1883 version of its own under `data/schema_versions/` (that is what
1884 `?versions=true` lists and what rollback restores); a package install does
1885 not write to it, and the two numbers are unrelated. A package install is
1886 undone by its restore point.
1887
1888So: raise it when you change a schema's shape, as a note to the next reader;
1889the engine does not need it. **A test must not pin the number to prove a
1890change.** Assert the fields, the rules and the views the test is about, or
1891`schema[""version""] >= N` when the history is the point. Two package tests
1892(`tests/test_app_contacts_package.py`, `tests/test_app_tasks_package.py`)
1893pinned the exact number, so every schema edit meant editing a test for no
1894reason; every `tests/test_app_*_package.py` now says `>=`. If a test of
1895yours fails only on the number after you bumped it, the test is what is wrong.
1896
1897**A failing pin on a pure addition is a test bug.** Adding a field to a
1898form, a column to `list_fields`, a value to an enum, a dependency, a second
1899permission file, a schema or a seed to a package, or bumping a version, must
1900not turn a test red. The `tests/test_app_*_package.py` files used to say
1901`forms.default.fields == [...]`, `dependencies == [{""id"": ""app-projects""}]`
1902and `package[""version""] == ""0.6.0""`, so each of those additions broke a test
1903that only meant to say ""these are still here"". They now assert what matters:
1904`tests/package_pins.py` has `assert_includes_in_order(actual, expected)` (every
1905expected member present, in the order named, extras allowed) and
1906`version_at_least`, and sets are compared with `>=`. If your addition fails an
1907exact-equality pin on a list, a set of collections or a version, relax the
1908pin the same way; do not add your value to the expected list. **Keep exact
1909equality for what must not change**: a permission rule, a `transitions`
1910target set, a hidden field, a money amount. Those are behaviour and
1911security, and an addition that touches them should fail until a person
1912decides it is intended.
1913
1914### Which version to bump
1915
1916The `version` in `dbbasic-package.json` is a different thing from a schema's:
1917the package's release, recorded in its install baseline and in the install
1918changelog. Bump it on any content change. Neither number is compared by the
1919installer (content hashes decide what changes), so these are conventions the
1920next reader relies on:
1921
1922| You changed | Package `version` | Schema `version` |
1923|---|---|---|
1924| a field added to `deals.json` (the recipe above) | `0.1.0` to `0.2.0` | `1` to `2` |
1925| only an object's code, a seeded row or a rule's `reason` | `0.2.0` to `0.2.1` | unchanged |
1926| only a permission rule or a view's blocks | `0.2.1` to `0.3.0` if behaviour changed for someone, else `0.2.2` | unchanged |
1927| a field renamed or removed, a rule tightened over rows that already exist | `0.3.0` to `0.4.0` (or `1.0.0` once you have promised stability), and say in `description` what an operator must do | `2` to `3` |
1928
1929Patch for a fix nobody has to react to, minor for something added or changed
1930that people can see, and the description for anything an operator must act on.
1931Then reinstall with `allow_replace` (an install of a package that already has
1932objects or schemas on disk is refused without it).
1933
1934## Upgrading A Package: Data, Backfill, And An Upgrade Test
1935
1936An upgrade is a reinstall of a higher version over the box's live data
1937(`allow_replace`). What it does to each layer:
1938
1939| Layer | On upgrade |
1940|---|---|
1941| records | **untouched.** Data lives outside the package, keyed by collection |
1942| the schema | replaced, or merged with the operator's local additions ([what `version` does](#what-a-schemas-version-does)) |
1943| a newly added field | old rows read **empty** for it. **There is no data backfill on upgrade:** `migrations` is parsed and refused (a package that lists one does not install), so nothing rewrites old rows for you |
1944| a `default` | fills **new writes** only, never an existing row |
1945| seed rows | merged by id; a live row an operator changed is kept |
1946
1947The recommended pattern, since nothing migrates for you:
1948
19491. **Make changes additive.** Add a field; do not rename, retype or remove one
1950 (a rename is a new field plus a backfill, with the old one left in place).
19512. **Write every reader to cope with empty.** A page, a check or a handler that
1952 reads the new field treats blank as ""the default"" (`row.get(""priority"") or
1953 ""normal""`); a `where` filter on the new field simply does not match old rows
1954 (`?priority=normal` omits them), so a filter that must include old rows
1955 waits for the backfill.
19563. **Backfill as a separate, repeatable step**, not inside the install: an
1957 admin loop of `PUT /collections/<c>/records/<id>` with the new value for
1958 each row that lacks one (it is idempotent: a second run finds nothing to
1959 do), or a one-off script using `object_records.update_collection_record`.
19604. **Only then tighten:** make the field `required`, add `required_when`,
1961 `unique` or a lock. A rule added on a field that old rows lack refuses
1962 those rows' next write until they conform ([what happens to rows already
1963 there](#add-a-field-and-show-it-in-a-list-page)).
1964
1965**Test the upgrade before you ship it.** Install the old version, write data
1966as a real person, change the package's files to the new version, install it
1967over the same data with `Sandbox.reinstall` and read the old data back. Save as
1968a pytest file in your checkout and run it from the repository root; the data
1969directory is a throwaway, nothing is left running. (`tests/test_package_recipes.py`
1970runs this exact block.)
1971
1972<!-- recipe: upgrade-test -->
1973```python
1974import json
1975import shutil
1976
1977from scripts import new_package
1978from scripts.try_package import Sandbox
1979
1980
1981def test_the_upgrade_keeps_old_rows_and_gives_new_rows_the_default(tmp_path):
1982 root = tmp_path / ""packages""
1983 for name in (""app-nav"", ""app-views""):
1984 shutil.copytree(f""packages/{name}"", root / name)
1985 new_package.create_package(""app-tickets"", packages_dir=root) # version 1
1986 records = ""/collections/tickets/records""
1987 with Sandbox([""app-tickets""], packages_dir=root) as box:
1988 box.add_user(""ann"")
1989 status, body = box.call(""ann"", ""POST"", records, {""title"": ""old"", ""owner_id"": ""ann""})
1990 assert status == 201
1991 old_id = body[""record""][""id""]
1992
1993 schema_path = root / ""app-tickets"" / ""schemas"" / ""tickets.json"" # ship version 2
1994 schema = json.loads(schema_path.read_text())
1995 schema[""fields""].append({""name"": ""priority"", ""type"": ""enum"", ""default"": ""normal"",
1996 ""enum"": [""low"", ""normal"", ""high""]})
1997 schema[""version""] = 2
1998 schema_path.write_text(json.dumps(schema))
1999 box.reinstall(""app-tickets"")
2000
2001 old = box.call(""ann"", ""GET"", f""{records}/{old_id}"")[1][""record""]
2002 assert old[""title""] == ""old"" # the row survived
2003 assert not old.get(""priority"") # and was not backfilled
2004 status, body = box.call(""ann"", ""POST"", records, {""title"": ""new"", ""owner_id"": ""ann""})
2005 assert body[""record""][""priority""] == ""normal"" # new writes get the default
2006 assert box.call(""ann"", ""GET"", records)[1][""total""] == 2
2007```
2008
2009Customisations an operator made (extra fields, edited objects, rules) survive
2010an upgrade by the three-way rules in
2011[upgrade-and-customization.md](/docs/upgrade-and-customization); test those with
2012the same pattern, making the change between the two installs.
2013
2014## Try Your Change
2015
2016A rule or a schema is only half checked by reading it; the other half is what
2017the API answers a person with that role, with permission enforcement on.
2018`scripts/try_package.py` does that in one command: it installs packages into
2019a throwaway data directory, creates users with the roles you name and an API
2020key for each, and sends the requests you list, as those users, through the
2021real application. Standard library only, no network, no port opened, nothing
2022left running; the scratch directory is removed when it finishes
2023(`--data-dir DIR` keeps the data instead).
2024
2025```sh
2026python scripts/try_package.py deals \
2027 --user ann --user bob --user carol:auditor \
2028 --call 'ann POST /collections/deals/records {""title"": ""Ann one"", ""owner_id"": ""ann""}' \
2029 --call 'ann PUT /collections/deals/records/$last_id {""title"": ""Ann 1""}' \
2030 --call 'bob GET /collections/deals/records' \
2031 --call 'carol GET /collections/deals/records' \
2032 --call 'anon GET /collections/deals/records'
2033```
2034
2035- A package name that lists `dependencies` found beside it installs those
2036 first (`app-nav`, `app-views`, ...). Other packages directories:
2037 `--packages-dir`. To see what your change did, run the same calls against the
2038 unchanged package: `git worktree add ../before HEAD` gives you the old
2039 tree, `--packages-dir ../before/packages` runs the old version while the
2040 plain command runs your edited one, and a diff of the two outputs (add
2041 `--brief`) is the behaviour change. The packages beside the one you name
2042 (its dependencies) come from the same directory.
2043- `--user NAME[:ROLE,ROLE]` makes a user. A role is just a name; a rule's
2044 `""principal"": ""role:auditor""` matches users whose roles include `auditor`.
2045 Roles live on the user record (`data/identity/users.tsv`): set them when the
2046 user is created, as here, with `POST /identity/users` (`""roles"": [...]`),
2047 with `object_identity_cli.py create-user --roles a,b`, or in Python with
2048 `object_identity.create_user({""user_id"": ""carol"", ""roles"": [""auditor""]})`.
2049 The deployment policy's `user_roles` map (`{""carol"": [""auditor""]}`, written
2050 with `PUT /permissions/policy`) assigns roles too, and the two add together.
2051 `admin` and `superuser` are the admin roles, and the admin token bypasses
2052 every rule.
2053- A call is `USER METHOD PATH [JSON]`; USER is a `--user` name, `admin` (the
2054 admin token) or `anon` (no credentials). Each answer prints as its status and
2055 JSON. `$last_id` in a path is the id of the record the previous call returned.
2056- **`--brief`** prints one line per call instead of the JSON:
2057 `ann POST /collections/deals/records -> 400 Record field 'title' is required`,
2058 the status, then the error (and its `code`, when it has one). Use it for a
2059 run of many calls; leave it off to read one full answer.
2060- **`--rows 'USER ROUTE'`** shows what a seeded page's list blocks would put on
2061 screen for that person: for each `list` block, the rows the person may read
2062 and the title and subtitle each row would carry (`title_field`,
2063 `subtitle_field`, `subtitle_label`, else the first non-empty of `title`,
2064 `name`, `label`, `subject`, `body`, `text`, `content`, `message`,
2065 `description`, `email`, then the id). Pages are drawn in the browser by
2066 JavaScript, which this does not run, so the script computes the labels with a
2067 Python copy of the list renderer's rules (a test fails if the two default
2068 orders drift apart). It checks the data and the labels, not the layout: a
2069 `table` collection prints its `list_fields` columns instead (a table ignores
2070 `title_field` and `subtitle_field`), board, tree and calendar modes are not
2071 previewed, and the search box is not reproduced. For anything visual, open
2072 the page in a browser. Example:
2073 `--rows 'ann /notes'` after `--call 'ann POST /collections/notes/records {""content"": ""hi"", ""owner_id"": ""ann""}'`.
2074- **Pages need `DBBASIC_ENABLE_SITE_ROUTES=true`.** A seeded view is served
2075 through a `site_routes` row, and routes are off by default, so without the
2076 variable `ann GET /notes` is `404 Not found`. Run
2077 `DBBASIC_ENABLE_SITE_ROUTES=true python scripts/try_package.py ...` (and
2078 start a real server with it set) to get the page. What comes back is the page
2079 shell, not the rows, which the browser fetches afterwards; `--rows` does not
2080 need the variable, because it reads the `views` records directly.
2081- **`owner_id` on a create is yours unless your role says otherwise.** Leave
2082 it out (or send your own id) and the server fills in the caller before the
2083 rules are asked, so an own-rows rule (`{""owner_id"": ""$user_id""}`) allows it.
2084 Someone else's id is refused with `403`, `""field"": ""owner_id""`, and is never
2085 rewritten: only an admin role or a rule with `""on_behalf"": true` (staff
2086 entering records for others) may create a row another user owns
2087 (docs/permissions-model.md, ""Who owns a record you create""). The server fills
2088 in only `owner_id`; any other field a rule filters on must be sent, and a
2089 create without it is answered `403 {""error"": ""no matching role rule""}`,
2090 which reads as ""no permission"" and is really ""your record does not match
2091 your own grant"".
2092- Enforcement is on; `--no-enforce` turns it off, and then only the admin token
2093 gets in. Event handlers, schedules and the attention rollup are daemon work and
2094 do not run here (they are off on a stock install too).
2095
2096From Python, for a test of your own (this is what
2097`tests/test_try_package.py` does):
2098
2099```python
2100from scripts.try_package import Sandbox
2101
2102with Sandbox([""deals""]) as box:
2103 box.add_user(""ann"")
2104 box.add_user(""carol"", roles=[""auditor""])
2105 status, body = box.call(""ann"", ""POST"", ""/collections/deals/records"",
2106 {""title"": ""Ann one"", ""owner_id"": ""ann""})
2107 status, body = box.call(""carol"", ""GET"", ""/collections/deals/records"")
2108```
2109
2110Putting your package under `packages/` also lets the DRON test check it
2111(`python -m pytest tests/test_dron_schema.py -k deals`), which finds a
2112misspelt key before an install does (the installer refuses one too).
2113
2114## What A Record Looks Like On The Wire
2115
2116Records are stored in TSV files, so **every value a record API returns is a
2117string**. This is the storage representation, not a bug in one endpoint, and it is
2118what every record surface returns today:
2119
2120```text
2121POST {""title"": ""x"", ""amount_cents"": 500, ""is_public"": true}
2122 -> {""record"": {""title"": ""x"", ""amount_cents"": ""500"", ""is_public"": ""true"", ...}}
2123```
2124
2125- **Integers and numbers** come back as `""500""`, `""5.5""`; **booleans** as
2126 exactly `""true""` or `""false""`. A field never written is absent from a
2127 single record and an empty string `""""` in a list: treat both as empty.
2128 Dates and datetimes are ISO strings.
2129- **What you may send** is looser than what you get back: a JSON number
2130 or a numeric string for an `integer` field (`500` or `""500""`; `""5.5""` is
2131 refused `400 ... must be an integer`), and for a `boolean` a JSON boolean or
2132 `""true""`, `""yes""` or `1`, which are all stored as `""true""`.
2133- **Filters and the counts that use them** compare the stored text:
2134 `?amount_cents=500` and `{""status"": ""open""}` match exactly. Ordered
2135 filters (`?amount_cents.gte=100`) parse the cell by the field's type. Never
2136 compare `""10""` and `""9""` as strings in a client; convert first.
2137- **Clients convert using the schema.** `GET /api/schema/<collection>` lists
2138 every field with its `type` (`integer`, `number`, `boolean`, `date`,
2139 `datetime`, `enum`, `text`, ...). A generic client reads it once and
2140 converts: `parseInt` for `integer` (money is integer cents; do not use
2141 floats), `value === ""true""` for `boolean`, `new Date` for dates. The shipped
2142 list and form pages read the same endpoint for their cell formatting.
2143- Responses carry a few real numbers beside the records (`total`, `count`,
2144 `limit`, `offset`); those are JSON numbers.
2145
2146`tests/test_package_recipes.py` checks each claim above against the `deals`
2147package and `app-notes`.
2148
2149## Recipes
2150
2151Four things people ask for first, each as a small change to one package,
2152`deals`, with what to expect. Create the three files, then run any recipe's
2153commands with `scripts/try_package.py` above. (`tests/test_package_recipes.py`
2154builds the package from these exact blocks and checks every result stated here,
2155so they stay true.) The first three blocks are whole files. Every later block
2156is **a fragment, and the sentence above it says which file it goes in and
2157where**: ""append to `rules`"" means add the object to that array, and ""add these
2158keys"" means merge them into the file's top-level object beside the keys that
2159are already there (a key you add that exists, such as `dependencies` or
2160`objects`, replaces it). The blocks are valid JSON on their own and are not
2161meant to be saved as a file. (Or start from the [scaffold](#start-from-a-scaffold),
2162which writes the same shape under your own names.)
2163
2164`packages/deals/dbbasic-package.json`:
2165
2166<!-- recipe: deals-manifest -->
2167```json
2168{
2169 ""id"": ""deals"",
2170 ""name"": ""Deals"",
2171 ""version"": ""0.1.0"",
2172 ""description"": ""Deals, each owned by one person"",
2173 ""compatibility"": {""dbbasic_object_server"": "">=0.1.0""},
2174 ""dependencies"": [],
2175 ""objects"": [],
2176 ""schemas"": [{""collection"": ""deals"", ""path"": ""schemas/deals.json""}],
2177 ""permissions"": [{""path"": ""permissions/rules.json""}],
2178 ""seed"": [],
2179 ""migrations"": []
2180}
2181```
2182
2183`packages/deals/schemas/deals.json`:
2184
2185<!-- recipe: deals-schema -->
2186```json
2187{
2188 ""name"": ""deals"",
2189 ""title"": ""Deals"",
2190 ""version"": 1,
2191 ""fields"": [
2192 {""name"": ""id""},
2193 {""name"": ""title"", ""type"": ""text"", ""required"": true},
2194 {""name"": ""description"", ""type"": ""textarea""},
2195 {""name"": ""status"", ""type"": ""enum"", ""enum"": [""open"", ""won"", ""lost""],
2196 ""default"": ""open"", ""transitions"": {""open"": [""won"", ""lost""]}},
2197 {""name"": ""amount_cents"", ""type"": ""integer""},
2198 {""name"": ""assigned_to"", ""type"": ""text""},
2199 {""name"": ""owner_id"", ""type"": ""text""}
2200 ],
2201 ""forms"": {""default"": {""fields"": [""title"", ""description"", ""status"", ""amount_cents"", ""assigned_to""]}},
2202 ""views"": {""list_mode"": ""table"", ""list_fields"": [""title"", ""status"", ""amount_cents""]},
2203 ""search"": {""fields"": [""title"", ""description""]}
2204}
2205```
2206
2207`packages/deals/permissions/rules.json`:
2208
2209<!-- recipe: deals-rules -->
2210```json
2211{
2212 ""rules"": [
2213 {""effect"": ""allow"", ""principal"": ""registered"",
2214 ""actions"": [""create"", ""read"", ""update"", ""delete""],
2215 ""collection"": ""deals"", ""row_filter"": {""owner_id"": ""$user_id""},
2216 ""reason"": ""people manage their own deals""}
2217 ]
2218}
2219```
2220
2221As it stands, `ann` sees and changes her own deals, and nobody else's.
2222
2223### A role reads every row while only owners write
2224
2225**Append this object to the `rules` array** in `permissions/rules.json`: the
2226role's grant has **no `row_filter`**, and a grant with no filter is every row.
2227
2228<!-- recipe: deals-auditor-rule -->
2229```json
2230{""effect"": ""allow"", ""principal"": ""role:auditor"", ""actions"": [""read""],
2231 ""collection"": ""deals"",
2232 ""reason"": ""auditors read every deal and change none""}
2233```
2234
2235Rules add up: a request is allowed when any allow rule matches, and each rule
2236brings its own row filter. So an auditor reads every row through this rule and,
2237being signed in, still owns whatever she creates through the first. With
2238`ann` (two deals), `bob` (one) and `carol` (role `auditor`):
2239
2240| Request | Answer |
2241|---|---|
2242| `ann GET /collections/deals/records` | `200`, `total: 2`, her rows |
2243| `bob GET /collections/deals/records` | `200`, `total: 1`, his row |
2244| `carol GET /collections/deals/records` | `200`, `total: 3`, everyone's |
2245| `carol GET ...records?limit=2&offset=2` | `200`, `count: 1`, `total: 3`, `has_more: false` |
2246| `carol GET ...records?owner_id=ann` | `200`, `total: 2`: filters apply after the grant |
2247| `carol GET /api/search?q=Ann&collections=deals` | `200`, Ann's deals |
2248| `carol PUT` or `DELETE` on Ann's deal | `403 no matching role rule` |
2249| `bob PUT` on Ann's deal | `403 no matching role rule` |
2250| `ann POST` with `owner_id: ""ann""`, or without it | `201`, owned by `ann`; with `""bob""`: `403` |
2251
2252Listing, paging and filtering are all done after the permission filter, so
2253`total` is the number of rows the caller may read.
2254
2255### A count over rows I own **or** am assigned
2256
2257`where` is a row filter: its entries are ANDed, and **there is no OR and no
2258NOT** (adding either is a design decision that has not been taken). Write two
2259entries, one per condition, in the manifest. A queue declared with `collection`
2260and `where` is counted **for the viewer, over the rows the viewer may read**, so
2261the second queue also needs a read grant on the assigned rows, or the assignee
2262sees 0, and a zero is never shown.
2263
2264<!-- recipe: deals-attention -->
2265```json
2266{
2267 ""dependencies"": [""app-nav""],
2268 ""attention"": [
2269 {""id"": ""deals_i_own"", ""collection"": ""deals"",
2270 ""where"": {""status"": ""open"", ""owner_id"": ""$user_id""},
2271 ""label"": ""Open deals I own"", ""path"": ""/deals"", ""group"": ""Work""},
2272 {""id"": ""deals_assigned_to_me"", ""collection"": ""deals"",
2273 ""where"": {""status"": ""open"", ""assigned_to"": ""$user_id"",
2274 ""owner_id"": {""op"": ""ne"", ""value"": ""$user_id""}},
2275 ""label"": ""Open deals assigned to me"", ""path"": ""/deals"", ""group"": ""Work""}
2276 ]
2277}
2278```
2279
2280(**Merge both keys into the top level of `dbbasic-package.json`**, replacing
2281its empty `""dependencies"": []`. `app-nav` must be installed: it owns the
2282registry the entries are written to, and without it they are skipped with a
2283note. See [the `app-nav` rule](#depend-on-app-nav).)
2284
2285The second queue excludes rows the viewer owns (`""owner_id"": {""op"": ""ne"",
2286""value"": ""$user_id""}`), so a deal that is both owned by and assigned to the
2287same person is counted **once**, in ""I own"". Without that condition it would
2288count in both queues and the badge would double-count it. (`ne` matches a deal
2289with no owner at all, and the queue still needs one literal condition, here
2290`status`.) And **append this object to the `rules` array** in
2291`permissions/rules.json`:
2292
2293<!-- recipe: deals-assignee-rule -->
2294```json
2295{""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read""],
2296 ""collection"": ""deals"", ""row_filter"": {""assigned_to"": ""$user_id""},
2297 ""reason"": ""assignees read the deals assigned to them""}
2298```
2299
2300Read the result the way the menu does: `GET /objects/action_nav_entries`,
2301as each person, and look at `attention`. With Ann owning two open deals that
2302are assigned to Bob, and Bob owning one:
2303
2304| Viewer | `attention` |
2305|---|---|
2306| `ann` | `deals_i_own` count `2` |
2307| `bob` | `deals_assigned_to_me` count `2`, `deals_i_own` count `1` |
2308| `carol` (auditor, owns none) | nothing: both queues are 0 |
2309
2310The two queues do not overlap, so the union ""owned or assigned"" is their sum
2311with nothing counted twice (a deal Bob both owns and is assigned counts once,
2312under ""I own""). Reach for a provider object (`COUNT`), below, only when the
2313rule is more than conditions can say.
2314
2315To put the number on the app list too, give the package a door: **merge this
2316`nav` key into the top level of `dbbasic-package.json`**, and add
2317`""nav_id"": ""deals""` to each of the two `attention` entries above:
2318
2319<!-- recipe: deals-nav -->
2320```json
2321{""nav"": [{""id"": ""deals"", ""label"": ""Deals"", ""path"": ""/deals"", ""group"": ""Work""}]}
2322```
2323
2324`GET /objects/action_nav_entries` then returns the Deals entry with `count` `2`
2325for `ann` and `3` for `bob` (2 assigned + 1 owned): **the badge is the sum of
2326every queue that names the door**, while `attention` keeps the two rows apart.
2327
2328### Freeze some fields once a record is settled
2329
2330`locked_when` freezes a record while its **stored** state matches `when`. Two
2331ways to say which fields stay free, and a rule uses one of them:
2332
2333- `""except"": [...]` freezes everything **except** the listed fields. Fields you
2334 add to the schema later are frozen too, which is the safe direction for money
2335 and the surprising one for a note field nobody thought about.
2336- `""fields"": [...]` freezes **only** the listed fields; every other field,
2337 including ones added later, stays editable. Use it when most of the record
2338 is allowed to keep changing. The names must be declared fields (not `id`),
2339 and a rule with both `except` and `fields` is refused at schema load.
2340
2341<!-- recipe: deals-locked-when -->
2342```json
2343{
2344 ""locked_when"": [
2345 {""when"": {""status"": [""won"", ""lost""]},
2346 ""fields"": [""title"", ""description"", ""amount_cents""],
2347 ""message"": ""A settled deal's title, description and amount are frozen.""}
2348 ]
2349}
2350```
2351
2352(**Merge that key into the top level of `schemas/deals.json`**, beside
2353`fields` and `forms`.) With a `won` deal:
2354
2355| Request | Answer |
2356|---|---|
2357| `PUT` `{""assigned_to"": ""carol""}` | `200`: not a frozen field |
2358| `PUT` `{""title"": ""late""}` | `409 {""code"": ""record_locked"", ""fields"": [""title""], ""error"": ""A settled deal's ...""}` |
2359| `PUT` `{""title"": ""<its current title>""}` | `200`: sending a frozen field back unchanged is not a change |
2360| `DELETE` | `409 record_locked`, `fields: []` (`allow_delete` defaults to `false`) |
2361| the admin token does the same `PUT` | `409`: nobody is exempt |
2362| `PUT` `{""status"": ""open""}` | `400 ... cannot move from 'won' to 'open' (allowed: none)` |
2363
2364The last row is not the lock: it is the `transitions` map. **`done`, `won`,
2365`closed` mean nothing to the platform.** A status is terminal only because it
2366has no entry in `transitions` (values missing from the map are terminal); a
2367status you can leave is a status you listed moves for. The `fields` form does
2368not name `status`, so the transitions alone decide where a settled deal may
2369go. In the `except` form you would list `status` to let the lock be left, and
2370leave it out to make the state final. Details: ""Locked when settled"" in
2371[`validation-and-logic.md`](/docs/validation-and-logic).
2372
2373### Add a field and show it in a list page
2374
2375Five places know about a field; the list page needs the first and one of the
2376next two:
2377
23781. `fields`: `{""name"": ""priority"", ""type"": ""enum"", ""enum"": [""low"", ""normal"",
2379 ""high""], ""default"": ""normal"", ""label"": ""Priority""}`. The record API accepts,
2380 validates and returns it from here. Rules a field can carry, each in
2381 [`validation-and-logic.md`](/docs/validation-and-logic): `required`, `enum`,
2382 `validation.min_length` / `max_length` / `pattern`, `validation.min` /
2383 `max` and `exclusive_min` / `exclusive_max` ([strict bounds](/docs/validation-and-logic#strict-bounds-and-conditional-required-fields)),
2384 `validation.required_when` (non-blank only while the record is in a given
2385 state, same section), and a root-level `unique` key
2386 ([uniqueness](/docs/validation-and-logic#uniqueness--declared-in-the-schema-enforced-inside-the-write-lock)).
23872. `forms.default.fields`: add `""priority""`. When a schema lists form fields,
2388 a field not listed is not on the form.
23893. `views.list_fields`: add `""priority""`. This is what the **table** list
2390 shows as columns and what the **board** shows on each card. The list page
2391 itself is a seeded view record over the schema's `views.list_mode` (see
2392 [Seeded views and site routes](#seeded-views-and-site-routes)); the plain
2393 row list (`list_mode` absent, `cards` or `feed`) and the tree and calendar
2394 modes do not show `list_fields` at all, only a title and a date. To put a
2395 field on a row list, name it as the list block's `subtitle_field`. A row
2396 with no value for that field draws no subtitle line (never a bare
2397 ""Pinned:""), and a field the schema types `boolean` reads Yes/No instead of
2398 `true`/`false` (the list generator fetches the schema for this; with
2399 `list_modes_enabled` turned off it does not, and values show as stored).
24004. `views.detail_fields`, if the schema declares one, for the detail page;
2401 `search.fields` to make it searchable text; `views.filter_fields` for a
2402 filter select (enums and booleans).
24035. Bump `version`, and reinstall with `allow_replace`
2404 (`POST /packages/deals/install` with `{""allow_replace"": true}`, or
2405 `install_package(..., allow_replace=True)` in Python): the schema comes back
2406 `updated`.
2407
2408What to expect afterwards: `GET /api/schema/deals` lists `priority` under
2409`fields` and in `views.list_fields`; a deal created from now on without a
2410priority reads `normal`; **a deal written before the change has no value** (a
2411`default` fills new writes, not old rows), so `?priority=normal` does not list
2412it. Backfill old rows with an update if the page should show a value for them.
2413A value outside the enum is refused `400 Record field 'priority' must be one of: low, normal, high`.
2414
2415**Required fields must be in every create.** A field with `""required"": true`
2416makes a create without it a `400`, and the generated form is not the only
2417caller: your `try_package.py --call` is too. On a real package:
2418
2419```sh
2420python scripts/try_package.py app-contacts --user ann --brief \
2421 --call 'ann POST /collections/contacts/records {""last_name"": ""Lee"", ""owner_id"": ""ann""}' \
2422 --call 'ann POST /collections/contacts/records {""first_name"": ""Ada"", ""owner_id"": ""ann""}'
2423# ann POST /collections/contacts/records -> 400 Record field 'first_name' is required
2424# ann POST /collections/contacts/records -> 201
2425```
2426
2427A field you make `required` later therefore breaks every caller that does not
2428send it yet; add it as optional, backfill, then require it.
2429
2430**What happens to rows that are already there when you add a rule.** None
2431is rewritten, and none is removed:
2432
2433- `unique` **compares exactly as stored, case included**: `""Acme""` and
2434 `""acme""` are two keys unless the constraint says `""ignore_case"": true`
2435 (which folds the key fields, not `scope`). Values are **trimmed** first, so
2436 `""Acme""` and `""Acme ""` are one key: trimming is leading and trailing
2437 whitespace only (Python `str.strip`), not whitespace inside the value.
2438 A blank key field means the row has no key and is exempt. Tested in
2439 `tests/test_package_recipes.py`; full rules in
2440 [validation-and-logic.md](/docs/validation-and-logic#uniqueness--declared-in-the-schema-enforced-inside-the-write-lock).
2441- `unique`: existing duplicates stay and stay editable; no further holder of
2442 the key is admitted. `object_records.find_unique_violations(collection,
2443 base_dir=...)` lists them; run it before you ship the declaration and merge
2444 or delete what it reports.
2445- `required_when`, `min` / `max`: a row that already breaks the rule stays on
2446 file but is **refused on its next write**, whatever that write changes,
2447 until it conforms ([validation-and-logic.md](/docs/validation-and-logic#strict-bounds-and-conditional-required-fields)).
2448- `locked_when`: it looks at the stored state, so a row already in a matching
2449 state is frozen from the moment the rule lands.
2450
2451## What Can't Be Declared
2452
2453Schemas, permission rules, `where` filters and seeded views say a great deal
2454without code. They do not say these, and a package that needs one is not
2455doing something wrong: it needs the tool in the right-hand column.
2456
2457| You want | Why a declaration cannot say it | Use |
2458|---|---|---|
2459| ""close date must not be in the past"", ""after its date"", ""older than X"" as a rule on a write | no schema rule, `required_when`, `locked_when` or permission filter reads the clock | a **locked check** that reads the record and the clock (below) |
2460| the same, as a **count** (""invoices over a week old"") | | an `attention` declaration with `{""op"": ""older_than_days"", ""value"": 7}` (counts only; [Declared counts](#declared-counts-collection--where)) |
2461| a status that changes **by itself** when time passes (`open` to `overdue`) | nothing runs on a record because time passed | a scheduled object in the daemon (time-driven state belongs to the daemon, [`logic-decisions.md`](/docs/logic-decisions)); a check only decides at write time |
2462| `OR` / `NOT` in a `where` or a `row_filter` | entries are ANDed. There is no OR and no NOT, by decision; do not ask a package to work around it | two entries (two queues, two rules: rules already add up), `ne` conditions for ""not one of these"", or a provider object |
2463| comparing two fields (`end_on > start_on`, `taken <= capacity`) | a bound is a constant | a locked check on the record's own fields |
2464| ""forbidden when"" (a lost deal must have **no** reason code) | `required_when` asks for non-blank, never blank | a locked check |
2465| a rule that needs rows of **other** collections (a sum against a ceiling) | | a locked check with `reads` ([Locked checks](/docs/validation-and-logic#locked-checks--a-decision-across-collections-made-inside-the-write-lock)) |
2466| `required_when` whose condition is in **another** collection (""a PO number when the deal's type says so"") | `required_when` reads only the record | stamp the condition onto the record with a hook, keep `required_when` on the stamp, and refuse a wrong stamp with a locked check ([below](#a-requirement-another-collection-decides)) |
2467| a rule about **who** may do it, that no row filter can state | | a pre-write hook, which gets the caller; a check never does |
2468
2469### A check that reads the record and the clock
2470
2471A locked check is a function the schema names and the platform calls inside
2472the write lock, for every writer (HTTP, MCP, handlers, the daemon, imports),
2473and a refusal writes nothing. This one refuses a deal whose `close_on` is in
2474the past. Three files change.
2475
2476**1. `dbbasic-package.json`**: merge this key into the top level, replacing the
2477empty `""objects"": []`:
2478
2479<!-- recipe: deals-close-date-manifest -->
2480```json
2481{""objects"": [{""id"": ""hook_deals"", ""path"": ""objects/hook/deals.py""}]}
2482```
2483
2484**2. `schemas/deals.json`**: append this field object to the `fields` array:
2485
2486<!-- recipe: deals-close-date-field -->
2487```json
2488{""name"": ""close_on"", ""type"": ""date"", ""label"": ""Close on""}
2489```
2490
2491and merge this key into the schema's top level (beside `fields`):
2492
2493<!-- recipe: deals-close-date-checks -->
2494```json
2495{
2496 ""locked_checks"": [
2497 {""name"": ""close_date"", ""object"": ""hook_deals"", ""function"": ""LOCKED_CHECK"",
2498 ""on"": {""create"": true, ""update"": [""close_on""], ""delete"": false}}
2499 ]
2500}
2501```
2502
2503**3. `packages/deals/objects/hook/deals.py`** (a new file):
2504
2505<!-- recipe: deals-close-check -->
2506```python
2507from datetime import date
2508
2509
2510def LOCKED_CHECK(request):
2511 close_on = (request.get(""record"") or {}).get(""close_on"", """")
2512 if close_on and close_on < date.today().isoformat():
2513 return {""error"": ""A deal cannot close in the past."", ""status"": 409}
2514 return None
2515```
2516
2517#### Comparing a datetime with now
2518
2519A `date` is a bare `YYYY-MM-DD` with no zone, compared above with the server's
2520local date. A `datetime` field needs three decisions, and the platform's
2521convention is **UTC**:
2522
2523- **What is stored is whatever the writer sent, if it parses.** The platform
2524 validates with `datetime.fromisoformat` after turning a trailing `Z` into
2525 `+00:00`, and stores the string as sent. So a stored value may be **aware**
2526 (`2026-07-27T09:39:00Z`, `...+02:00`) or **naive** (`2026-07-27T09:39:00`, no
2527 offset). The generated form sends UTC with a `Z` and **no fractional seconds**
2528 (the browser's `datetime-local` answer, read as the viewer's wall clock, is
2529 converted to UTC before it is sent); a server-filled `created_at` is UTC with
2530 microseconds and a `Z`. An API client may send any of them.
2531- **Comparing aware with naive raises `TypeError`.** Normalise first: read a
2532 naive value as UTC (that is the platform's own rule: attention's
2533 `older_than_days` does the same), convert an aware one to UTC, and compare
2534 with `datetime.now(timezone.utc)`.
2535- **A value you cannot parse is a check that cannot decide, so fail closed.**
2536 Do not `return None` (allow) from an `except`. Let the exception out: the
2537 platform turns any exception raised by a check into `503
2538 check_unavailable` and writes nothing. Return `{""error"": ""..."", ""status"":
2539 503}` yourself if you want your own message.
2540
2541Add a second field and a second check. Append to `fields` in
2542`schemas/deals.json`:
2543
2544<!-- recipe: deals-follow-up-field -->
2545```json
2546{""name"": ""follow_up_at"", ""type"": ""datetime"", ""label"": ""Follow up at""}
2547```
2548
2549append to the `locked_checks` array you just added:
2550
2551<!-- recipe: deals-follow-up-check-entry -->
2552```json
2553{""name"": ""follow_up"", ""object"": ""hook_deals"", ""function"": ""FOLLOW_UP_CHECK"",
2554 ""on"": {""create"": true, ""update"": [""follow_up_at""], ""delete"": false}}
2555```
2556
2557and add this to `objects/hook/deals.py`, below `LOCKED_CHECK`:
2558
2559<!-- recipe: deals-follow-up-check -->
2560```python
2561from datetime import datetime, timezone
2562
2563
2564def as_utc(text):
2565 """"""A stored datetime as an aware UTC datetime. Raises ValueError if it is not one.""""""
2566 when = datetime.fromisoformat(text.strip().replace(""Z"", ""+00:00""))
2567 if when.tzinfo is None:
2568 return when.replace(tzinfo=timezone.utc) # naive means UTC here
2569 return when.astimezone(timezone.utc)
2570
2571
2572def FOLLOW_UP_CHECK(request):
2573 text = (request.get(""record"") or {}).get(""follow_up_at"", """")
2574 if not text:
2575 return None # the field is optional
2576 if as_utc(text) <= datetime.now(timezone.utc): # an unparseable value raises: 503
2577 return {""error"": ""A follow-up must be in the future."", ""status"": 409}
2578 return None
2579```
2580
2581With that, `Z`, `+02:00` and offset-less values all compare correctly, a past
2582one is `409 check_refused`, and a value `as_utc` cannot read is `503
2583check_unavailable`, never a quiet allow.
2584
2585What to know, each verified in `object_records` and by
2586`tests/test_package_recipes.py`:
2587
2588- **A check may read the current time.** It is ordinary Python, loaded
2589 without a sandbox; the only things it may not do are write or run another
2590 object. Dates are `YYYY-MM-DD` strings, which sort in date order, and the
2591 `record` it receives holds strings (see [the wire](#what-a-record-looks-like-on-the-wire)).
2592- **`record` is the row as it will be stored** (on an update, the stored row
2593 with the changes applied); `existing` is the row on file, read under the
2594 lock (`None` on a create). Return `None` to allow, or `{""error"": ""..."",
2595 ""status"": 409}` (any 4xx) to refuse. The refusal reaches the client as `409
2596 {""code"": ""check_refused"", ""check"": ""close_date"", ""error"": ""A deal cannot
2597 close in the past.""}`.
2598- **It decides at write time only**, and only for writes `on` selects. Here
2599 `update: [""close_on""]` means a deal whose date has since passed can still
2600 have its title changed, and is judged again the moment its date is touched.
2601 A rule that must hold as time passes is not a write rule.
2602- **The object does not have to live in the same package** as the schema: it
2603 is looked up by id among the installed objects. Shipping it beside the schema
2604 is the convention, and a check in another package needs that package in
2605 `dependencies`. Install does **not** check that the object exists; a check
2606 whose object is missing refuses every write it selects with `503
2607 check_unavailable`, which is why the recipe is tried before it is shipped.
2608- A check with `reads` (other collections) also takes a lock that every write
2609 to those collections takes; a check of the record's own fields needs none
2610 and costs one `flock` round trip. Details, failure modes and cost:
2611 [Locked checks](/docs/validation-and-logic#locked-checks--a-decision-across-collections-made-inside-the-write-lock).
2612
2613### A requirement another collection decides
2614
2615""A purchase order number is required when the deal's **type** says so"" is a
2616`required_when` whose condition lives in another collection, and
2617`required_when` reads only the record. The way through, used by app-finance's
2618expense categories (`expense-substantiation.md`),
2619is to **copy the condition onto the record** and let three tools each do the
2620part only it can:
2621
26221. a pre-write hook **stamps** what the other collection says
2623 (`po_required`) on every API write, so nobody has to type it;
26242. `required_when` on the stamped field makes it **binding**, declared, for
2625 every writer;
26263. a locked check **refuses a stamp that disagrees** with the other
2627 collection, inside the write lock and for every writer, so a writer below
2628 the hook (an import, an action) cannot skip the rule by leaving the stamp
2629 out.
2630
2631The stamp is also the point-in-time record of the rule that applied
2632([`logic-decisions.md`](/docs/logic-decisions) #1). Six changes to the base
2633`deals` package.
2634
2635**1. `packages/deals/schemas/deal_types.json`** (a new file):
2636
2637<!-- recipe: deals-type-schema -->
2638```json
2639{
2640 ""name"": ""deal_types"",
2641 ""title"": ""Deal Types"",
2642 ""version"": 1,
2643 ""fields"": [
2644 {""name"": ""id""},
2645 {""name"": ""name"", ""type"": ""text"", ""required"": true},
2646 {""name"": ""requires_po"", ""type"": ""boolean"", ""default"": ""false""}
2647 ]
2648}
2649```
2650
2651**2. `dbbasic-package.json`**: merge these keys into the top level (they
2652replace `objects` and `schemas`; `deal_types` is listed first so its schema
2653exists before a deal points at it):
2654
2655<!-- recipe: deals-type-manifest -->
2656```json
2657{
2658 ""objects"": [{""id"": ""hook_deal_po"", ""path"": ""objects/hook/deal_po.py""}],
2659 ""schemas"": [{""collection"": ""deal_types"", ""path"": ""schemas/deal_types.json""},
2660 {""collection"": ""deals"", ""path"": ""schemas/deals.json""}]
2661}
2662```
2663
2664**3. `permissions/rules.json`**: append this object to the `rules` array:
2665
2666<!-- recipe: deals-type-rule -->
2667```json
2668{""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read""],
2669 ""collection"": ""deal_types"",
2670 ""reason"": ""everybody filing a deal needs to see the types and what each requires""}
2671```
2672
2673**4. `schemas/deals.json`**: append these three field objects to the `fields`
2674array:
2675
2676<!-- recipe: deals-type-fields -->
2677```json
2678[
2679 {""name"": ""deal_type_id"",
2680 ""relation"": {""collection"": ""deal_types"", ""display_field"": ""name"", ""requires"": ""read""}},
2681 {""name"": ""po_required"", ""type"": ""boolean""},
2682 {""name"": ""po_number"", ""type"": ""text"",
2683 ""validation"": {""required_when"": {""po_required"": ""true"", ""status"": [""won""]}}}
2684]
2685```
2686
2687**5. `schemas/deals.json`**: merge these keys into the schema's top level:
2688
2689<!-- recipe: deals-type-keys -->
2690```json
2691{
2692 ""hooks"": {""before_write"": ""hook_deal_po""},
2693 ""locked_checks"": [
2694 {""name"": ""po_stamp"", ""object"": ""hook_deal_po"", ""function"": ""LOCKED_CHECK"",
2695 ""reads"": [""deal_types""],
2696 ""on"": {""create"": true, ""update"": [""deal_type_id"", ""po_required""], ""delete"": false}}
2697 ]
2698}
2699```
2700
2701**6. `packages/deals/objects/hook/deal_po.py`** (a new file):
2702
2703<!-- recipe: deals-type-hook -->
2704```python
2705import os
2706
2707import object_records
2708
2709
2710def requires_po(deal_type_id, base):
2711 """"""""true"" or ""false"", as the deal type says. Raises if the type cannot be read.""""""
2712 if not deal_type_id:
2713 return ""false""
2714 row = object_records.get_collection_record(""deal_types"", deal_type_id, base_dir=base)
2715 return ""true"" if row.get(""requires_po"") == ""true"" else ""false""
2716
2717
2718def BEFORE_WRITE(request):
2719 if request[""action""] not in (""create"", ""update""):
2720 return None
2721 record = dict(request[""record""])
2722 base = os.environ.get(""DBBASIC_DATA_DIR"", ""data"")
2723 record[""po_required""] = requires_po(record.get(""deal_type_id"", """"), base)
2724 return {""record"": record}
2725
2726
2727def LOCKED_CHECK(request):
2728 record = request[""record""]
2729 wanted = requires_po(record.get(""deal_type_id"", """"), request[""base_dir""])
2730 if (record.get(""po_required"") or ""false"") != wanted:
2731 return {""error"": f""po_required must be {wanted}, as the deal type says."", ""status"": 409}
2732 return None
2733```
2734
2735With a type ""Enterprise"" (`requires_po: true`) made by an admin:
2736
2737| Request | Answer |
2738|---|---|
2739| `ann POST` a deal of that type | `201`, `po_required: ""true""` (stamped; she did not send it) |
2740| `ann PUT` `{""status"": ""won""}` | `400 Record field 'po_number' is required when po_required is true and status is won` |
2741| `ann PUT` `{""status"": ""won"", ""po_number"": ""PO-1""}` | `200` |
2742| `ann POST` a deal with no type, then `PUT` won | `200`: `po_required` is `false` |
2743| a writer below the hook creates one with `po_required: ""false""` | `CheckRefusedError` (over HTTP: `409 check_refused`), nothing written |
2744| an admin later sets `requires_po: false` on the type | deals already written keep `po_required: ""true""` until their next write through the API restamps them |
2745
2746This hook restamps on every write, which is the simple choice. app-finance's
2747expense hook restamps only when the stamp is *judged* (a new category or
2748amount, a move into submitted or approved), so an approved expense keeps the
2749rule it was approved under for good; `object_expense_rules.stamps_are_judged`
2750is that decision written down.
2751
2752The check `reads` `deal_types`, so every write to a deal type waits on the
2753same lock: a type changed in the middle of a deal's write cannot slip
2754between the check and the append. A hook that cannot read the type raises,
2755which refuses the write (fail closed); so does the check (`503`).
2756
2757### An action that is the grant
2758
2759Some actions exist to write what their caller may not write over the record
2760API. app-counter's are the example: a cashier records a payment, a credit
2761note, a refund or a waste stock move whose relation declares `requires:
2762update` on an invoice, payment or product the cashier may only read. That
2763is deliberate (giving cashiers update on invoices would let them reprice
2764and void bills), so these role-granted actions are exempt from
2765`Access.relation_refusal`: asking it would refuse the very write the action
2766is for. The action is the grant, and therefore it must check, itself, what
2767the relation check and the record API would otherwise have checked:
2768
2769- **The caller's role.** The server asks the `execute` rule only with
2770 enforcement on. Ask it inside the action too, from the rules that already
2771 name the roles (`object_corrections.staff_refusal(access, object_id,
2772 doing=...)` counts only role grants, admins and denies), so it holds with
2773 enforcement off and a plain user is refused. Where only some of the
2774 action's roles may do the expensive part, ask
2775 `object_corrections.role_grants(access, action, collection=...,
2776 record=...)`: the same role-only question for any action, with the owner
2777 fallback off, so owning the row never reads as holding the role.
2778 app-disputes' resolve action pays out only for a role that may update
2779 every dispute (manager, owner), while a cashier may close their own as
2780 `no_action`.
2781- **The record's state.** Only the states the action is for: a counter
2782 payment only for an issued invoice (not a draft, a void, a quote or a
2783 credit note) with money open, whichever way the record was named.
2784- **Scope.** Read a record whose reach the caller's own read decides (the
2785 order, the invoice) through `object_access` as the caller. Where the
2786 action itself is the grant for a record the role does not read (the
2787 product a cashier writes off), read it under the action's authority only
2788 after the role check, still honour a deny rule that names the caller
2789 (`object_corrections.denied_by_rule`), and do not widen the role's read
2790 grants to make the lookup work. Either way a refused record gets the
2791 answer a missing one gets, without echoing the id, so the action is no
2792 oracle for ids. When the action pays out of a record the caller may only
2793 read, check that the records it combines belong together: app-disputes
2794 pays out of an order only through that order's own bill and payments,
2795 of the order's own account (`orders.invoice_id` is not a validated
2796 pointer), instead of asking for an update right on the order that no
2797 staff role should hold.
2798- **Limits.** Anything the caller may do alone only up to a setting (a
2799 refund amount, a waste quantity) needs an approval above it that names
2800 the item it approves and is spent once; an approval that names no item is
2801 refused when it is written and not honoured if one is already on file.
2802 A limit that is unset or unreadable fails closed unless the shop's
2803 ordinary work needs a small default, and the description says which.
2804
2805Refuse before the first write, and say in the action's docstring which of
2806these it relies on.
2807
2808## Seeded Views And Site Routes
2809
2810Most app pages are not code. A page is a record in the `views` collection
2811whose `blocks` column says what to draw, and a row in `site_routes` that points
2812a URL at the renderer. A package ships both as seed files.
2813
2814`seed/views.tsv` (first row is the header, tab-separated):
2815
2816| Column | Meaning |
2817|---|---|
2818| `id` | the record id; unique across every package, so prefix it (`view_deals`) |
2819| `title` | required; the page heading |
2820| `route` | the path the page answers, e.g. `/deals` or `/deals/{deal_id}`. At most one `{name}` capture; that captured id is what `$record_id` means in the blocks |
2821| `layout` | `single` (default), `two_column` or `grid` |
2822| `blocks` | a JSON list of blocks, on one line (below) |
2823| `owner_id` | leave blank for a package's page |
2824| `is_public` | `true` lets anyone read the **view record**. What its blocks show is still decided by the viewer's own permissions, so a public view over private rows renders an empty frame for a stranger |
2825| `pinned` | `true` puts it in the nav app switcher |
2826| `created_at` | any timestamp |
2827
2828`seed/site_routes.tsv`:
2829
2830| Column | Meaning |
2831|---|---|
2832| `id` | the row id |
2833| `pattern` | `/deals`, `/deals/{deal_id}` or `/deals/{deal_id:uuid}` (`:uuid` only matches a UUID) |
2834| `object_id` | `site_view_render` for a view |
2835| `priority` | an integer; the lowest wins, and a tie goes to the pattern with more literal segments |
2836| `host` | optional; the row applies to that host only |
2837
2838```text
2839id pattern object_id priority
2840route_deals /deals site_view_render 20
2841route_deals_detail /deals/{deal_id} site_view_render 10
2842```
2843
2844```text
2845id title route layout blocks owner_id is_public pinned created_at
2846view_deals Deals /deals single [{""kind"": ""list"", ""collection"": ""deals"", ""search"": true, ""sort"": true, ""add"": true, ""owner_scoped"": true, ""title_field"": ""title"", ""add_label"": ""+ New Deal""}] true false 2026-01-01T00:00:00
2847view_deals_detail Deal /deals/{deal_id} single [{""kind"": ""detail"", ""collection"": ""deals"", ""record_id"": ""$record_id"", ""editable"": true, ""deletable"": true, ""delete_redirect"": ""/deals""}] true false 2026-01-01T00:00:00
2848```
2849
2850To wire them in: add both seed files to the manifest (`{""collection"": ""views"",
2851""path"": ""seed/views.tsv""}` and the same for `site_routes`), list `app-views` in
2852`dependencies` (it ships the `views` schema and the `site_view_render` object,
2853and it is not installed for you), and run the server with
2854`DBBASIC_ENABLE_SITE_ROUTES=true` (routes are off by default; see
2855[`site-routing.md`](/docs/site-routing)). Each view's `route` and its
2856`site_routes` row must say the same pattern: the renderer finds the view by
2857matching the request against the views' `route` columns. Two reminders: a
2858changed row of a shipped view reaches boxes that already have it by the rule
2859in the next section (keep the `id`), and the TSV cannot hold a tab or a
2860newline inside `blocks`, so keep each block list on one line.
2861
2862### Changing a seeded row in a new version
2863
2864Keep the row's `id`, put the new value in the seed file, bump the package
2865`version` and reinstall as for any upgrade (`allow_replace`). Do **not** add a
2866second row for the same route: two views answering one `route` collide, and
2867the renderer takes the first it finds. The install decides **column by column**, so a
2868box's own edits are never lost:
2869
2870- At every install it records, for each seeded row and column, a hash of what
2871 the package shipped and of what the row held right after it was written
2872 (`data/package_baselines/<package>.json`, key `seed_rows`; hashes, never
2873 the values). `id`, `created_at` and `updated_at` are not tracked.
2874- A column the new version changed, whose live value is still what the last
2875 install wrote, is **replaced**. The seed entry of the install result lists
2876 those ids under `replaced`, and its `status` is `merged`.
2877- A column the new version changed, whose live value is something else (an
2878 operator edited it through the API or a form), is **kept**. It is listed
2879 under `kept` (`id`, `columns`, `reason: ""edited""`) and as a warning in the
2880 result, and the install goes on. The same column the package did *not*
2881 change is never touched, edited or not, and says nothing.
2882- A box installed before rows were tracked has no baseline, and an edit looks
2883 exactly like an old default. A row there that already equals the new value
2884 is adopted silently; one that differs is **kept** with `reason: ""no
2885 baseline""`. Once it matches (edit it by hand, e.g. `PUT
2886 /collections/views/records/view_notes` with the new `blocks`, or delete it
2887 and reinstall so the shipped row comes back) later versions flow.
2888- A row the collection refuses to update is kept with the refusal's code, and
2889 never fails the install.
2890
2891Example: `view_notes` ships `[{""kind"": ""list"", ""collection"": ""notes""}]`. Version
28920.2.0 adds `""subtitle_field"": ""owner_id""` to its `blocks`. A box that never
2893touched the row gets the new `blocks` on reinstall; a box whose operator
2894retitled the page keeps that title and still gets the new `blocks`; a box
2895whose operator rewrote `blocks` keeps theirs and the install says so. A page
2896and its route are two seed rows (`views` and `site_routes`): if you change a
2897`route`, change both, and each is decided on its own. A row removed from the
2898seed file stays on boxes that have it, and a row an operator deleted is
2899added back by the next install, as before. `tests/test_seed_row_upgrade.py`
2900runs every case above. Check what your own change does with `--rows` (see
2901[Try Your Change](#try-your-change)) on a box built from the old version.
2902
2903**Blocks.** `kind` is one of `list`, `form`, `detail`, `related`, `thread`,
2904`count`, `aggregate`, `markdown`, `reader`, `object`. An unknown kind or key is
2905not an error at runtime, it is a placeholder card or silently ignored, so check
2906them with the DRON schema instead: `dron/dron-view.schema.json` describes every
2907kind and option with a sentence each, and `tests/test_dron_schema.py` validates
2908every shipped `views.tsv` against it, and every `site_routes.tsv`, so a
2909misspelt option fails there (`python -m pytest tests/test_dron_schema.py -k
2910deals`). The `list` block's options:
2911
2912| Option | Does |
2913|---|---|
2914| `collection` | required |
2915| `title` | a heading above the list |
2916| `search` | `true`: a search box (text search over the schema's `search.fields`) |
2917| `sort` | `true`: a Newest/Oldest select; `""oldest""` starts oldest first; always by `created_at` |
2918| `sort_by`, `sort_dir` | sort by this field instead, `asc` or `desc` (default `desc`) |
2919| `add`, `add_label` | `true`: a button that opens the generated create form |
2920| `owner_scoped` | `true`: ask only for the viewer's own rows. A request, not access control |
2921| `where` | a standing narrowing, `{field: ""value""}`, equality only, applied after the permission filter; keeps the table, filter bar and realtime |
2922| `title_field`, `subtitle_field`, `subtitle_label` | which fields label a row (default: the first of `title`, `name`, `label`, `subject`, `body`, `text`, `content`, `message`, `description`, `email`, then the id) |
2923| `href_template`, `href_field` | where a row title links, when not `/<collection>/<id>` |
2924| `row_actions: false`, `link: false` | no edit/delete buttons, no detail link: for logs and reports |
2925| `row_limit` | rows drawn before ""Show all"" (default 50) |
2926| `filters`, `limit` | **avoid**: they swap in a bare list of titles with none of the above. Use `where` and `row_limit` |
2927
2928**Which list modes show `list_fields`.** The mode is `views.list_mode` in the
2929collection's schema, not in the block.
2930
2931| `list_mode` | Shows |
2932|---|---|
2933| `table` | one column per `views.list_fields` entry (every field when none is listed), relation columns by label, headers sort |
2934| `board` | cards grouped by an enum (`views.board.group_field`; default the schema's `flow` field, else the first enum with `transitions`, else the first enum), each card's extra lines from `views.board.card_fields` else `views.list_fields`; a collection with `list_fields` also gets a Board / Table toggle |
2935| `tree` | a title per node, nested by `views.tree.parent_field` (default `parent_id`); **no `list_fields`** |
2936| `calendar` | a title per day, by `views.calendar.date_field`; **no `list_fields`** |
2937| absent, `cards`, `feed` | rows of avatar, title, created date and tags, plus the block's `subtitle_field`; **no `list_fields`** |
2938
2939A mode whose field cannot be found (no enum for a board, no self-relation for a
2940tree) falls back to the row list with a notice. `views.filter_fields` (enum and
2941boolean fields) adds a filter bar above every mode.
2942
2943## Semantics At A Glance
2944
2945Small facts that were guessed at, in one place. The fuller account is linked.
2946
2947- **`older_than_days: N` is inclusive**: a row matches when its age is `N` or
2948 more days (`age >= N`). A date-only value (`2026-11-20`) ages in calendar days
2949 against the server's local date, so a date `N` days back matches today; a
2950 datetime ages in elapsed whole days. A blank, unparseable or future value
2951 never matches. (""Due before today"" is `older_than_days: 1` on a date.)
2952 [Declared counts](#declared-counts-collection--where).
2953- **`unique` compares trimmed values and ignores blank ones.** `""evt-1""` and
2954 `""evt-1 ""` collide; a record whose key field is blank has no key. A violation
2955 is `409 {""code"": ""unique_violation"", ""error"": <your `message`, else a
2956 generated sentence>, ""fields"": [...], ""scope"": [...]}`; the id of the
2957 record holding the key is not returned. `ignore_case` is opt-in.
2958 ([`validation-and-logic.md`](/docs/validation-and-logic#uniqueness--declared-in-the-schema-enforced-inside-the-write-lock))
2959- **`locked_when` refuses with `409 record_locked`**, and `fields` lists the
2960 frozen fields the write tried to change (`[]` for a delete). `allow_delete`
2961 defaults to `false`: a settled record cannot be deleted. Judged by the stored
2962 record, for every writer, the admin token included.
2963- **No status means ""done"".** Only the `transitions` map says where a value may
2964 go; a value with no entry is terminal. `done`, `closed`, `won` are your words.
2965- **Roles are assigned on the user** (`roles` when the user is created) and in
2966 the policy's `user_roles`; rules match them as `role:<name>`.
2967 [Try Your Change](#try-your-change).
2968- **Schema validation of your package** is `tests/test_dron_schema.py`, with no
2969 `jsonschema` package needed. **Searching** is `GET /api/search?q=...&collections=<c>`;
2970 `GET /collections/<c>/records` takes `limit`, `offset` and field filters
2971 (`field=value`, `field.op=value`; ops `eq ne in gte lte gt lt`), and
2972 `?search=ann` is refused `400` as an unknown field. `q` and `sort` are
2973 reserved there and ignored.
2974
2975## A Minimal Working Example
2976
2977`packages/hello-world/` in this repository is the smallest complete package.
2978`packages/admin-write-probe/` is the smallest complete *app-shaped* package:
2979one HTML page object, one schema, one seed file, exercising records end to
2980end. `packages/app-projects/` and `packages/app-notes/` are the reference
2981*user apps*: an owner-scoped schema with `search` metadata, permission
2982rules granting signed-in users their own rows (`row_filter` on
2983`$user_id`), and a signed-in page that reads and writes records with the
2984visitor's session cookie. Start a new app package from `app-notes`.
2985
2986`app-notes` also shows the public/private pattern: a boolean `is_public`
2987field plus a second permission rule (`principal: public`, `row_filter:
2988{""is_public"": ""true""}`) makes shared records readable by anyone across
2989every surface — pages, records API, MCP, and search — with no
2990visibility code in the app itself. Its permalink page (`site_note_view`)
2991expects a `site_routes` record mapping `/notes/{note_id:uuid}` to it;
2992route records are site data, so each deployment adds them next to its
2993other routes.
2994
2995Object files inside packages are normal DBBASIC objects. A package page that
2996renders per-user content reads `request[""_identity""]`; a package form posts to
2997its own object id and writes records through the object runtime. Signed-in
2998browser users carry their session cookie automatically.
2999
3000## Rules For Generated Packages
3001
3002- Never put secrets, tokens, real hostnames, or private paths in package
3003 content — packages are meant to be shareable source.
3004- Keep one package per app primitive; use `dependencies` to declare (not yet
3005 resolve) cross-package needs.
3006- Bump the manifest's `version` on any content change so install changelogs and
3007 restore points stay meaningful. (A schema's own `version` is a label, not a
3008 switch: [what it does](#what-a-schemas-version-does).)
3009- Prefer seed data that demonstrates the schema without pretending to be real
3010 data.
3011- Dry-run output is the review artifact: a package that cannot explain itself
3012 in a dry-run plan is not ready to install.
3013"
3014schema-forms Schema Field Contract: Generated Forms and Views Building on DBBASIC 220 How one schema document drives desktop forms, web forms, MCP agents, and record-write validation from the same declared field semantics. "This is the contract that lets user interfaces generate themselves from
3015schemas. One schema drives every surface at once: Scroll's desktop forms, a
3016server-rendered web form, an agent reading constraints over MCP, and the
3017record-write APIs enforcing the same rules for all of them.
3018
3019The governing principle: **schemas declare semantics, never widgets.** A
3020field says ""one of these values"" or ""points at a projects record"" — each
3021interface maps that meaning onto its own idiom (a dropdown, a picker, a
3022JSON constraint, a spoken prompt). New kinds of interface plug in later
3023without touching the data.
3024
3025Everything here is enforced by the server on record writes today. None of
3026it is a DSL — it is keys in the schema JSON document, checked by explicit
3027code, versioned and rolled back through the normal schema history.
3028
3029## Field Keys
3030
3031```json
3032{
3033 ""name"": ""urgency"",
3034 ""type"": ""enum"",
3035 ""required"": true,
3036 ""label"": ""Urgency"",
3037 ""help"": ""How soon this needs attention"",
3038 ""placeholder"": ""Choose…"",
3039 ""default"": ""normal"",
3040 ""enum"": [""low"", ""normal"", ""high"", ""critical""]
3041}
3042```
3043
3044- `name` — required; letters/digits/underscores.
3045- `type` — `text` (default), `textarea`, `integer`, `number`, `boolean`,
3046 `date`, `datetime`, `enum`, `computed`. Types are validated on write
3047 (integers must parse, dates must be ISO, enums must match, and so on).
3048 Boolean fields accept several spellings on input (`True`, `1`, `yes`)
3049 but are stored canonically as `true`/`false`, so permission row
3050 filters like `{""is_public"": ""true""}` match reliably.
3051- `required` — empty values rejected on write.
3052- `label`, `help`, `placeholder` — presentation text for generated forms.
3053- `default` — filled in when the field is not submitted.
3054- `enum` — allowed values; writes outside the list are rejected. Renders as
3055 a dropdown/segment control in form UIs.
3056- `computed` / `read_only` — the server rejects client writes to these
3057 fields; forms render them display-only.
3058- `transitions` — for lifecycle fields, which values each current value
3059 may move to. Enforced on record update; values missing from the map
3060 are terminal. (`done`, `closed`, `won` mean nothing to the platform: a
3061 status is final only because nothing lists a move out of it.) This is data plus one check, not a state machine
3062 framework — no hooks, no callbacks, no side effects:
3063
3064 ```json
3065 {""name"": ""status"", ""type"": ""enum"",
3066 ""enum"": [""open"", ""assigned"", ""done""],
3067 ""transitions"": {""open"": [""assigned""], ""assigned"": [""done"", ""open""]}}
3068 ```
3069
3070 Form UIs can offer only the moves allowed from the record's current
3071 value; the server rejects everything else either way.
3072
3073 A list entry can also be a guarded object instead of a plain string,
3074 adding *who* on top of *whether*:
3075
3076 ```json
3077 {""transitions"": {
3078 ""assigned"": [{""to"": ""open"", ""when"": {""assigned_to"": ""$user_id""}}]
3079 }}
3080 ```
3081
3082 The move is allowed only once every `when` clause matches the record's
3083 current stored values against the resolved subject variable
3084 (`$user_id`, `$account_id`, `$accessible_projects`, `$owned_projects`,
3085 `$writable_projects`) or a literal string — the same closed set and
3086 matching rules row filters use (see `docs/permissions-model.md`). Guards
3087 are only evaluated where a request subject is available (the HTTP
3088 update path); direct library callers still get the plain validity
3089 check (the move's `to` must be in the list) but not the guard.
3090- `relation` — a validated pointer to another collection:
3091
3092 ```json
3093 {""name"": ""project_id"", ""relation"": {""collection"": ""projects"", ""display_field"": ""name""}}
3094 ```
3095
3096 On write, the value must be an existing record id in that collection
3097 (`projects/p999` missing → 400). `display_field` tells form UIs which
3098 field of the target record to show in pickers. A bare string
3099 (`""relation"": ""projects""`) is shorthand. This is deliberately a pointer
3100 plus a display hint, not an association framework — no joins, no lazy
3101 loading, no cascades. `""requires"": ""read""` or `""update""` makes an API
3102 writer prove they may see (or act on) the record the pointer names
3103 before the write lands; see ""Pointing at a record you may not act on"" in
3104 docs/permissions-model.md.
3105- `validation` — explicit bounds, all enforced on write:
3106
3107 ```json
3108 {""validation"": {""min_length"": 3, ""max_length"": 80, ""pattern"": ""^[a-z-]+$"", ""min"": 0, ""max"": 100}}
3109 ```
3110
3111 `pattern` is **full-matched** against the whole value (`re.fullmatch`),
3112 not searched — so it must describe the entire field, not a prefix. A URL
3113 check is `^https?://\S+$`, not `^https?://` (that would only match the
3114 literal scheme and reject every real URL). The `^`/`$` anchors are
3115 therefore redundant but fine to keep for readability.
3116 A pattern is written in the DRON dialect, a subset Python and JavaScript
3117 read alike: no lookbehind, named groups, inline flags (`(?i)`),
3118 backreferences or `\b`; `\d` and `\w` are ASCII. A package with a pattern
3119 outside it is refused at install with what to write instead. See
3120 ""Regular expressions"" in dron.md.
3121
3122## Schema Root Keys
3123
3124Presentation metadata lives beside the fields and versions with them —
3125Scroll's ""Save Layout"" persists here, so form design has history and
3126rollback like source code:
3127
3128```json
3129{
3130 ""fields"": [...],
3131 ""forms"": {
3132 ""default"": {""fields"": [""title"", ""description"", ""project_id"", ""urgency"", ""due_date"", ""assigned_to""]}
3133 },
3134 ""views"": {
3135 ""list_mode"": ""table"",
3136 ""list_fields"": [""title"", ""urgency"", ""due_date"", ""assigned_to""]
3137 }
3138}
3139```
3140
3141- `forms.default.fields` — field order for the generated record form.
3142 Additional named forms can define alternate layouts.
3143- `views.list_mode` — how the generated list renders. The shared list
3144 renderer (`window.dbbasicList`) resolves it from the schema:
3145 - `table` — a dense, sortable HTML table over `list_fields`; cells format by
3146 type (money `_cents`, boolean, relative dates, enum badges), and relation
3147 columns show the target's label, not the raw id.
3148 - `board` — a kanban grouped by an enum field, drag-to-transition (the drag
3149 issues the ordinary status write, so `flow` transitions still gate it). A
3150 board collection that also has `list_fields` gets a **Board ⇄ Table**
3151 toggle (the choice persists per collection).
3152 - `tree` — nests a self-relation (`parent_id`) into a hierarchy.
3153 - `calendar` — buckets by a date field.
3154 - absent / `cards` / `feed` — the plain rich-row list.
3155
3156 Every mode shares one fetch/sort/cap/search/realtime pipeline, so all of
3157 them inherit filtering, the 50-row cap, and live updates. A mode whose
3158 required field can't be derived falls back to the row list with a visible
3159 notice — never a blank page.
3160- `views.list_fields` — the columns of a `table` list and the extra lines on
3161 each `board` card (a board's own `views.board.card_fields` wins). **Only those
3162 two modes use it**: the plain row list (`list_mode` absent, `cards` or
3163 `feed`), `tree` and `calendar` show a title (and, for rows, a created date)
3164 and ignore it; a row list takes its title and subtitle from the view block's
3165 `title_field` and `subtitle_field` instead. Relation fields resolve to the
3166 referenced record's label. To add a field to a list page, see the recipe in
3167 [`package-authoring.md`](/docs/package-authoring#add-a-field-and-show-it-in-a-list-page).
3168- `views.filter_fields` — fields to expose as a **filter bar** above the list
3169 (enum → a select of its options, boolean → Yes/No). A pick narrows the fetch
3170 server-side (`field=value`, after the permission row filter) and composes
3171 with the search box; works in every mode.
3172- `search` — opts the collection into global search (`GET /api/search`
3173 and the `global_search` MCP tool):
3174
3175 ```json
3176 {""search"": {""fields"": [""title"", ""content""], ""result_fields"": [""id"", ""title""]}}
3177 ```
3178
3179 `fields` are the searchable fields; `result_fields` (optional) trims
3180 what each search hit returns, defaulting to `id` plus
3181 `views.list_fields`. Collections without a `search` section never
3182 appear in search results. Search runs inside the permission engine, so
3183 row filters and field permissions bound what any caller can find.
3184- `formula` / `rollup` (on a `type: computed` field) — derived values,
3185 materialized on write: a formula computes from sibling fields
3186 (`""first_name + \"" \"" + last_name""`); a rollup aggregates a child
3187 collection (`{""collection"": ""fin_journal_lines"", ""fk_field"": ""journal_id"",
3188 ""op"": ""sum"", ""field"": ""debit_cents""}`). Stored like any field, so every
3189 view/filter/sort sees them; kept current by the write path. See
3190 [`validation-and-logic.md`](/docs/validation-and-logic).
3191- `capabilities` — generic per-collection *behaviors* on top of this display
3192 layer: `{""comments"": true}`, `{""attachments"": true}`, `{""shareable"": true}`
3193 grow a comment thread, attachment list, and owner-checked sharing on the
3194 detail page from one flag each. See [`capabilities.md`](/docs/capabilities).
3195
3196## Worked Example: tasks
3197
3198The acceptance test for this contract is Scroll's New Task screen,
3199expressed entirely as data:
3200
3201```json
3202{
3203 ""fields"": [
3204 {""name"": ""id""},
3205 {""name"": ""title"", ""type"": ""text"", ""required"": true, ""label"": ""Title"",
3206 ""validation"": {""min_length"": 1, ""max_length"": 200}},
3207 {""name"": ""description"", ""type"": ""textarea"", ""label"": ""Description""},
3208 {""name"": ""project_id"", ""label"": ""Project"",
3209 ""relation"": {""collection"": ""projects"", ""display_field"": ""name""}},
3210 {""name"": ""urgency"", ""type"": ""enum"", ""label"": ""Urgency"", ""default"": ""normal"",
3211 ""enum"": [""low"", ""normal"", ""high"", ""critical""]},
3212 {""name"": ""due_date"", ""type"": ""date"", ""label"": ""Due Date""},
3213 {""name"": ""assigned_to"", ""label"": ""Assigned To"",
3214 ""relation"": {""collection"": ""users"", ""display_field"": ""display_name""}}
3215 ],
3216 ""forms"": {""default"": {""fields"": [""title"", ""description"", ""project_id"",
3217 ""urgency"", ""due_date"", ""assigned_to""]}},
3218 ""views"": {""list_mode"": ""table"",
3219 ""list_fields"": [""title"", ""urgency"", ""due_date"", ""assigned_to""]}
3220}
3221```
3222
3223A form renderer walks `forms.default.fields`, looks up each field's
3224semantics, and emits the right control. The record POST enforces every
3225rule the form promised — and the same rules bind a record created over
3226MCP or raw HTTP, so no surface can bypass what another surface displays.
3227"
3228business-logic-patterns Business Logic Patterns: Where Every Rule Goes Building on DBBASIC 230 A placement guide and decision procedure for where each kind of business rule belongs in the primitive stack, illustrated with worked examples from tax, aging, dunning, refunds, inventory, and bank reconciliation. "Every business rule has one correct home in the primitive stack. This page is
3229the placement guide: the decision procedure, the map, and four worked examples
3230(sales tax, payment aging, dunning, refunds) that most systems get wrong.
3231The placement *decisions* and their reasons accumulate in
3232[`logic-decisions.md`](/docs/logic-decisions), the way UI behavior accumulates in
3233[`ui-decisions.md`](/docs/ui-decisions).
3234
3235The method behind all of it (see logic-decisions #4): build each module's
3236rules **concretely** in the cheapest correct primitive — a hook is three lines
3237of real code — and only promote a pattern to a declarative schema key after it
3238has repeated in two or three real modules. Concrete → pattern → primitive,
3239never primitive-first. Systems that build the workflow/rules engine first die
3240when reality doesn't fit it; ours extracts engines from reality.
3241
3242## Where does this rule go?
3243
3244```mermaid
3245flowchart TD
3246 Q[""a business rule""] --> D1{""Derivable from<br/>stored data?""}
3247 D1 -->|same record| F[""formula field""]
3248 D1 -->|child records| R[""rollup field""]
3249 D1 -->|no| D2{""Does it GATE<br/>a write?""}
3250 D2 -->|shape / bounds / FK| V[""schema validation""]
3251 D2 -->|legal state moves + who| T[""transitions + when guards""]
3252 D2 -->|cross-record or computed gate| H[""pre-write hook<br/>(reject or stamp)""]
3253 D2 -->|no| D3{""Does TIME<br/>cause it?""}
3254 D3 -->|yes| DM[""daemon: scheduled pass /<br/>auto-transition""]
3255 D3 -->|no| D4{""Is it a REACTION<br/>to a change?""}
3256 D4 -->|notify / email| N[""notify_rules (after write)""]
3257 D4 -->|run code| TR[""trigger → target object""]
3258 D4 -->|external system| C[""connector<br/>(desired state + reconcile)""]
3259 D4 -->|no| O[""plain object<br/>(page / API / worker)""]
3260```
3261
3262## The placement map
3263
3264| Kind of rule | Primitive | Lives in | Example |
3265|---|---|---|---|
3266| Shape, type, bounds, enum, FK-exists | schema validation | `object_records` write path | amount is integer cents; project must exist |
3267| Same-record derivation | `formula` (materialized) | `object_computed` via `object_records` | `tax_cents = amount_cents * tax_rate` |
3268| Aggregation over children | `rollup` (materialized, live) | same | `invoice.paid_cents = sum(payments)` |
3269| Legal state moves, and who may move | `transitions` + `when` | `object_records` | `draft → posted`, owner only |
3270| A value that may appear once (a key, a code, an idempotency marker) | schema `unique` | `object_records`, **inside the write lock**, every writer | one usage event per `event_id` per owner; a `generated_from` marker used once |
3271| A sum that must not pass a ceiling, or any rule that reads other collections, under overlapping writes | schema `locked_checks`: a read-only function + the collections it `reads` + a named `lock` | `object_records`, **inside the write lock and the check lock**, every writer | payments ≤ invoice, refunds ≤ payment (`ledger` lock); nothing written into a closed period (`fin_periods` lock) |
3272| A record that is settled: frozen fields, no delete | schema `locked_when` | `object_records`, **inside the write lock**, every writer | approved time may change only `status`, `invoice_id`, `notes` |
3273| Cross-record gate, computed gate, point-in-time stamp | **pre-write hook** | `hooks.before_write` → `object_server` write path | journal must balance; stamp `tax_rate` |
3274| Time-driven state | daemon scheduled pass / `after_hours` auto-transition | `object_daemon` | `sent → overdue` when past due |
3275| Reaction: notify, email | `notify_rules` | daemon, **after** the write | dunning email on `overdue` |
3276| Reaction: run code | trigger → target object | daemon | recompute, follow-on records |
3277| External side effect | connector | desired-state records + reconcile | payment-provider refund call |
3278| Correction to money / inventory | append-only compensating record | `storage: append` collections | refunds, stock moves, journal reversals |
3279| Everything else | a plain object | anywhere | bespoke report, integration, one-off page |
3280
3281Two hard boundaries hold the map together:
3282
3283- **Gates before the write; reactions after.** A hook may reject or stamp but
3284 never send email or call out — a gate with side effects leaks that a write
3285 was attempted and couples saves to SMTP. A reaction may notify or spawn work
3286 but never block the write that already happened.
3287 ([`event-hooks-decisions.md`](/docs/event-hooks-decisions))
3288- **Derived values are non-authoritative; gates are authoritative.** A broken
3289 formula stores `""""` and the write succeeds; a broken hook fails closed and
3290 the write is rejected. Never let a gate read only a derived value it could
3291 recompute — the journal-balance hook sums the lines itself even though
3292 rollup totals exist.
3293
3294One placement the map gets wrong if read quickly: **""has this already been
3295written?"" is not a hook.** A hook that looks for an existing row runs before
3296the write lock, so two overlapping writes both find nothing; and handlers and
3297scheduled jobs write below the hook entirely. Declare the key `unique`
3298([`validation-and-logic.md`](/docs/validation-and-logic)) and let the writer
3299that loses catch `UniqueConstraintError`.
3300
3301## Worked example 1: sales tax (the one everyone leaves out)
3302
3303Why it's left out: it hides a doctrine most systems never articulate —
3304**stamp point-in-time facts; derive live facts** (logic-decisions #1).
3305The tax *rate* is a fact about the transaction moment: rates change, and the
3306invoice must forever carry the rate it was issued under.
3307
33081. **Rates are data**: a `tax_rates` collection — `region`, `category`,
3309 `rate`, `valid_from`. Editable like any records; history visible.
33102. **Stamping is a hook**: `hooks.before_write` on invoice lines looks up the
3311 applicable rate and *stamps* `tax_rate` onto the line — same posture as the
3312 server stamping `owner_id`. The client never supplies it; later rate
3313 changes never rewrite history.
33143. **Amounts are formulas/rollups**: `line.tax_cents = amount_cents *
3315 tax_rate` (formula); `invoice.tax_total_cents` (rollup). Materialized, so
3316 they appear on every list/detail/report and update live.
3317
3318## Worked example 2: payment aging (time makes the state)
3319
3320The trap: an invoice becomes overdue with **no write happening** — time did
3321it. Any system that computes ""is it late?"" ad hoc in the UI grows a dozen
3322disagreeing copies of that check.
3323
33241. `balance_cents` is a **rollup** (`total_cents` minus `sum(payments)`).
33252. `sent → overdue` is a **daemon scheduled pass** through the ordinary
3326 transition machinery, when `due_date < today` and `balance_cents > 0` —
3327 so the state is *stored*, permission-checked, realtime-pushed, and every
3328 surface agrees (logic-decisions #2: time-driven state belongs to the
3329 daemon, never to read-time checks).
33303. Aging buckets (30/60/90) are a rollup/report over stored state.
3331
3332## Worked example 3: dunning (reactions compose on state)
3333
3334Dunning is nothing new — it is the composition of the two layers above:
3335
33361. The daemon flips the state (`overdue`, later `overdue_30`, …).
33372. `notify_rules` reacts: state change → email template to the invoice's
3338 contact. The rule is data; the daemon delivers after the write.
33393. Escalation (""again at 30 days unless paid"") is *more time-driven state*,
3340 not a special notification feature — each escalation step is a transition
3341 the daemon makes, each with its own notify rule.
3342
3343## Worked example 4: refunds (money moves, never mutates)
3344
3345**Money never mutates; it moves** (logic-decisions #3). A refund is not an
3346edit to a payment — it is a new, append-only compensating record, exactly like
3347a stock move or a journal reversal.
3348
33491. `refunds` is an `storage: append` collection pointing at the payment.
33502. The invariant is a **hook**: `refund ≤ payment − prior refunds` — a
3351 cross-record gate, summed from the records themselves.
33523. `payment.refunded_cents` / `net_cents` are **rollup/formula** — display
3353 truth, derived.
33544. ""Correctly credited"" is the balanced journal entry the refund composes —
3355 enforced by the journal-balance hook that already ships. The chain closes:
3356 append-only record → hook invariant → rollup display → balanced books.
3357
3358## Worked example 5: inventory shrinkage (the events nobody codes for)
3359
3360Waste, breakage, theft, expiry, damage, disaster: systems are easy to build
3361when quantities just flow buy → stock → sell; real usage is losses. Naming
3362them is the point — ""adjustment"" is the euphemism that hides exactly what
3363operators and auditors need to see.
3364
33651. **Losses are movements** (logic-decisions #3): a loss is an append-only
3366 stock move with a loss `reason`, out of a location, to nowhere — never an
3367 edit to an on-hand number (levels stay derived).
33682. **The hook stamps and gates**: `unit_cost_cents` is stamped from the
3369 product at the moment of movement (#1 — tomorrow's cost edit must not
3370 reprice yesterday's loss); a loss must leave a real location and can have
3371 no destination.
33723. **The composer books the shadow**: a loss move composes a posted journal —
3373 DR shrinkage-expense / CR inventory-asset — with per-reason account
3374 overrides as settings (theft to its own account for the insurance claim).
33754. **Count reconciliation is the same machinery**: a physical count writes
3376 one compensating adjustment move for the variance (out for shortage, in
3377 for overage) plus the mirror journal. The count is an *event*, not an
3378 edit.
3379
3380This was also the composer pattern's third repeat, which triggered the
3381doctrine-#4 extraction: every generated journal now goes through
3382`object_finance.compose_posted_journal` (idempotent by `generated_from`,
3383verify-then-post), and the payment/refund/recurring/reversal composers
3384shrank onto it.
3385
3386## Worked example 6: bank reconciliation (evidence, not data entry)
3387
3388Comparing the books to a bank statement is the strongest practical control a
3389small business has, and the reason is not arithmetic — it is that the bank's
3390copy was written by someone with no stake in our numbers. Every design
3391choice follows from protecting that independence (logic-decisions #8).
3392
33931. **Imported lines are append-only and keep their original text** in `raw`;
3394 parsed fields are a view of it. A pre-write hook makes the factual fields
3395 immutable on update — corrections come from re-importing a corrected
3396 statement, never from editing a line to agree with the books.
33972. **The statement checks itself.** Opening + lines = closing (tie-out), and
3398 this opening = the last statement's closing (continuity). Both run at
3399 import and *set* the import's status; a truncated or edited file fails
3400 arithmetic. The flags record which checks **ran**, so a balance-less CSV
3401 never reads as trustworthy as a verified one.
34023. **Reading a bank's format is data**, not code: a saved column map,
3403 authored once with AI help and executed deterministically thereafter. AI
3404 at configuration time, code at run time — a control cannot be
3405 nondeterministic.
34064. **The matcher proposes; a person disposes.** Suggestions are derived and
3407 non-authoritative; confirming is an ordinary attributed update, so the
3408 change log names who reconciled what. Only a two-signal match
3409 (reference *and* amount) is auto-confirmable, and even that is
3410 configurable to off.
34115. **The unmatched tail is where the business logic lives**: fees, interest,
3412 own-account transfers, NSF bounces — each a resolution verb composing a
3413 posted journal through the shared composer, stamped with the line's id so
3414 resolving twice books once. These are exactly the entries small books
3415 never record, which is why their cash balance drifts until they stop
3416 reconciling at all.
3417
3418## State-dependent behavior generally
3419
3420`transitions` + `when` guards define the machine; the board's drag is its UI;
3421hooks gate specific moves with computed conditions (the balance check gates
3422`draft → posted`); the daemon makes time-based moves. The known missing
3423declarative is **""state freezes fields""** (a posted invoice's amounts are
3424immutable). Per the method: express it in each module's hook first; promote it
3425to a schema key (`locked_when`) only after the shape repeats
3426(logic-decisions #5).
3427
3428## What this implies we build next
3429
3430The examples above want one substrate piece that doesn't exist yet: a
3431**payments collection** (plain records — provider integration is a connector
3432later). It unblocks aging, dunning, and refunds at once. Then: `tax_rates` +
3433the stamping hook; then a delay/repeat notion for `notify_rules` if escalation
3434schedules outgrow ""each step is its own transition.""
3435
3436## Related
3437
3438- [`validation-and-logic.md`](/docs/validation-and-logic) — the enforcement
3439 reference for each primitive (validation table, hooks contract,
3440 formulas/rollups, the automation substrate).
3441- [`logic-decisions.md`](/docs/logic-decisions) — the living log of placement
3442 decisions and doctrines.
3443- [`storage-modes.md`](/docs/storage-modes) — append-only collections, the
3444 substrate for money-moves.
3445"
3446validation-and-logic Validation and Business Logic Building on DBBASIC 240 How DBBASIC Object Server enforces field validation and runs business rules from the schema alone, with no per-app code required. "Two things a schema-driven system has to get right without per-app code:
3447rejecting bad writes, and running the business rules a record's lifecycle
3448implies. DBBASIC does both from the schema, enforced on the server — the form
3449is a convenience, not the gate.
3450
3451## Validation — declared once, enforced on every write
3452
3453The write path (create and update) validates each field against the schema,
3454server-side, regardless of which surface issued the write (web form, API, MCP
3455agent, AI). A form's client-side checks are a nicety on top; they are not what
3456protects the data.
3457
3458What is enforced today:
3459
3460| Check | Declared as | Enforced |
3461|-------|-------------|----------|
3462| Type parses | `type` (integer, number, date, datetime, boolean, enum) | ✅ |
3463| Required present | `required: true` | ✅ |
3464| Enum membership | `enum: [...]` | ✅ (value must be in the list) |
3465| Length bounds | `validation.min_length` / `max_length` | ✅ |
3466| Numeric range | `validation.min` / `max` | ✅ (every writer; `payments.amount_cents` and `refunds.amount_cents` declare `min: 1`) |
3467| Strict numeric bound | `validation.exclusive_min` / `exclusive_max` | ✅ (every writer; ""greater than zero"" — see below) |
3468| Required once a state holds | `validation.required_when` | ✅ (every writer; ""a matched line names its target"" — see below) |
3469| Pattern | `validation.pattern` (regex: Python `re` syntax, matched against the whole value; a package whose pattern does not compile is refused at install, see `dron.md`) | ✅ |
3470| Referential integrity | `relation: {collection}` | ✅ (id must exist in the target) |
3471| State transition | field `transitions` map / `flow` | ✅ (status can only move where allowed) |
3472| Read-only / computed | `read_only` / `type: computed` | ✅ (client value rejected) |
3473| Uniqueness | root-level `unique: [{fields, scope}]` | ✅ (inside the write lock, for every writer — see below) |
3474| Frozen once settled | root-level `locked_when: [{when, except}]` or `[{when, fields}]` | ✅ (update and delete, inside the write lock, for every writer — see below) |
3475| Storable in TSV | (substrate) | ✅ (size, no NUL/control chars) |
3476
3477Referential integrity and enforced state transitions are the notable ones —
3478most no-code tools skip both. A relation is a *validated pointer*: you cannot
3479point a `project_id` at a project that doesn't exist. A status field with a
3480`transitions` map is a state machine: an order can go `open → cancelled` only
3481if the schema says so.
3482
3483### Strict bounds and conditional required fields
3484
3485```json
3486{""name"": ""quantity"", ""type"": ""number"", ""required"": true,
3487 ""validation"": {""exclusive_min"": 0}},
3488
3489{""name"": ""matched_to"", ""type"": ""text"",
3490 ""validation"": {""required_when"": {""match_status"": [""matched""]}}}
3491```
3492
3493**`exclusive_min` / `exclusive_max`** say *strictly* greater / less than a
3494number. `min` and `max` are inclusive, so `min: 0` admits a zero and ""usage is
3495positive"" or ""a stock move moves something"" could not be said without code.
3496Use `min: 1` for a whole-number count (`payments.amount_cents`); use
3497`exclusive_min: 0` where fractions are real (`quantity`, which may be 1.5 or
34980.0000001). The comparison is exact (decimal, not float), the field must be
3499numeric, and a blank value is left to `required`, as it is for `min`. The
3500refusal reads `Record field 'quantity' must be greater than 0`. They combine
3501with `min` / `max`; a range that allows nothing (`exclusive_min: 5` with
3502`max: 5`) is refused at schema load.
3503
3504**`required_when`** says the field must be non-blank (not empty, not only
3505spaces) while the record matches **every** condition, in the shape
3506`locked_when.when` uses: `{field: value}` or `{field: [values]}`, where a field
3507holds one of its values (compared exactly, as stored; booleans as `true` /
3508`false`). It is judged on the record **as it will be stored**: on an update,
3509the stored row with the submitted changes applied. So the write that sets
3510`match_status` to `matched` must also set `matched_to` (or find it already
3511set), a write that blanks `matched_to` while the line is matched is refused,
3512and moving the line out of `matched` frees the field. The refusal reads
3513`Record field 'matched_to' is required when match_status is matched`.
3514
3515Both are checked by `object_records` with the other field rules, on create
3516and update, for every writer: HTTP, MCP, handlers, the daemon, imports. A
3517refusal is the ordinary validation **400** (`InvalidRecordPayloadError`) and
3518nothing is written. A row that already breaks a rule when a declaration is
3519added stays on file, but is refused on its next write whatever that write
3520changes — the same as `min`.
3521
3522**Refused at schema load** (`ValueError`, never ""no rule""): a bound that is not
3523a finite number, an exclusive bound on a non-numeric field, bounds that leave
3524no value, a `required_when` that is empty, names a field the schema does not
3525declare (a typo would never apply), names the field itself, has a value that is
3526not a string or a non-empty list of strings, or sits on a computed or
3527read-only field.
3528
3529**What they do not do.** They cannot say ""forbidden when"" (a loss move must have
3530*no* destination) or compare two fields (`taken <= capacity`), and `required_when`
3531asks for non-blank, not for a particular value. Those stay in a hook or a
3532[locked check](#locked-checks--a-decision-across-collections-made-inside-the-write-lock). The whole list of what a declaration cannot say, and the tool for each, is
3533[What can't be declared](/docs/package-authoring#what-cant-be-declared).
3534
3535### Known gaps
3536
3537- **Numeric range is declared field by field, and most money fields do not
3538 declare it yet.** `validation.min`/`max` is enforced, but a price can still
3539 go negative wherever no schema says otherwise. The collections where it
3540 mattered first (payments, refunds) declare `min: 1`, and the quantities of
3541 usage events, stock moves and shipment lines declare `exclusive_min: 0`; the
3542 others still rely on their hook, which only the public write surface reaches.
3543- **Declarative cross-field rules** — no formula language yet for
3544 ""end_date > start_date"" (`visible_when` handles conditional *visibility*,
3545 not validation). The general mechanism exists, though: a **pre-write hook**
3546 (below) expresses any cross-field or cross-collection rule in real code. A
3547 Salesforce-style declarative rule (formula + message) remains the ergonomic
3548 follow-on for the common cases.
3549- **Inline client feedback** — the form pre-checks `required`; length/pattern
3550 errors currently surface after a server round-trip, and messages are
3551 technical (""longer than max_length""). Friendlier, inline feedback is a
3552 UX polish item, not a safety gap.
3553
3554## Uniqueness — declared in the schema, enforced inside the write lock
3555
3556```json
3557{
3558 ""name"": ""usage_events"",
3559 ""unique"": [
3560 {""fields"": [""event_id""], ""scope"": [""owner_id""]},
3561 {""fields"": [""code""], ""ignore_case"": true, ""message"": ""That code is already in use.""}
3562 ],
3563 ""fields"": [ ... ]
3564}
3565```
3566
3567Each entry says: no two records may hold the same `fields` values — within
3568the same `scope` values, when a scope is given.
3569
3570| key | meaning |
3571|---|---|
3572| `fields` | Required. The key: one or more field names. With several, records collide only when **all** match. |
3573| `scope` | Optional. Field names the key is unique *within* (""per owner"", ""per bank account""). |
3574| `ignore_case` | Optional, default `false`. Compare the `fields` values without regard to case. |
3575| `message` | Optional. The error text for a violation, in place of the generated sentence. |
3576
3577How two records are compared:
3578
3579- **Values are compared trimmed.** `""evt-1""` and `""evt-1 ""` are one key.
3580- **A blank `fields` value means the record has no key and is exempt.** Most
3581 wallets have no gift-card code and a bank line from a CSV has no bank
3582 transaction id; uniqueness is a property of the keys that exist. Make the
3583 field `required` if every record must have one.
3584- **A blank `scope` value is an ordinary value.** Two ownerless records with
3585 the same key *do* collide. (Admin-token writes are not owner-stamped; if a
3586 blank scope were exempt, they could duplicate freely.)
3587- `ignore_case` folds the `fields` values, not the scope.
3588
3589**Why this is a schema key and not a hook.** A duplicate check in a pre-write
3590hook reads the collection, finds nothing and allows the write — but hooks run
3591*before* the write lock, so two overlapping requests both find nothing and
3592both land. A handler or scheduled job that asks ""have I done this already?""
3593before writing has the same gap, and never reaches a hook at all. This is how
3594one usage event was billed twice, one wallet top-up credited twice and one
3595setting configured twice. `unique` is checked by `object_records` under the
3596same lock that performs the append, so the second writer sees the first one's
3597row. It applies to **every writer**: HTTP, MCP, handlers, the daemon, imports,
3598seeds. There is no bypass flag.
3599
3600**What a violation looks like.** Nothing is written and no change-log entry
3601is made.
3602
3603- From `object_records.create_collection_record` / `update_collection_record`:
3604 `object_records.UniqueConstraintError` (a `ValueError`), with `.collection`,
3605 `.fields`, `.scope` and `.existing_id` — the record that holds the key. A
3606 storage-level writer that must be idempotent catches it and treats it as
3607 ""already done"":
3608
3609 ```python
3610 try:
3611 object_records.create_collection_record(""wallet_entries"", entry, base_dir=base, actor=ACTOR)
3612 except object_records.UniqueConstraintError:
3613 return {""status"": ""already_posted""} # the marker was used; post nothing
3614 ```
3615
3616- Over HTTP: **409** with `""code"": ""unique_violation""` and the constraint's
3617 `fields` and `scope`. The id of the record that holds the key is *not*
3618 returned — the caller may not be allowed to read it.
3619
3620**Updates.** An update is checked only for a key it *changes*. A record may
3621keep its own key and change anything else.
3622
3623**Data that was already there.** Declaring a constraint over a collection
3624that already holds duplicates does not remove them and does not fail. The
3625existing records stay and stay editable; no *further* holder of that key is
3626admitted, and deleting one duplicate does not free a key another still holds.
3627`object_records.find_unique_violations(collection, base_dir=...)` lists them
3628(`[{""fields"", ""scope"", ""values"", ""ids""}]`) — run it before declaring a
3629constraint, and merge or delete what it reports.
3630
3631**What is refused at schema load** (a `ValueError`, so an unenforceable
3632constraint never loads as ""no constraint""): an entry that is not an object (a
3633bare list of names is ambiguous — one compound key, or several?), unknown
3634keys, `id`, a `computed` field, a `store: extra` field, a field named twice.
3635A field does not have to be declared in `fields` to be constrained.
3636
3637**Cost.** Collections without `unique` pay one cached schema lookup per
3638write. A constrained collection keeps an in-memory index of who holds each
3639key; it is built once (one pass over the cached rows) and then updated by
3640each write, so a write costs a dictionary lookup, not a scan. Measured at
3641100,000 rows in append mode, three runs of 200 creates: 1.2–1.4 ms per create
3642without a constraint, 1.25–1.5 ms with one; the one write that builds the
3643index took about 170 ms longer, most of it reading the file because the
3644collection was cold. The index is rebuilt after anything else changes the file —
3645another process's write, a compaction, a restore — so several processes
3646taking turns writing one collection each pay a rebuild per turn. A collection
3647too large for the records cache still holds its keys in memory.
3648
3649**What it does not do.** It compares stored values for equality. It cannot
3650express ""one *received* payment per order"" (a conditional key) or ""amounts
3651must not exceed a ceiling"" (a sum). `unique` is not exposed by `/api/schema`.
3652
3653**A ceiling is not a `unique` key.** ""Payments must not exceed the
3654invoice"", ""refunds must not exceed the payment"" are sums over rows that
3655several writers add to, with inputs in other collections. `payments.v3` and
3656`refunds.v3` approximated it with a per-parent sequence number declared
3657`unique` (each hooked writer stamped the next number from the read it
3658summed), which serialized writers that came through the hook and nobody
3659else: a webhook's payment carried no number, an admin's edit kept its old
3660one, and an invoice line cut in the meantime was not seen. Declare a
3661ceiling as a [locked check](#locked-checks--a-decision-across-collections-made-inside-the-write-lock)
3662instead; it holds for every writer and for inputs in other collections.
3663The v3 columns `invoice_seq` / `payment_seq` remain as data, unconstrained
3664and no longer stamped.
3665
3666## Locked when settled — declared in the schema, enforced inside the write lock
3667
3668```json
3669{
3670 ""name"": ""time_logs"",
3671 ""locked_when"": [
3672 {""when"": {""status"": [""approved"", ""billed""]},
3673 ""except"": [""status"", ""invoice_id"", ""notes""],
3674 ""message"": ""Approved time is settled. Correct it with a new entry.""}
3675 ],
3676 ""fields"": [ ... ]
3677}
3678```
3679
3680Each rule says: while the **stored** record has `when`, an update may change
3681only the `except` fields, and the record cannot be deleted. Or, written the
3682other way round with `fields`, an update may change anything **but** the
3683listed fields (below).
3684
3685| key | meaning |
3686|---|---|
3687| `when` | Required, at least one field. `{field: value}` or `{field: [values]}`; the rule applies when *every* named field holds one of its values (compared exactly, as stored). |
3688| `except` | Optional, default `[]`. The fields an update may still change while the rule applies. Everything else is frozen — including fields added to the schema later, and fields the schema does not declare. |
3689| `fields` | Optional, instead of `except`. The only fields the rule freezes while it applies; every other field, including ones added to the schema later, stays editable. A non-empty list of declared fields, never `id`. A rule that names both `except` and `fields` is refused when the schema loads, as is an empty list or a name the schema does not declare (a typo would leave the field editable, the unsafe direction). |
3690| `allow_delete` | Optional, default `false`. `true` freezes the fields but still lets the record be deleted. |
3691| `message` | Optional. The error text for a refusal, in place of the generated sentence. |
3692
3693Which form to use: `except` is the safe default for a record that is *money or
3694evidence* (a new field is frozen until someone decides otherwise). `fields` is
3695for a record that is mostly still alive once settled, where only a few fields
3696are the settled fact:
3697
3698```json
3699{""when"": {""status"": [""won"", ""lost""]},
3700 ""fields"": [""title"", ""description"", ""amount_cents""],
3701 ""message"": ""A settled deal's title, description and amount are frozen.""}
3702```
3703
3704The two forms are judged the same way in everything below, inside the same
3705lock, for every writer; only the question ""is this field frozen?"" differs.
3706`allow_delete` is independent of the form and defaults to `false`: a settled
3707record cannot be deleted whichever fields are frozen. A refusal is `409
3708record_locked` with `fields` naming the frozen fields the write tried to
3709change (`[]` for a delete), and a `message` becomes its `error`.
3710
3711How a write is judged:
3712
3713- **By the stored record, not by what the write would produce.** The write
3714 that moves a draft to `approved` may change anything — the stored row is a
3715 draft. A write to an approved row may change only the `except` fields, even
3716 if it also moves the row out of `approved`: unlocking and editing take two
3717 writes.
3718- **A change is a submitted field whose value would differ.** Sending a frozen
3719 field back unchanged is fine (a form posts everything it shows).
3720- **Computed and read-only fields are never frozen.** A client cannot submit
3721 either; what changes them is the server — a rollup recomputed on a posted
3722 journal, a trusted writer's stamp.
3723- **Every matching rule applies**, and each can only restrict.
3724- **Nobody is exempt**: not the owner, not an admin, not the admin token, not
3725 a storage-level writer, and there is no bypass argument. A trusted writer
3726 that must touch a settled record (the invoice generator moving `approved` to
3727 `billed` and stamping `invoice_id`) does it through the `except` fields.
3728- **Creates are not affected**: a record may be created already in the state.
3729
3730**The state field decides whether the lock can be left.** Put the field that
3731`when` tests in `except` and the `transitions` map decides which moves out of
3732the state are legal; leave it out and the state is terminal.
3733
3734**Why this is a schema key and not a hook.** Three hooks each carried their
3735own `_ALLOWED_AFTER_…` set (time logs, expenses, scans), which is the point
3736[`logic-decisions.md`](/docs/logic-decisions) #5 said to promote the pattern.
3737They also shared three gaps a hook cannot close: the hook did not run on
3738delete, so the frozen record could be removed; the hook reads the record
3739*before* the write lock, so an edit that overlaps the approval is checked
3740against the draft and written onto the approved row; and storage-level
3741writers never reach a hook. `locked_when` is checked by `object_records`
3742against the row read under the lock.
3743
3744**What a refusal looks like.** Nothing is written and no change-log entry is
3745made.
3746
3747- From `object_records.update_collection_record` / `delete_collection_record`:
3748 `object_records.RecordLockedError` (a `ValueError`), with `.collection`,
3749 `.record_id`, `.action` (`""update""` or `""delete""`), `.fields` (the frozen
3750 fields the update tried to change; `[]` for a delete) and `.when`.
3751- Over HTTP: **409** with `""code"": ""record_locked""` and `fields`.
3752
3753**What it does not do.** It reads one record. It cannot freeze a journal's
3754*lines* because the *journal* is posted — that rule is about another
3755collection, and stays in the line's hook (`hook_fin_journal_lines`, where it
3756is advisory against a concurrent post, and where it has to ask about the
3757journal a line is *leaving* as well as the one it joins: a hook that read
3758only the new `journal_id` let a line be moved out of a posted journal).
3759Retention pruning (`prune_collection_records`) rewrites the file rather than
3760deleting row by row, so it cannot apply the rule per record; it refuses a
3761collection that declares `locked_when` outright (its one caller ages out
3762`page_views`, which declares none). `locked_when` is not exposed by `/api/schema`,
3763so the generated form does not yet grey out frozen fields; it learns from the
3764409.
3765
3766## Locked checks — a decision across collections, made inside the write lock
3767
3768```json
3769{
3770 ""name"": ""payments"",
3771 ""locked_checks"": [
3772 {""name"": ""overpayment"",
3773 ""object"": ""hook_payments"",
3774 ""function"": ""LOCKED_CHECK"",
3775 ""reads"": [""invoices"", ""invoice_lines"", ""refunds"", ""app_settings""],
3776 ""lock"": ""ledger"",
3777 ""on"": {""create"": true, ""update"": [""amount_cents"", ""invoice_id"", ""status""], ""delete"": true}}
3778 ],
3779 ""fields"": [ ... ]
3780}
3781```
3782
3783Each entry says: before any write that `on` selects lands in this
3784collection, call `function` of the installed object `object`, holding the
3785named `lock`, and do not write unless it allows. `unique` and `locked_when`
3786are rules about one collection; a locked check is for the rule that needs
3787rows from **other** collections — a sum against a ceiling (""payments on an
3788invoice do not exceed what the invoice is worth""), a headroom (""refunds do
3789not exceed the payment""), a parent that must still be in a state.
3790
3791| key | meaning |
3792|---|---|
3793| `object` | Required. The installed object that ships the check (usually the collection's hook object). |
3794| `function` | Optional, default `LOCKED_CHECK`. A function of that object, not one of its request verbs (`GET`, `POST`, …) or `BEFORE_WRITE` — those are refused at schema load. |
3795| `name` | Optional, default the object id. Named in errors (`check`) and in the 409. Unique within the schema. |
3796| `reads` | Collections the check reads besides this one. **Every write to them takes the lock too** — that is what holds them still. List every collection whose rows the verdict depends on. |
3797| `lock` | Optional, default this collection's name. A lock name (`[a-z0-9_]+`). Checks that read each other's collections should share one (`payments` and `refunds` both use `ledger`). |
3798| `on` | Optional, default all three. `create` / `delete`: `true` or `false`. `update`: `true` (any field changes), `false`, or a list of fields — the check runs only when a write changes one of them. |
3799
3800Unknown keys, a misspelled collection in `reads`, an `on` that selects
3801nothing: refused at schema load (a `ValueError`), so a check that cannot be
3802enforced never loads as ""no check"". Not exposed by `/api/schema`.
3803
3804**Why a declaration and a function, not a declarative sum.** The owner
3805prefers configuration, and `""ceilings"": [{""sum"": ..., ""group_by"": ...,
3806""max_from"": ...}]` was the first candidate. It cannot state the ceilings
3807that ship: the overpayment ceiling is the smaller of the invoice's stamped
3808total and what its lines say (subtotal by `object_lines`, plus the larger of
3809line and document tax), and the refund headroom is the payment's amount net
3810of the *other* refunds, refused outright for a bounced payment. A
3811declarative form would need an expression language to say that, or it would
3812change what the ceiling is computed from. So the *locking* is declared —
3813which collections, which lock, which writes — and the *verdict* is a named,
3814read-only function the package ships beside its hook, sharing the hook's
3815code so the early answer and the locked answer cannot drift.
3816
3817**When it runs.** `object_records.create/update/delete_collection_record`
3818call it for every writer — HTTP and MCP, actions, handlers, webhooks, the
3819daemon, imports (`object_import`), materialize, merged seeds — after schema
3820validation, transitions, `locked_when` and `unique`, and before anything is
3821written. There is no bypass argument. Its request:
3822
3823| key | create | update | delete |
3824|---|---|---|---|
3825| `record` | the row to be stored | the stored row with the changes applied | the row being removed |
3826| `existing` | `None` | the stored row, read **under the lock** | the same row |
3827| `collection`, `action`, `check`, `reads`, `base_dir` | | | |
3828
3829There is no `subject`: a locked check states a fact about the data, not a
3830permission. Who may do what stays in the hook.
3831
3832**What it answers.** `None` (or `{}`) allows. `{""error"": ""..."", ""status"":
3833409}` refuses (any 4xx; the default is 409); `{""error"": ..., ""status"":
3834503}` says it could not decide. Anything else is a broken check.
3835
3836| outcome | `CheckRefusedError` `.status` / `.code` | over HTTP |
3837|---|---|---|
3838| the check refused | 409 (or its 4xx) / `check_refused` | 409 `{""code"": ""check_refused"", ""check"": name, ""error"": its sentence}` |
3839| it said 503, raised, is not installed, or its lock was not free within `DBBASIC_CHECK_LOCK_TIMEOUT_SECONDS` (default 30) | 503 / `check_unavailable` | 503 — retry |
3840| it answered outside the contract, or tried to write or to run another object | 500 / `check_failed` | 500 |
3841
3842Nothing is written and no change-log entry is made in any of these.
3843`CheckRefusedError` is a `ValueError` (like `UniqueConstraintError`), with
3844`.collection`, `.check`, `.status`, `.code`. A storage-level writer that
3845records money which has already moved must decide what a refusal means for
3846it — the Stripe webhook answers 409 with `needs_attention` (not
3847acknowledged, so Stripe redelivers once a person makes room); checkout's
3848gift-card payment reverses the wallet debit it just made.
3849
3850**What a check may do.** Read, through `object_records`, and decide. It
3851runs holding locks other writers wait on, so:
3852
3853- it may not write (`create/update/delete_collection_record`, retention)
3854 or run another object (`object_execution.execute_object`) — both raise
3855 `LockedCheckWriteError`, answered 500, nothing written;
3856- it must fail closed on a read it cannot make: return 503, or let the
3857 exception escape (also 503) — never treat ""unreadable"" as ""nothing
3858 there"";
3859- it should be quick: its cost is paid inside the lock by every writer of
3860 every collection the lock covers. A check that hangs makes the others
3861 time out with 503 after `DBBASIC_CHECK_LOCK_TIMEOUT_SECONDS` rather than
3862 wait forever; the platform does not interrupt the check itself.
3863
3864**The lock, and why it cannot deadlock.** A check lock is an `flock` on
3865`<data>/.locks/<lock>.lock`, so it holds across threads and processes like
3866the collection file locks. The rules:
3867
38681. A write plans its locks **before taking any**: every lock whose check is
3869 declared on, or reads, the collection it writes — plus those of the
3870 collections its rollups refresh, because that refresh writes them while
3871 this write's file lock is held.
38722. It takes those check locks **in sorted order**, then its collection file
3873 lock. A lock this thread already holds is not taken again (a rollup
3874 refresh nested in a write finds its locks held).
38753. A thread **never waits for a check lock while holding a file lock**. If a
3876 nested write needs one it does not hold (only possible if the schemas
3877 changed between the outer write's plan and the inner write), it gets
3878 `CheckLockOrderError` instead; a rollup refresh is best-effort and skips.
3879
3880So a thread waiting for a check lock holds only check locks that sort
3881before it and no file lock, and a thread waiting for a file lock already
3882holds every check lock it will ever take in that write. Waits among check
3883locks follow one total order (no cycle); no thread holding a file lock waits
3884on a check lock (no cycle through both kinds); waits among file locks are
3885the existing child → rollup-parent order, unchanged. Multiple named locks are
3886supported and tested (a write to a collection two checks read takes both).
3887
3888What the lock buys and costs: every write to a covered collection waits for
3889any other covered write in flight — for payments that is every write to
3890payments, refunds, invoices, invoice lines and settings, one at a time,
3891for the length of one check and one append. It is one lock per name, not
3892one per invoice; the ledger's writes are few and short, and a per-key lock
3893would need the key of every input (a line's invoice, a refund's payment's
3894invoice, both sides of a re-point) to be planned before the write, which a
3895name does not.
3896
3897**Nobody routes around it.**
3898
3899- Every storage write goes through the three functions above.
3900- Retention (`prune_collection_records`) refuses a collection a check is
3901 declared on or reads, as it refuses one with `locked_when`.
3902- A package's seed into a collection that already has records is merged row
3903 by row through `create_collection_record` (checked, as before); a
3904 **fresh** seed is normally a byte copy, but into a collection that
3905 declares a locked check it is written row by row as well, and refused
3906 rows are listed in the install result (`code: check_refused`).
3907- `compact_collection` rewrites a file without changing what it holds and
3908 takes no check lock. A backup **restore** replaces files wholesale, as it
3909 does for `unique` and `locked_when`: it is an operator's act on a stopped
3910 or quiet server, not a writer.
3911- A server running code from before this key ignores it (unknown root keys
3912 are dropped at schema load), as it would ignore `unique`.
3913
3914**Cost.** Collections no check covers pay one look at the schema index
3915(already made for rollups; shared). A covered write pays one `flock` round
3916trip (open, lock, unlock, close) and waits for other covered writes; a write
3917the check is selected for also pays the check's reads, inside the lock. Measured on one machine, append mode,
3918storage-level creates, median of 200 (50 at 100,000 rows); ""rows"" is the
3919number of payments, with a tenth as many invoices and refunds and a fifth
3920as many invoice lines:
3921
3922| write | 1,000 rows: without / with the declaration | 100,000 rows: without / with |
3923|---|---|---|
3924| a collection nothing covers (vs 246b3e5, before the mechanism) | 0.68 / 0.68 ms | 2.50 / 2.50 ms |
3925| `invoice_lines` create (takes the `ledger` lock, not checked) | 1.27 / 1.32 ms | 41.8 / 39.3 ms |
3926| `payments` create (takes the lock, runs `overpayment`) | 2.37 / 3.06 ms | 133.8 / 143.4 ms |
3927
3928The check costs about 0.7 ms at 1,000 payments and 10 ms at 100,000 (it
3929reads one invoice's payments, refunds and lines through
3930`read_collection_records_where`; the field index it uses is rebuilt after
3931each write to the collection). Most of a payment write at 100,000 rows is
3932not the check: it is the `invoices` rollup refresh, which reads every
3933payment, and was there before.
3934
3935**Shipped:** `payments.overpayment` (`hook_payments.LOCKED_CHECK`) and
3936`refunds.refundable` (`hook_refunds.LOCKED_CHECK`), both on the `ledger`
3937lock; `fin_journals.closed_period` and `fin_journal_lines.closed_period`
3938(`hook_fin_journals` / `hook_fin_journal_lines.LOCKED_CHECK`) on the
3939`fin_periods` lock, reading `fin_closed_periods` -- nothing is written,
3940edited, moved or deleted in a closed period by any writer. That rule had
3941lived in the two hooks, and every journal composer writes below them, so
3942a payment recorded after its month was closed posted into the closed
3943month. What a composer does instead is `object_finance.
3944compose_posted_journal`'s policy: the first open day after the period,
3945with `occurred_on` and `period_review=pending` saying so
3946(`tests/test_closed_period_composers.py`). Tests: `tests/test_locked_checks.py` (the mechanism, on a toy
3947package: every writer, every failure mode, the lock order, six processes
3948writing every covered collection in random order),
3949`tests/test_money_gates_locked_ceilings.py` and
3950`tests/test_money_gates_ceiling_races.py` (the money). Also `expenses.category_stamps` (`hook_expenses`, reading
3951`expense_categories`: an expense's stamped requirements and deductible share
3952must be what its category says when it is created, recategorised, submitted
3953or approved), `mileage_logs.mileage_rules` (`hook_mileage_logs`, reading
3954`mileage_rates` and `vehicles` and the other trips on the vehicle: no
3955backwards or overlapping odometer readings, no approval at a rate other than
3956the year's) and `fringe_benefits.fringe_period`; see
3957`expense-substantiation.md`.
3958
3959## Pre-write hooks — code inside the write path
3960
3961For rules the schema can't express, a collection declares a **hook object**:
3962
3963```json
3964{ ""name"": ""fin_journals"", ""hooks"": { ""before_write"": ""hook_fin_journals"" } }
3965```
3966
3967The object's `BEFORE_WRITE(request)` runs **synchronously inside the generic
3968HTTP write path** — after permission checks, before persist — for every public
3969create, update **and delete** on that collection. `request` carries
3970`{collection, action, record, existing, changes, subject}`. It returns `None`
3971to allow, `{""error"": ""..."", ""status"": 4xx}` to reject with its own message, or
3972`{""record"": {...}}` to transform (the transformed record still passes full
3973schema validation, and can never touch `id`, `owner_id`, or read-only/computed
3974fields).
3975
3976What the request holds depends on `action`:
3977
3978| `action` | `existing` | `record` | `changes` | may answer |
3979|---|---|---|---|---|
3980| `""create""` | `None` | the row to be written | the same row | allow, reject, transform |
3981| `""update""` | the stored row before this write | that row with the caller's changes applied | only what the caller sent | allow, reject, transform |
3982| `""delete""` | the row about to be removed | the same row | `{}` | allow, reject |
3983
3984`subject` is `{""user_id"": ..., ""roles"": [...]}` in all three.
3985
3986**Branch on `action` first.** A hook is called for all three and every rule in
3987it has to say which it is about. The delete path ran no hook until a review
3988found that ""approved time is frozen"" stopped an edit and not a `DELETE`; when
3989deletes started arriving, two shipped hooks that decided ""is this being
3990approved?"" from the record's status mistook the removal of an approved row for
3991an approval, and answered with the self-approval refusal. A hook that has no
3992rule about deletes starts with
3993`if request[""action""] not in (""create"", ""update""): return None`.
3994
3995A delete cannot be transformed — there is nothing to persist — so a hook that
3996answers one with `{""record"": ...}` is treated as broken (`500`, nothing
3997deleted), like any other answer outside the contract.
3998
3999`existing` is read before the write lock is taken, so everything a hook checks
4000is advisory against a concurrent writer: two requests can both pass the same
4001hook and both write. A hook is the right place for a rule about one request;
4002it cannot make a rule hold under a race. ""This value appears once"" is declared
4003as `unique` (above) and enforced inside the lock; ""this sum stays under what
4004another collection says"" is a `locked_checks` entry (above), whose function
4005the hook can share so its early answer and the locked one agree; ""this record
4006has not changed since I read it"" is `If-Match` / `expected_rev`.
4007
4008The contract is deliberately strict:
4009
4010- **Fail closed** — a declared hook that is missing, raises, or returns a
4011 non-contract shape rejects the write. A gate that silently passes on error
4012 is not a gate.
4013- **Every surface that writes on a caller's behalf** — the collection routes,
4014 MCP's record tools (which call them), and the file routes (`/api/files`,
4015 WebDAV), which create and delete `files` records through their own helpers
4016 and ask the `files` hook the same way.
4017- **A gate's own reads fail closed too.** A hook that reads other records to
4018 decide must not treat ""I could not read"" as ""nothing there"". Five shipped
4019 gates did, and with the ledger unreadable the duplicate gate passed the
4020 duplicate. `object_records.read_collection_records` raises on a failed
4021 read; what a gate may fold to ""no rows"" is only a collection that is *not
4022 installed*, which is a fact rather than an unknown:
4023
4024 ```python
4025 try:
4026 rows = object_records.read_collection_records(""refunds"", base_dir=base)
4027 except object_collections.CollectionNotFoundError:
4028 rows = [] # app-payments' refunds not installed: none exist
4029 except Exception:
4030 return {""error"": ""Refund history is unreadable; refusing to record ""
4031 ""against an unknown history."", ""status"": 503}
4032 ```
4033
4034 A hook that simply lets the exception escape is also closed (`500
4035 hook_failed`, no write); returning its own `503` just says why. The shared
4036 readers gates call take `strict=True` for the same behaviour —
4037 `object_banking.existing_line_keys`, `is_duplicate_line`,
4038 `find_import_by_file_hash`, `previous_import`, `run_gates`, and
4039 `object_finance.closed_period_for` — and are lenient by default only
4040 until each caller is moved over. Moved so far: both bank statement
4041 importers (every gate read strict; an import that fails part-way is
4042 resumed by re-importing the file), `action_reverse_journal`'s
4043 closed-period check, and the hooks that gate on these reads
4044 (`hook_bank_lines`, `hook_fin_journals`, `hook_fin_journal_lines`).
4045
4046 The server relays a hook's status when it is a 4xx or `503`
4047 (`_apply_before_write_hook`); anything else a refusing hook returns
4048 reaches the client as `400`. So ""I could not read"" arrives as something
4049 to retry, not as a bad request, and a hook still cannot call a refused
4050 write a success or a server fault of its own.
4051- **After permissions** — a denied subject never reaches the hook.
4052- **Opt-in per collection** — collections without `hooks` pay one cached dict
4053 lookup; the original latency concern that deferred this feature
4054 ([`event-hooks-decisions.md`](/docs/event-hooks-decisions)) stays bounded.
4055- **Public surface only** — trusted server-side writers (the daemon,
4056 migrations, seed-merge) call the storage layer directly and bypass hooks.
4057
4058This is what keeps the generative form working when custom logic arrives: the
4059form still POSTs to `/collections/{c}/records`; the rule lives server-side.
4060First adopter: `fin_journals` refuses to post a journal whose lines don't
4061balance — a cross-collection rule (it sums `fin_journal_lines`) no schema key
4062could express.
4063
4064## Business logic — the automation substrate
4065
4066Business rules run without per-app code through a set of declarative
4067primitives, driven by a background daemon and the change log:
4068
4069```mermaid
4070flowchart LR
4071 W[""record write""] --> CL[""change log""]
4072 CL --> DAEMON[""daemon: poll triggers""]
4073 DAEMON --> NOTIFY[""notify_rules → notification / email""]
4074 DAEMON --> TARGET[""trigger object → target object""]
4075 W --> TRANS[""transition guards (flow: when clauses)""]
4076 SCHED[""schedule""] --> DAEMON
4077 DAEMON --> COMPUTE[""computed / materialize fields""]
4078 DAEMON --> CONN[""connectors → external systems + reconcile""]
4079```
4080
4081- **Transitions with guards** — a `flow`/`transitions` map is a conditional
4082 state machine; a `when` clause gates whether a move is allowed. The board's
4083 drag and every status write run through it.
4084- **notify_rules** — declarative ""a record changed → send a notification /
4085 email."" Data, not code.
4086- **Trigger → target objects** — the daemon polls trigger objects and executes
4087 target objects: the event-handler path (see
4088 `runtime-contract.md` and
4089 [`event-hooks-decisions.md`](/docs/event-hooks-decisions)).
4090- **Computed / materialized fields** — derived values (`type: computed`,
4091 `materialize_definitions`).
4092- **Connectors** — external side effects expressed as desired-state records
4093 with a reconcile pass.
4094- **Scheduled passes** — the daemon runs periodic work (compaction,
4095 auto-transitions).
4096
4097This is the same family as Salesforce flows/validation-rules, Hasura event
4098triggers, and Directus Flows — declarative automation over a data store, here
4099on plain-text records.
4100
4101### Formula & rollup fields — shipped
4102
4103The spreadsheet feature, on collections. A `type: computed` field declares
4104either a **formula** over sibling fields or a **rollup** over a child
4105collection:
4106
4107```json
4108{""name"": ""full_name"", ""type"": ""computed"",
4109 ""formula"": ""first_name + \"" \"" + last_name""}
4110
4111{""name"": ""debit_total_cents"", ""type"": ""computed"",
4112 ""rollup"": {""collection"": ""fin_journal_lines"", ""fk_field"": ""journal_id"",
4113 ""op"": ""sum"", ""field"": ""debit_cents""}}
4114```
4115
4116Values are **materialized on write at the storage layer** — stored in the TSV,
4117recomputed whenever inputs change (formulas on writes of the record itself;
4118rollups when source-collection records are created, updated, or deleted —
4119single-hop, loop-guarded). Because the value is stored, every surface works
4120with zero changes: lists, tables, detail, search, `field=value` filters, sort,
4121CSV, backups — and **realtime falls out free**: edit a journal line and the
4122journal's totals update live in every open browser. `rollup.op` is
4123`sum | count | min | max | avg`, with an optional equality `where`. The
4124formula language is a tiny safe expression grammar (fields, strings, numbers,
4125`+ - * /`, parens, `round(x[, places])` and `floor(x)` — never Python
4126eval). Numbers are exact: whole numbers are integers of any size, fractions
4127are Decimal, never float. A formula over whole numbers only fills an integer
4128field, so a division in it is rounded half-up once at the end
4129(`1234 * 825 / 10000` is 102); one with a fractional operand keeps its
4130fraction. Rollups sum the same way. A broken formula stores an empty value
4131and never fails the write — derived values are non-authoritative, the opposite
4132posture of hooks. Definition changes are backfilled explicitly with
4133`object_records.recompute_computed_fields(collection)` (install step, admin
4134action, or cron — never a runtime loop).
4135
4136Finding a written collection's rollup parents happens after the row has
4137landed, so it is best-effort like the refresh: a schema file in
4138`<data>/schemas/` that does not load (invalid JSON, a name outside the
4139schema-name rules) is skipped, exactly as the check-lock plan skips it, and
4140the write is answered as written. Writes to that file's own collection are
4141refused before anything is written, since its schema is what they validate
4142against. A rollup the broken file declares is not refreshed while it is
4143broken — nobody can read the declaration — so its parent rows are stale until
4144the file is fixed and then either a child of that parent is written again
4145(the refresh recomputes from every child) or
4146`recompute_computed_fields(<parent>)` is run. The broken file itself is what
4147to look for: `GET /schemas/<name>` answers its error.
4148
4149**Declarative validation rules** (cross-field formula + message) remain the
4150natural next sugar over the hook.
4151
4152## Related
4153
4154- [`business-logic-patterns.md`](/docs/business-logic-patterns) — WHERE each kind
4155 of rule goes (the placement flowchart) with worked examples; and
4156 [`logic-decisions.md`](/docs/logic-decisions), the doctrines behind placements.
4157- [`schema-forms.md`](/docs/schema-forms) — the field contract these checks read.
4158- `runtime-contract.md` — the daemon, triggers,
4159 schedules, and event contracts.
4160- [`event-hooks-decisions.md`](/docs/event-hooks-decisions) — why event handlers
4161 are shaped the way they are.
4162- [`storage-modes.md`](/docs/storage-modes) — append-only collections, the
4163 immutable substrate for audit-shaped data (journals, stock moves).
4164"
4165capabilities Capabilities: Per-Collection Behaviors, Declared Not Coded Building on DBBASIC 250 How the platform's capability layer lets any collection opt into comments, attachments, and sharing by declaring a flag instead of hand-building each behavior per app. "The schema-driven UI has two layers. The **display** layer turns a schema into
4166a list, table, board, form, and detail page (see
4167[`schema-forms.md`](/docs/schema-forms)). The **capability** layer sits on top of
4168it: generic *behaviors* a collection opts into by declaring a flag, wired by the
4169platform instead of hand-built per app.
4170
4171A collection declares them under a root-level `capabilities` key:
4172
4173```json
4174{
4175 ""name"": ""tasks"",
4176 ""capabilities"": { ""comments"": true, ""attachments"": true, ""shareable"": true },
4177 ""fields"": [ ... ]
4178}
4179```
4180
4181and its detail page grows a comment thread, an attachment list, and a share
4182control — with no per-view block and no per-app table. The same three flags on
4183`contacts`, `invoices`, or any other collection give the same behaviors.
4184
4185This is the ""define once, project everywhere"" rule applied to what a record
4186*does* and *connects to*, not just how it looks. It replaces the pattern where
4187every app hand-rolled its own version of the same idea: comments existed four
4188separate times (`task_comments`, `thread_comments`, `profile_comments`,
4189`interactions`) before one `capabilities.comments` flag collapsed them.
4190
4191## The model
4192
4193Each capability is one **polymorphic collection** (a row attaches to a record in
4194*any* collection via a `parent_collection` + `parent_id` pair), one **widget**
4195served as a static script like `/list` and `/form`, and one line in the detail
4196renderer that mounts the widget when the flag is present.
4197
4198```mermaid
4199flowchart TD
4200 S[""schema.capabilities flag""] --> API[""/api/schema exposes it""]
4201 API --> VR[""view_render: maybeMountCapabilities()""]
4202 VR -->|flag present| W[""window.dbbasicThread / Attachments / Share .mount()""]
4203 W --> C[""polymorphic collection<br/>parent_collection + parent_id""]
4204 C -->|permission-checked read and write| STORE[""object store""]
4205 D[""detail block""] --> VR
4206```
4207
4208The wiring is one function, `maybeMountCapabilities` in
4209`app-views/objects/site/view_render.py`: it fetches the record's schema, reads
4210`capabilities`, and mounts each declared widget into its own sub-element under
4211the detail. Absent flag or unloaded widget → nothing renders, never an error.
4212
4213`capabilities` is whitelisted in schema normalization
4214(`object_schemas.py`) and surfaced by `/api/schema` so the client can wire it —
4215the same ""carried, not interpreted"" posture as `flow` and `blocks`.
4216
4217## The three capabilities
4218
4219| Flag | Widget (route) | Backing collection | Package |
4220|------|----------------|--------------------|---------|
4221| `comments` | `window.dbbasicThread` (`/thread`) | `thread_comments` | `app-thread` |
4222| `attachments` | `window.dbbasicAttachments` (`/attachments`) | `files` (+`parent_*`) | `app-files` |
4223| `shareable` | `window.dbbasicShare` (`/share`) | `record_shares` | `app-share` |
4224
4225### comments
4226
4227A comment thread for one record. Reads/writes `thread_comments` filtered to the
4228`(parent_collection, parent_id)` pair, posts with a minimal payload (the server
4229owns `created_at`; `owner_id` is set from the session and redacted from other
4230readers, so each comment also stamps a display `author_name`), owner-only
4231delete, and re-renders over the change log like every other surface. The
4232widget shows only published comments (and the viewer's own); moderating them
4233(publishing, flagging, removing) has no widget yet and is a `status` change
4234over the record API by a user with the `moderator` role, who can change
4235nothing else on someone else's comment and cannot moderate their own
4236([permissions-model.md, ""Comment moderation""](/docs/permissions-model#comment-moderation)); moderators find the pending
4237ones listed at `/comments/pending`.
4238
4239### attachments
4240
4241An upload/list/download/delete surface for files attached to one record.
4242Uploads go multipart to `/api/files` — which owns `owner_id`/`size`/
4243`content_type` and saves the blob — carrying `parent_collection`/`parent_id` so
4244the file lands on this record. Delete is blob-aware (`DELETE /api/files/{id}`
4245removes the bytes *and* the metadata row; a plain record delete would orphan the
4246blob). No per-collection foreign key on `files` is needed.
4247
4248### shareable
4249
4250The foundational one — it changes the **permission check**, not just a widget.
4251A record's owner grants other users read (or write) access to that individual
4252record. See the security model below.
4253
4254## Sharing: the security model
4255
4256Sharing is the one capability that grants access, so it is designed so that a
4257grant can only ever *narrow* what a viewer could already reach, never widen it
4258for the granter's own benefit.
4259
4260```mermaid
4261sequenceDiagram
4262 participant Owner
4263 participant API as /api/share
4264 participant Store as record_shares
4265 participant Grantee
4266 participant Engine as permission check
4267
4268 Owner->>API: POST {collection, record_id, user_id}
4269 API->>API: does Owner own the TARGET record?
4270 Note right of API: cross-collection ownership check<br/>a row_filter cannot express
4271 API-->>Owner: 403 if not owner
4272 API->>Store: create grant (owner-only path)
4273 Grantee->>Engine: read record
4274 Engine->>Store: subject.shared_records[collection]
4275 Engine->>Engine: {id: $shared_records} row filter matches
4276 Engine-->>Grantee: allowed (only this record, only this collection)
4277```
4278
4279Three properties make it safe:
4280
42811. **Grants are minted only by `/api/share`.** `record_shares` has *no*
4282 create/update/delete permission rule, so a raw collection write can't forge
4283 one. The endpoint authorizes each grant against the **target record's**
4284 `owner_id` — a cross-collection fact a row filter can't check. A non-owner
4285 gets `403 ""Only the record's owner can share it.""`
42862. **Reads resolve through the subject.** Before a check runs, the server builds
4287 `subject.shared_records` (per collection) from `record_shares`, the same way
4288 it builds `project_ids` from `project_access`. A collection opts in with a
4289 `{""id"": ""$shared_records""}` read rule.
42903. **`$shared_records` is collection-aware.** The collection being checked is
4291 threaded through `_record_matches_filter → _resolve_filter_value`, so a share
4292 on a *task* never matches a same-id row in another collection. (Covered by
4293 `test_shared_records_filter_is_collection_scoped`.)
4294
4295Revoking (`DELETE /api/share/{id}`) is allowed to the record's owner, the
4296grant's granter or an admin. After that check it is a delete like any other
4297(docs/dron-write-semantics.md, S30): a `before_write` hook declared on
4298`record_shares` is asked, `locked_when` and `locked_checks` apply, a grant
4299that changed since it was looked up is not removed (`409 conflict`, retry),
4300and the change is published as a record change event.
4301
4302Verified end to end: a grantee reads a shared record (`200`), a non-grantee is
4303denied (`403`), and a non-owner cannot create a grant (`403`).
4304
4305## Adding a new capability
4306
4307The recipe, in order:
4308
43091. **A polymorphic collection** with `parent_collection` + `parent_id` (both
4310 *settable on create* — a field that is `required` **and** `read_only` can
4311 never be created through the HTTP write path, only a server-side
4312 `preserve_read_only` bypass).
43132. **A widget** object at `site_{name}` serving `window.dbbasic{Name}` (public
4314 `execute` rule — it's a static script; the data it reads stays row-gated).
43153. **Wire it** in `view_render`'s `maybeMountCapabilities` and add
4316 `<script src=""/{name}"">` to the view page.
43174. **Adopt it** on a collection with `capabilities.{name}: true`. If the
4318 behavior grants access (like sharing), also add the permission rule.
4319
4320Leave `owner_id` to the server on create — a field with a `public: hidden`
4321policy is server-set from the session and a client value is rejected.
4322
4323## Related
4324
4325- [`schema-forms.md`](/docs/schema-forms) — the display layer (forms, views, list
4326 modes) capabilities sit on top of.
4327- [`permissions-model.md`](/docs/permissions-model) — row/field filters, the
4328 `$`-variable row-filter language `$shared_records` extends, and sharing.
4329- [`ui-decisions.md`](/docs/ui-decisions) — decisions #7–#14, the living log of the
4330 generative-UI and capability behaviors (with the gotchas found building them).
4331"
4332capability-objects Capability Objects: ffmpeg, OCR, and Other System Tools Building on DBBASIC 260 How to write DBBASIC objects that shell out to system binaries like tesseract and ffmpeg safely, with worked examples and a security checklist. "A DBBASIC object is plain Python running in a subprocess. There is no
4333import sandbox and no call whitelist, so an object can do anything
4334Python on that machine can do — including shell out to system binaries.
4335That makes real capability work a normal object: OCR a scanned receipt
4336with `tesseract`, transcode a clip with `ffmpeg`, render a thumbnail
4337with ImageMagick, extract text from a PDF, call a local model.
4338
4339The old prototype shipped a pack of these. The runtime carries the same
4340capability; this page documents how to write them safely.
4341
4342## The execution model
4343
4344Each object call runs in a **spawned subprocess** with a wall-clock
4345timeout (`DBBASIC_OBJECT_TIMEOUT_SECONDS`). Practical consequences:
4346
4347- The object has the full standard library, the filesystem, and the
4348 ability to launch its own subprocesses. `subprocess.run([...])` works.
4349- A runaway object is killed at the timeout, so a hung `ffmpeg` cannot
4350 wedge the server. Set the timeout to fit the workload.
4351- It is isolated from the parent's memory, not from the machine. There
4352 is no CPU or memory cap yet (see status), so capability
4353 objects are **operator/admin code** — your own tools on your own box,
4354 the same trust level as a cron job. Writing object source is gated;
4355 visitors run these objects, they do not author them.
4356
4357## Prerequisite: install the tool
4358
4359Capability objects call binaries that must exist on the VM. This is a
4360normal operator step, explicit rather than hidden:
4361
4362```bash
4363sudo apt install tesseract-ocr ffmpeg imagemagick poppler-utils
4364```
4365
4366If a binary is missing, the object's `subprocess.run` raises
4367`FileNotFoundError`, which surfaces as a normal object execution error
4368in the logs and change feed — no silent failure.
4369
4370## Worked example: OCR an uploaded image
4371
4372A browser form posting `multipart/form-data` delivers files under
4373`request[""_files""]` with base64 content (see
4374[object authoring](/docs/object-authoring#upload-forms)). The object
4375writes the bytes to a temp file, runs `tesseract`, and returns the text.
4376
4377```python
4378import base64
4379import subprocess
4380import tempfile
4381from pathlib import Path
4382
4383
4384def POST(request):
4385 upload = request.get(""_files"", {}).get(""image"")
4386 if upload is None:
4387 return {""status"": ""error"", ""error"": ""post an image field""}
4388
4389 content = base64.b64decode(upload[""content_base64""])
4390 with tempfile.TemporaryDirectory() as work:
4391 source = Path(work) / ""in.png""
4392 source.write_bytes(content)
4393 result = subprocess.run(
4394 [""tesseract"", str(source), ""stdout""],
4395 capture_output=True, text=True, timeout=30,
4396 )
4397
4398 if result.returncode != 0:
4399 _logger.error(""ocr failed"", stderr=result.stderr[:500])
4400 return {""status"": ""error"", ""error"": ""OCR failed""}
4401
4402 text = result.stdout.strip()
4403 _logger.info(""ocr done"", chars=len(text))
4404 return {""status"": ""ok"", ""text"": text}
4405```
4406
4407Set that object's timeout generously (`DBBASIC_OBJECT_TIMEOUT_SECONDS`)
4408so a large scan has room, and grant it a public `execute` rule if the
4409form is public.
4410
4411## Worked example: transcode with ffmpeg
4412
4413```python
4414import base64
4415import subprocess
4416import tempfile
4417from pathlib import Path
4418
4419
4420def POST(request):
4421 upload = request.get(""_files"", {}).get(""clip"")
4422 content = base64.b64decode(upload[""content_base64""])
4423 with tempfile.TemporaryDirectory() as work:
4424 src = Path(work) / ""in""
4425 out = Path(work) / ""out.mp3""
4426 src.write_bytes(content)
4427 proc = subprocess.run(
4428 [""ffmpeg"", ""-y"", ""-i"", str(src), ""-vn"", ""-b:a"", ""128k"", str(out)],
4429 capture_output=True, timeout=120,
4430 )
4431 if proc.returncode != 0 or not out.exists():
4432 return {""status"": ""error"", ""error"": ""transcode failed""}
4433 audio = out.read_bytes()
4434
4435 return {
4436 ""content_type"": ""audio/mpeg"",
4437 ""body"": base64.b64encode(audio).decode(""ascii""),
4438 ""encoding"": ""base64"",
4439 }
4440```
4441
4442Small media (receipts, short clips, single images) fits inside a
4443request. **Long media does not** — a two-second timeout is fine for a
4444receipt but a 2 GB video transcode belongs in a background job, not a
4445web request. Background jobs are the next platform slice
4446(status); until then, keep capability objects to work that
4447finishes in seconds.
4448
4449## Composing with files, records, and AI
4450
4451Capability objects get more useful combined with the rest of the
4452platform:
4453
4454- **Files** — instead of accepting an upload each time, an object can
4455 read a stored file's bytes and OCR or transcode it, then write the
4456 result back as a new file or a record. (The clean helper for an
4457 object to read from the `files` collection by id is a small planned
4458 addition; today an object works from the request payload.)
4459- **Records** — an OCR object can `create` a record with the extracted
4460 text so it becomes searchable through [global search](/docs/http-api-contract#global-search).
4461- **AI + shell** — because the object is exposed as an
4462 `execute_object` MCP tool, the shell AI can call it. ""OCR my latest
4463 upload and note the total"" becomes: the AI reads the file, calls the
4464 OCR object, and creates a note — each step permission-checked and
4465 audited, no glue code.
4466
4467## Safety checklist for a capability object
4468
4469- Set a timeout that fits the job; never rely on the default.
4470- Validate the upload before spending CPU on it (size, content type).
4471- Write to a `tempfile.TemporaryDirectory()` so nothing leaks between
4472 calls; never build a shell command by string-concatenating user input
4473 — pass argument lists to `subprocess.run`, never `shell=True`.
4474- Log failures with `_logger` so they land in the change feed.
4475- Treat these as operator-authored: source writes are gated, and a
4476 per-family ""builder role"" for scoped, non-admin object creation is a
4477 deliberate open design item, not a shipped capability.
4478"
4479storage-modes Collection Storage Modes Data & Storage 300 How collections choose between classic (rewrite-on-write) and append (log-structured) storage, with real numbers on write cost, compaction, and current limits. "A collection stores its records one of two ways. Both live in the same
4480single `records.tsv`, both are served by the same API, permissions, cache,
4481and generators, and both satisfy the invariant in
4482[`append-only-storage-design.md`](/docs/append-only-storage): the file
4483alone is the complete truth.
4484
4485## Classic (the default)
4486
4487Every write atomically rewrites the whole file (temp file + rename). Every
4488row appears exactly once. This is the right mode for what collections
4489usually are — hundreds to tens of thousands of records — and it is what
4490every collection uses unless its schema says otherwise. Nothing existing
4491changed modes; there is no migration.
4492
4493- Write cost grows with collection size (measured: ~4ms at 1k rows,
4494 ~284ms at 100k, ~2.8s at 1M — per write).
4495- The file never contains history; `cat` shows current state only.
4496
4497## Append (opt-in per collection)
4498
4499Declare it in the schema:
4500
4501```json
4502{ ""name"": ""events_log"", ""storage"": ""append"", ""fields"": [ ... ] }
4503```
4504
4505The collection becomes a last-wins log inside the same file: create,
4506update, and delete each append one row instead of rewriting. An internal
4507first column `_op` marks ordinary rows (empty) and deletions (`del`) — it
4508is never visible in schemas, API responses, or returned records, and no
4509schema may declare a field named `_op`. Reads fold the log newest-wins;
4510list order matches classic mode exactly.
4511
4512- Write cost is near-constant (measured: create ~4ms at 100k rows, ~34ms
4513 at 1M; update ~1–9ms — versus seconds in classic mode at that scale).
4514- Until compaction, `cat` shows the row's full history and deletions —
4515 an inspectable audit trail, by design.
4516- Mode transitions are just writes: adding `""storage"": ""append""` takes
4517 effect on the next write (one final rewrite adds `_op`); removing it
4518 compacts back to a classic file on the next write.
4519
4520### Compaction (the VACUUM analog)
4521
4522Superseded rows and tombstones accumulate until compaction folds the file
4523back to live rows only (atomic rewrite, under the writer lock):
4524
4525- Manually: `object_records.compact_collection(""name"", base_dir=...)`
4526 (returns rows/bytes before and after).
4527- Automatically: when a read observes more dead rows than live ones and
4528 the file exceeds `DBBASIC_APPEND_COMPACT_MIN_ROWS` (default 10000)
4529 physical rows, the **next write** compacts instead of appending. Reads
4530 never rewrite anything.
4531- Via HTTP (admin-gated, same posture as other mutating admin record
4532 routes): `POST /admin/collections/{collection}/compact` runs
4533 `compact_collection` and returns its rows/bytes-before/after summary
4534 plus `duration_ms`. 404 for an unknown collection, 400 for a collection
4535 not currently in append storage mode. `GET /admin/storage` reports
4536 per-collection compaction observability -- `{""physical_rows"",
4537 ""live_rows"", ""dead_rows"", ""bloat_ratio"", ""file_bytes"",
4538 ""sidecar_present"", ""compaction_flagged""}` for every append-mode
4539 collection (`object_records.append_collection_stats` /
4540 `list_append_collection_stats`). This endpoint is cheap by
4541 construction: it never folds records.tsv to answer, preferring a warm
4542 in-process cache entry or the id->offset sidecar's own row count; a
4543 collection neither can answer comes back with `""estimated"": true` and
4544 only `file_bytes` populated (`physical_rows`/`live_rows` null) rather
4545 than paying an O(file) parse on a status call.
4546- Via the daemon (object_daemon.py, optional -- nothing else depends on
4547 it running): `process_compactions` polls every
4548 `DBBASIC_COMPACTION_INTERVAL_SECONDS` (default 3600, tracked by a
4549 `.compaction_last_run` marker file under the data dir rather than an
4550 in-process timer, so the interval survives a daemon restart) and
4551 compacts any append-mode collection whose `bloat_ratio` is at or above
4552 `DBBASIC_COMPACTION_BLOAT_RATIO` (default 1.0 -- dead rows at least
4553 matching live rows) AND whose physical row count is at or above
4554 `DBBASIC_APPEND_COMPACT_MIN_ROWS`. A failure compacting one collection
4555 is logged and skipped; it never stops the rest of the pass.
4556
4557### Crash behavior
4558
4559A write interrupted mid-row leaves a torn final line. Readers ignore it;
4560the next writer truncates it away before appending. Compaction and classic
4561mode keep full temp+rename atomicity.
4562
4563### Current limits (honest)
4564
4565- Collections larger than `DBBASIC_RECORDS_CACHE_MAX_ROWS` (default
4566 500k) fall out of the in-process cache. Point operations (create's
4567 duplicate check, get, update, delete) no longer pay a full fold-parse
4568 above that size: an id→offset sidecar (design doc, item 4;
4569 `.records.oidx` next to `records.tsv`, derived and disposable) answers
4570 them by seek instead (measured: create/update ~1ms, get ~0.3ms at 1M
4571 rows, versus ~2.8s for a full fold-parse before the sidecar existed).
4572 The sidecar builds lazily on first use past the threshold (one
4573 sequential scan, ~2s at 1M rows) and self-heals from any inconsistency
4574 by rebuilding. **List and read-all-records stay unchanged** above the
4575 threshold: they still fold the whole file, since ordering and
4576 windowing need the full picture -- a secondary sidecar for that is
4577 future work (design doc, item 5). At or below the threshold, nothing
4578 changed: the in-process cache still serves everything, sidecar or not.
4579- At or below the threshold, a WARM cache entry for an append-mode
4580 collection that grows in place (another process, the CLI, or a sibling
4581 worker appending — same inode, size only) is caught up with a
4582 tail-delta fold of just the new rows instead of a full re-parse of the
4583 whole file (design doc, Sidecars: ""when a stat signature changes by
4584 growth alone, parse only the tail delta""). Measured: reading a
4585 400,000-row collection right after an external +100-row append dropped
4586 from ~742–815ms (full re-fold every time, regardless of how small the
4587 growth was) to ~74–100ms (fold just the 100 new rows) — roughly 8x at
4588 this size, and the gap widens with collection size since the old cost
4589 was O(file) and the new one is O(delta). A delta containing any
4590 deletion falls back to a full fold (deletes shift every later row's
4591 position, which the cheap merge doesn't model); growth past the cache
4592 threshold is still evicted per the existing row-count rule above.
4593- A process's own append updates its cache entry without re-reading the
4594 file (previous entry + the one row) **only when that entry was current
4595 up to the byte where the row landed**. If another process appended
4596 first, the entry is left stale and the next read catches up with the
4597 tail-delta fold above. Until this check existed, the stale entry was
4598 extended anyway and stamped as current: the other process's record
4599 vanished from this process's lists and lookups, and a create reusing
4600 its id was accepted and overwrote it.
4601- Cold reads of an append file cost ~1.6x a classic parse (fold
4602 overhead). Compaction restores parity.
4603- Backup **preview/diff** interprets `_op`: for append-mode collections
4604 (backup side, live side, or both — a backup taken before a mode switch
4605 compares fine against a now-classic or now-append live file) it folds
4606 the log last-wins-by-id before diffing, so `_op` never appears as a
4607 field and a tombstoned id is treated as absent, not live. Backup/restore
4608 of the file itself is unaffected either way (the file is opaque bytes to
4609 backup).
4610
4611## Choosing
4612
4613Classic for ordinary app data (the default is correct). Append for
4614write-hot or log-shaped collections: event logs, impressions, telemetry,
4615game/world state, anything updated far more often than it is read cold.
4616When in doubt, stay classic — switching later is one schema edit.
4617"
4618append-only-storage Append-Only Storage: Design Decisions Data & Storage 310 Design decisions for making collection writes O(1) via append-only TSV storage, while preserving the single-file-of-truth invariant. "Decisions for the next storage phase: making collection writes O(1) while
4619keeping the system's defining constraint intact. Written before
4620implementation, like docs/event-hooks-decisions.md, so the direction is on
4621record with its reasoning.
4622
4623## The Invariant (decided first, everything else follows)
4624
4625**A collection either IS one `records.tsv` file, or can deterministically
4626emit one.** The single TSV is the source of truth: complete on its own,
4627greppable, diffable, backed up with `cp`. Anything clever — indexes, caches,
4628offsets — is a *sidecar*: derived, disposable, and rebuildable from the TSV
4629alone. No storage feature may ever be added that cannot be flattened back to
4630the single file. (This also binds any future alternate backend: its contract
4631includes materializing the canonical TSV on demand.)
4632
4633## Why Change Anything
4634
4635Measured (2026-07-12, M1, local SSD, after the read-cache work): `create` and
4636`update` rewrite the whole file per record — 10.5s at 1M rows, 2.5min at 5M.
4637Reads scale fine (O(1) indexed `get` holds at millions of rows); writes are
4638the wall. Motivating workloads: game-server state (write-hot large
4639collections), ad-exchange impression logs, price history — all append-shaped.
4640
4641## The Design
4642
4643Append-only *within the single file*:
4644
4645- **Create** appends one row. O(1).
4646- **Update** appends a superseding row with the same id. Reads resolve
4647 **last-wins** per id. (Note: today's duplicate-id behavior is
4648 first-occurrence-wins; this flips deliberately and must be called out in
4649 the change.)
4650- **Delete** appends a tombstone row (representation decided at
4651 implementation — a reserved marker that cannot collide with user data and
4652 survives the csv layer; it must be visible and obvious in a raw `cat`).
4653- **Compaction** is the only remaining whole-file rewrite: collapse to live
4654 rows via the existing atomic temp+rename, run on a schedule or when the
4655 superseded-row ratio passes a threshold — never inline in a request. Until
4656 compaction, the file contains its own row history: grep shows every version
4657 a record went through. That is a feature (an inspectable audit trail), not
4658 merely tolerated.
4659- **New-column handling**: today a new field triggers a full-file header
4660 rewrite. Append-only tolerates rows shorter than the current header (they
4661 read as empty — the semantics that already exist), so a header change can
4662 ride the next compaction rather than forcing an immediate rewrite.
4663
4664## Sidecars
4665
4666- **id → byte-offset index** file per collection: maps each id to the offset
4667 of its *latest* row. Enables point reads by seek without parsing the file.
4668 Derived and disposable — rebuild is one sequential scan. Never required for
4669 correctness; readers without the sidecar fall back to scan.
4670- **The in-process read cache** (already shipped) composes into incremental
4671 reads: cache entries remember the byte offset they consumed; when a stat
4672 signature changes by growth alone, parse only the tail delta — O(new rows),
4673 not O(file). This dissolves the ""big hot collection vs. cache eviction""
4674 tension for write-hot workloads.
4675- Cache-comment revision required at implementation: the current
4676 `_RECORDS_CACHE` reasoning leans on every write producing a fresh inode via
4677 atomic rename. Appends mutate in place (same inode; mtime/size change).
4678 Signature checks still detect change, but the comment's argument must be
4679 rewritten for the append case, including the torn-tail rule below.
4680
4681## Crash Safety
4682
4683Rename-atomicity is replaced (for appends) by the classic log rule: a torn
4684final line — no trailing newline, or a row that fails to parse at EOF — is
4685ignored by readers and truncated/overwritten by the next writer. Appends are
4686flushed per write; fsync policy is a deliberate knob (default: flush, no
4687fsync per row — same durability class as today's writes; an env for
4688fsync-per-append where a workload wants it). Compaction keeps full
4689temp+rename atomicity.
4690
4691## Concurrency
4692
4693Writers still serialize under the existing per-collection file lock — but the
4694critical section shrinks from ""rewrite everything"" to ""append one line,"" so
4695effective write throughput rises by orders of magnitude without new
4696machinery. Readers remain lock-free; the stat-signature cache covers
4697cross-process coherence, as today.
4698
4699## What This Buys, Honestly
4700
4701- The measured interactive ceiling moves from tens of thousands of rows to
4702 **tens of millions** for ordinary use, and far beyond for append-heavy,
4703 read-by-id workloads (a 15GB file appends in microseconds and point-reads
4704 by seek).
4705- What stays hard: rich secondary queries (by customer, by date range, by
4706 status) still scan unless a sidecar index for that field exists. Secondary
4707 sidecar indexes are future work, same rules: derived, disposable.
4708- What is out of scope on purpose: cross-collection transactions,
4709 replication, multi-writer scaling. Single VM, one honest file, is still the
4710 product.
4711
4712## Migration and Compatibility
4713
4714Opt-in per collection (schema flag or storage marker), default unchanged —
4715existing collections keep exact current behavior until switched. A compacted
4716append-only file is byte-compatible with a classic one (header + unique
4717rows), so switching a collection back is: compact, remove the marker.
4718Package installs, backups, and restore already treat `records.tsv` as opaque
4719content and keep working; the backup CLI gains nothing to learn (the sidecar
4720index is rebuildable, so backups may ignore it entirely).
4721
4722## The Escape Hatch (documented now, built never — until real need)
4723
4724If a collection someday truly outgrows one file (billions of rows, heavy
4725secondary queries), the answer is a **pluggable per-collection backend**
4726under the identical schema/permission/API surface — SQLite being the obvious
4727candidate (single file, stdlib, public domain). The invariant above still
4728binds it: such a backend must emit the canonical `records.tsv` on demand.
4729This paragraph exists so nobody ever ""improves"" the TSV engine into a
4730half-database; past the envelope, graft a real one underneath instead.
4731
4732## Prior Art
4733
4734The delta-plus-merge shape has flat-file ancestry: Strozzi NoSQL (1998), the
4735system that coined ""NoSQL,"" documented exactly this pattern for big tables —
4736extract a small working table, edit it, background-merge it into the sorted
4737master, keeping the old table and the delta ""for backup and/or journaling
4738purposes."" This design automates that workflow inside one file. Its lock
4739strategy (a .lock sidecar next to the table, cleaned on interrupt) is also
4740the mechanism this codebase independently uses. The offset-sidecar planned
4741below is the trick genomics' tabix proved on TSV at petabyte scale.
4742
4743## Build Order
4744
47451. Tail-delta read cache (offset-tracking) — useful even before append-only
4746 lands, zero format change.
47472. Append-only create/update/delete + torn-tail recovery + last-wins reads,
4748 behind the per-collection opt-in.
47493. Compaction (manual/admin trigger first, then scheduled via the daemon).
47504. id→offset sidecar for seek-based point reads on large collections.
47515. Secondary-field sidecars — only when a named workload demands one.
4752"
4753write-pipeline The Write Pipeline: What Happens, In What Order, And What Can Stop It Data & Storage 320 A stage-by-stage reference for every synchronous, fan-out, and asynchronous step a record write goes through, with each stage's failure semantics. "[`zero-to-code.md`](/docs/zero-to-code) says where each kind of logic lives.
4754This page is its runtime twin: when a record is written, **every stage that
4755runs, in order, with its failure semantics** — because ""code working with
4756code, signals going around"" is exactly where frameworks went dark. Django
4757signals and Rails callbacks earned their reputation not because reactions
4758are wrong but because nobody could answer *why did my record change?*
4759without a debugger. Here the pipeline is fixed, short, and this page is its
4760single description. Verified against `object_server.py` and
4761`object_records.py`; if this page and the code disagree, fix one of them —
4762that disagreement is a bug.
4763
4764## The synchronous path (inside the request)
4765
4766Everything here happens before the client gets its response, in this order:
4767
4768| # | stage | on failure | lives in |
4769|---|---|---|---|
4770| 1 | **permission check** (collection + row rules) | 403, nothing ran | policy |
4771| 2 | **field-write denial** (schema field permissions) | 403, names the fields | schema |
4772| 3 | **owner stamp** — sessions get `owner_id` written server-side; clients cannot spoof it (admin *tokens* skip this: seeding and migration set ownership deliberately) | — | server |
4773| 4 | **pre-write hook** (`hooks.before_write`) — may reject (its own 4xx, or 503 for an unreadable read) or transform (stamp fields; id/owner/read-only/computed protected) | **fails CLOSED**: a broken hook is a 500 and no write | `hook/` object |
4774| 5 | **auto `created_at`**, then **computed fields materialize** — rollups first, then formulas, so a formula may read a rollup | a broken formula stores `""""` — **fails SOFT**, the write proceeds | `object_computed` |
4775| 6 | **schema validation** — types, required, enums, relations-exist, integer-cents; runs on the *final* record, so a hook's transform is validated too | 400, no write | schema |
4776| 7 | **transition check** — is this status move declared, and may *this* subject make it (`when` guards) | 403/409, no write | schema |
4777| 8 | **take the check locks the write needs** (schema **`locked_checks`** declared on, or reading, this collection or its rollup parents; sorted, before any file lock), then **the collection's file lock**, and inside both check what must hold against the rows *as they are now*: the id is new (create), `If-Match`/`expected_rev` still matches (update), the stored record is not frozen by a schema **`locked_when`** rule (update, delete), no other record holds a key a schema **`unique`** constraint covers (create, update), and every selected **locked check** allows it (create, update, delete) | 409 (a check's 4xx; 503 when it cannot decide), no write | `object_records` |
4778| 9 | still inside the lock: **persist**, then the **change-log entry** (actor, before/after, changed fields) | write errors surface as 4xx/5xx | `object_records` |
4779
4780**Only stage 8 is atomic with the write.** Stages 1–4 read whatever they
4781read *before* the lock: two overlapping requests can both pass the same hook
4782and both arrive at stage 8. A rule of the form ""this value appears once""
4783therefore belongs in `unique`, not in a hook that looks for an existing row
4784— that hook passes twice. A rule of the form ""this record is settled""
4785belongs in `locked_when`, not in a hook that reads `existing.status` — that
4786hook is handed the record as it was before the lock, and an edit overlapping
4787the approval is written onto the approved row. A rule of the form ""this sum
4788stays under what another collection says"" belongs in `locked_checks`, whose
4789lock holds the other collection still. (An update re-reads its record under the lock and
4790runs stages 5–7 there; that makes them consistent with the stored record, not
4791with other records.) Stage 8 also runs for writers that never see stages 1–4:
4792handlers, the daemon, imports and seeds call `object_records` directly.
4793
4794Two asymmetries in there are doctrine, not accident: **gates fail closed,
4795derivations fail soft** (a validation gate that silently passes on error is
4796not a gate; a caption that blanks on error is just a blank caption), and
4797**hooks run before validation** so that what a hook stamps is still checked
4798like any client input.
4799
4800**A delete is the short version of the same path**: stage 1 (permission,
4801checked against the stored row), stage 4, stage 8 (`locked_when` and the
4802locked checks whose `on.delete` is true),
4803stage 9. The hook is called with
4804`action: ""delete""` and the row about to go; it may allow or reject, and a
4805transform is a broken answer (500, nothing deleted). There is nothing to
4806stamp, compute or validate. Until deletes reached stage 4, any rule a hook
4807enforced about a settled record could be walked round by deleting it.
4808
4809## The fan-out (after the write, same request, best-effort)
4810
4811Once the record is durably written, the server fans out — in this order,
4812each stage isolated so one failing never blocks the next, and none of them
4813can un-write the record:
4814
48151. **rollup re-triggers** — a payment write recomputes its invoice's rollup
4816 fields (single-hop by design: a thread-local guard stops A→B→A cascades;
4817 a chain that needs more hops is a design smell, not a setting)
48182. **realtime push** — permission-filtered signal (collection, id, action);
4819 subscribers re-fetch through the enforced API, so the socket never
4820 leaks record bodies
48213. **event handlers** (`HANDLES` objects) — the reaction layer: composers,
4822 status flips. Payload carries the raw verb (`create`) while the event
4823 name uses the participle (`…created`) — accept both
48244. **durable event log** (when enabled) — for pollers and webhooks
4825
4826## The asynchronous tail (the daemon, seconds later)
4827
4828Independent passes over the change log and collections, each with its own
4829cursor, each at-least-once: **notify** (rules → in-app/email intents),
4830**email outbox** drain, **change dispatch** (off by default — replays
4831handlers for storage-level writes so reactions stop depending on which
4832path wrote), **auto-transitions** (the 48h approve), **scheduled runners**
4833(aging, dunning, recurring journals, matcher, escalation — every run's
4834outcome a `scheduler_runs` record), **queue messages** (delay, retry,
4835backoff).
4836
4837## How chains work without becoming Django signals
4838
4839The reaction graph is real: a payment triggers the books composer, which
4840writes a journal, whose lines re-trigger the journal's rollups. What keeps
4841it legible instead of haunted:
4842
4843- **One hop is synchronous, everything else is a record.** A handler's
4844 write does not re-enter the dispatcher (storage-level writes don't
4845 dispatch), so there is no unbounded cascade — a deeper chain must go
4846 through the change-dispatch pass, which has a cursor, markers, and a log.
4847- **Everything generated says who generated it**: `generated_from`
4848 provenance on composed records, `actor` on every change-log entry.
4849 ""Why did my record change?"" is a query, not a debugging session:
4850 `record_changes` names the actor; a composed journal names its source.
4851- **Idempotency by provenance** means redelivery is safe by construction —
4852 a replayed event composes nothing, so at-least-once is a guarantee, not
4853 a hazard.
4854- **Reactions may not gate and gates may not react**
4855 ([`logic-decisions.md`](/docs/logic-decisions) #6). The moment a reaction
4856 can block a write, or a gate can send an email, the pipeline above stops
4857 being a truthful description — that boundary is what makes this page
4858 possible.
4859
4860## Multi-collection workflows
4861
4862An order becomes an invoice becomes a payment becomes a journal; a task is
4863claimed, submitted, approved, settled. There is deliberately **no workflow
4864engine** — a business process here is a chain of *(transition on one
4865record) → (reaction that writes the next record)*, and each link is
4866individually visible in the table above. The process's state is not hidden
4867in an engine: it IS the records, their statuses, and their provenance
4868stamps, which is why an AI operator can answer ""where is this order stuck?""
4869by reading collections. If a real orchestration need repeats (sagas,
4870compensation across many collections), that is a doctrine-#4 moment —
4871extract it *then*, from the concrete chains that exist.
4872
4873## Reading a live system
4874
4875- `record_changes` — who did what, before/after, per record
4876- `generated_from` — what machine wrote this, from what source
4877- `/scheduler` — what the clock did and what each run returned
4878- execution logs — every hook and handler run, observable like any object
4879- boot lines — the daemon prints every pass's posture (`Books: NOT READY…`,
4880 `Queue: enabled`, `Change dispatch: disabled`) so a disabled layer is
4881 announced, not discovered
4882"
4883durability-and-recovery Durability & Recovery Data & Storage 330 How the object server keeps your data safe and readable in plain text, with crash-safe writes, replayable change logs, and a dedicated conformance suite. "How the object server keeps your data safe, and why you can still read it in
4884fifty years.
4885
4886## The design principle: plain text is the source of truth
4887
4888Every record lives in a tab-separated-values file on disk —
4889`data/collections/<name>/records.tsv` — that you can open with `cat`, `grep`,
4890a spreadsheet, or any programming language's CSV reader, on any operating
4891system, with no special software. There is no proprietary binary format your
4892data can be trapped inside.
4893
4894Everything that makes the store *fast* — the id→offset index, the in-memory
4895read cache — is **derived from the TSV and rebuildable from it**. Delete every
4896index and cache and the database is byte-for-byte identical; you lose speed,
4897never a byte. The canonical data is exactly the set of `.tsv` files, and
4898nothing else is load-bearing.
4899
4900> **Why it matters:** a binary database entombs your bytes in a format that
4901> needs *its own software* to read. Plain text means your data outlives the
4902> software that wrote it.
4903
4904## Graceful degradation
4905
4906Because the store is plain text, corruption **degrades gracefully**. A damaged
4907`.tsv` — or a truncated backup of one — can be opened in any editor and
4908salvaged by hand: at worst a single line is garbled; the file never becomes
4909""won't open."" A corrupted binary database page, by contrast, can render the
4910whole database unreadable without vendor-specific recovery tools, and a torn
4911write can damage internal tree structure catastrophically. Plain text has no
4912structure to catastrophically damage.
4913
4914## Crash safety
4915
4916- **Classic collections** are rewritten with a temp-file-plus-atomic-rename.
4917 A reader always sees either the entire previous version or the entire new
4918 one — never a half-written file.
4919- **Append-only collections** (used for high-write logs) treat an interrupted
4920 write as a torn tail: only the last, incomplete entry is ignored on read;
4921 every fully-written entry before it survives — including rows whose quoted
4922 fields span multiple physical lines (the write-side repair is quote-aware;
4923 see [History: the torn-tail gap](#history-the-torn-tail-write-gap-fixed)).
4924- **Concurrency** is serialized with a kernel file lock (`flock`) that applies
4925 across both threads *and* separate processes, so concurrent writers on a
4926 multi-worker deployment cannot corrupt or lose each other's writes.
4927
4928## Recovery by replay: backup + log
4929
4930Alongside each collection, every mutation is also appended to an independent
4931**change log** — `record_changes/<collection>/changes.jsonl` — recording, for
4932each create/update/delete: a timestamp, the actor, and full *before* and
4933*after* snapshots of the record.
4934
4935This gives you the classic ""restore a backup and replay the log"" recovery
4936model, in plain text:
4937
4938- **Reconstruct a collection from its change log alone.** Replaying the log in
4939 chronological order — apply each `after` snapshot on create/update, drop the
4940 record on delete — reproduces the collection's exact current state. If a
4941 collection file is ever lost or damaged, the change log rebuilds it.
4942- **Point-in-time recovery.** Restore a plain-text backup, then replay the
4943 change log *forward* to a chosen timestamp.
4944- **The change log is itself crash-safe by construction.** It is line-based
4945 (JSON-per-line); a read skips any incomplete final line, so a crash
4946 mid-append costs only that one in-flight entry.
4947
4948The result is **two independent plain-text records of every change** — the
4949collection file and the change log — either of which can reconstruct the
4950other. Your recovery, like your data, needs no special software: a short
4951script replays the log.
4952
4953## How we test durability
4954
4955Durability is verified by a dedicated conformance suite, run deliberately
4956(like a benchmark) rather than on every commit, covering:
4957
4958- **Character-set fidelity** — ASCII and control bytes, multibyte UTF-8,
4959 emoji and grapheme clusters, adversarial Unicode, and arbitrary JSON, each
4960 round-tripped byte-exact through every storage and read path, with no silent
4961 normalization.
4962- **Crash recovery** — a write interrupted at *every byte offset* is simulated
4963 and the store is checked to recover to a valid state with no loss of
4964 committed data — including multi-line quoted rows, whose every-offset sweep
4965 was held as strict xfails until the write-side repair was fixed and is now
4966 an ordinary regression battery.
4967- **Concurrency** — real concurrent processes writing the same collection,
4968 checked for lost updates and corruption.
4969- **Atomicity** — single-record writes are all-or-nothing, and a reader never
4970 observes a torn intermediate.
4971- **Backup, restore, and compaction** — verified byte-exact, including exotic
4972 content, and crash-safe (an interrupted compaction never damages the
4973 original).
4974- **Plain-text rebuild and replay** — deleting every index leaves the data
4975 fully intact and queryable from the TSV alone; a collection is reconstructed
4976 exactly from its change log.
4977
4978The philosophy follows the databases that made testing their reputation: a
4979visible, exhaustive test suite is itself the assurance that the data is safe.
4980
4981## History: the torn-tail write gap (fixed)
4982
4983**Status: fixed (2026-07-30).** This section replaces a ""Known gap"" that
4984stood here for one day — kept as history because the shape of the bug and of
4985its first, reverted fix are both instructive.
4986
4987**The bug.** Before an append lands, `_repair_torn_tail` trims any partial
4988row left by an interrupted write. It found ""the last row boundary"" by
4989scanning backwards for a newline — quote-blind, so a newline *inside* a
4990quoted multi-line field looked like a boundary. Worse, its fast path
4991returned untouched any file whose final byte was `\n`, including a newline
4992inside an unclosed quote — skipping repair in exactly the case that needed
4993it. A crash mid-multi-line-row could then swallow the next appended row into
4994the open quote. Exposure: ~97% of such a row's write window.
4995
4996**The first fix, and why it was reverted.** It gated the repair on the
4997records cache's `covered_bytes`. Two flaws, found the second time around:
4998that value lives only in process memory (gone precisely when a crash makes
4999repair matter), and — the actual killer — a full parse of a *torn* file
5000stores `covered_bytes` equal to the whole file size, because the read fold
5001""accounts for"" the torn bytes by knowing they are torn. So a warm cache
5002reported clean on exactly the files needing repair. Under pytest the cache
5003was warm from other tests; standalone it was cold. ""Fails in pytest, passes
5004standalone"" was that, nothing more.
5005
5006**The fix that stands.** The repair scans forward with the same quote-aware
5007`committed_prefix_len` the read path and the backup index use — one
5008implementation, three users, no copies to drift. A cache may only ever
5009*skip* the scan, never choose a truncation point, and the only cache
5010consulted is the id-sidecar's, whose `covered_bytes` values are genuine row
5011boundaries by construction. Cold (post-crash) the repair pays one full scan,
5012which is the honest price of the one moment a torn tail can exist. Two
5013neighbouring holes were closed in the same pass: an intact-but-unterminated
5014*header* no longer truncates to a headerless file that reports success and
5015then fails every read (the header is restored from the schema), and a
5016sidecar corrupted with non-UTF-8 bytes now rebuilds instead of raising on
5017every read.
5018
5019**Verification.** The strict-xfail acceptance tests that mapped the trigger
5020surface — every byte offset from a row's first embedded newline to its last
5021— were rewritten into the regression guards they were designed to become,
5022and the every-offset sweeps now pass as ordinary tests.
5023"
5024backup-restore Backup and Restore Data & Storage 340 How to create, verify, and restore runtime backups of a DBBASIC Object Server instance, including scheduled backups and the deliberately CLI-only restore path. "DBBASIC runtime backups protect the object loop by keeping source, state, logs,
5025files, versions, schemas, and collection records recoverable together.
5026
5027The public backup helper is:
5028
5029```bash
5030python -m object_backup
5031```
5032
5033It creates a tar/gzip archive with a JSON manifest and a narrow runtime backup
5034set.
5035
5036## Included
5037
5038Runtime backups include:
5039
5040```text
5041objects/
5042data/state/
5043data/logs/
5044data/versions/
5045data/source_changes/
5046data/schema_versions/
5047data/record_changes/
5048data/package_changes/
5049data/file_changes/
5050data/files/
5051data/schemas/
5052data/collections/
5053```
5054
5055That covers object source, object state, current logs, rotated compressed logs,
5056source versions, source change history, schema change history, record change
5057history, package change history, object file change history, object-owned
5058files, schema metadata, and TSV-backed collection records.
5059
5060## Excluded
5061
5062Runtime backups deliberately exclude:
5063
5064- deployment secrets
5065- environment files
5066- systemd service files
5067- git history
5068- virtualenvs
5069- caches
5070- lock files
5071- temp files
5072- ephemeral rate-limit files
5073
5074The environment file and service unit still need operator-managed backups, but
5075they should be stored through a secret-aware server backup process, not inside
5076the portable runtime archive.
5077
5078## Create
5079
5080```bash
5081mkdir -p /var/backups/dbbasic-object-server
5082
5083python -m object_backup create \
5084 /var/backups/dbbasic-object-server/runtime-YYYYMMDD-HHMMSS.tar.gz \
5085 --objects-dir /var/lib/dbbasic-object-server/objects \
5086 --data-dir /var/lib/dbbasic-object-server/data
5087```
5088
5089The command writes `dbbasic-backup-manifest.json` inside the archive. The
5090manifest records the format version, timestamp, included roots, file count, byte
5091count, and warnings.
5092
5093## Restore Points
5094
5095Server-side mutations that can rewrite multiple runtime files should create a
5096restore point before writing. Package installs use:
5097
5098```python
5099object_backup.create_runtime_restore_point(""package-hello-world"")
5100```
5101
5102By default, restore points are written under:
5103
5104```text
5105data/backups/
5106```
5107
5108Set `DBBASIC_BACKUPS_DIR` to move those archives to a mounted backup volume or
5109another operator-managed path. Runtime backup archives do not include
5110`data/backups/`, so restore points do not recursively back up other archives.
5111
5112Every install writes a full archive by default, which on a large data
5113directory adds up quickly when reinstalling many packages. To share one
5114archive, create it once with `POST /admin/backups` and name it in each
5115install body: `{""allow_replace"": true, ""restore_point"": ""<backup id>""}`. No
5116new archive is written, and the install's change-log entry records the named
5117one, so `POST /packages/{id}/restore` still works. An unknown or malformed id
5118is refused (409 / 400) before anything changes. See ""Upgrade"" in
5119[`single-vm-deployment.md`](/docs/single-vm-deployment) for the batch recipe.
5120
5121Package restore uses the recorded restore point from a package install change,
5122not an arbitrary package path. That package-scoped HTTP route
5123(`POST /packages/{id}/restore`, gated by `DBBASIC_ENABLE_PACKAGE_RESTORE`)
5124is separate from full-runtime restore, which stays CLI-only. It calls
5125`restore_runtime_backup(..., overwrite=True, prune_extra=True)` so files created
5126by the package are removed if they were not present in the snapshot. Pruning is
5127limited to the runtime roots; `data/backups/` is left alone.
5128
5129A package restore rolls back the runtime, not the record of what happened.
5130What it does to each runtime root:
5131
5132| Root | Package restore |
5133| --- | --- |
5134| `objects/` | rolled back to the snapshot (files added since are removed) |
5135| `data/state/`, `data/files/`, `data/user_files/` | rolled back |
5136| `data/collections/`, `data/schemas/` | rolled back |
5137| `data/package_baselines/`, `data/reconciles/` | rolled back (they describe the installed packages) |
5138| `data/permissions/policy.json` | rolled back, only after the policy difference is shown and confirmed (below) |
5139| `data/permissions/audit.jsonl` and its rotated segments | **kept** as on disk |
5140| `data/identity/users.tsv`, `accounts.tsv` | **kept** as on disk: a user disabled, or a role removed, since the snapshot stays that way |
5141| `data/versions/` (object source versions) | **kept**; the restore adds a version |
5142| `data/source_changes/` | **kept**; the restore adds a `source_rollback`, `source_create` or `source_destroy` entry |
5143| `data/schema_versions/` | **kept**; the restore adds a version |
5144| `data/record_changes/` (and `archive/`) | **kept**; the restore adds a `create`/`update`/`delete` entry per row it changed |
5145| `data/file_changes/` | **kept**; the restore adds a `file_create`/`file_update`/`file_delete` entry |
5146| `data/package_changes/` | **kept**; the restore adds `restore_requested` and `rolled_back` |
5147| `data/logs/` (object logs, rotated logs) | **kept** |
5148
5149Every entry the restore adds names who ran it (the actor), when, and the
5150snapshot (`package_restore: {package_id, from_change_id, restore_point}` in a
5151source or file change's `details`, and the message
5152`Package restore: <id> rolled back to before change <change_id>` on versions
5153and record changes). An object source the restore replaces or removes is
5154saved as a version first when no version already holds it, so nothing the
5155rollback overwrote is lost: it can be brought back with the usual source
5156rollback. The response's `history` gives the counts of entries added and any
5157that could not be written (`failed`, `errors`); the runtime is restored
5158either way.
5159
5160### The policy difference comes first
5161
5162Rolling back can put back an older, looser permission policy: a deny rule
5163added since the snapshot to close a hole would silently disappear. So a
5164package restore is two steps whenever it changes who may do what:
5165
51661. `POST /packages/{id}/restore` with `{""change_id"": ""..."", ""preview"": true}`
5167 writes nothing and returns `policy_diff` (every rule added, removed or
5168 changed, reordered rules, access mode, admin roles, user roles, role
5169 metadata, and the field permissions in `data/schemas/`), a readable
5170 `policy_diff_text`, and `policy_diff_hash`.
51712. The apply, `{""change_id"": ""..."", ""confirm"": ""restore-runtime"",
5172 ""policy_diff_hash"": ""<from the preview>""}`, recomputes the difference and
5173 is refused with `409` if the hash is missing (and the policy changes) or
5174 is not the hash of the difference now -- the policy or the snapshot
5175 changed since the preview. The 409 carries the current difference and
5176 hash; look at it again before sending it back.
5177
5178Each change is marked `loosens` (someone may do something they may not do
5179now), `tightens`, or `neutral` (labels, reasons), and `policy_diff.loosens`
5180says whether any change loosens; the error and the text call a loosening
5181restore out in capitals. A change that cannot be proven to tighten counts as
5182loosening: a changed row filter or validity window, rules reordered (the
5183first matching allow wins), any access-mode change other than to
5184`role_based`. A snapshot without `policy.json` is compared as the server's
5185default policy, since the restore prunes the live one.
5186
5187Fail closed: if either policy, or any schema in `data/schemas/`, cannot be
5188read or parsed, the difference cannot be computed and the restore (and the
5189preview) is refused with `409`. Fix or move the unreadable file first.
5190
5191A restore that does not change the policy needs no hash. The difference and
5192its hash are recorded in the `rolled_back` package change.
5193
5194## Verify
5195
5196```bash
5197python -m object_backup verify \
5198 /var/backups/dbbasic-object-server/runtime-YYYYMMDD-HHMMSS.tar.gz \
5199 --json
5200```
5201
5202Verification checks that:
5203
5204- the archive can be read
5205- the manifest is present
5206- the manifest count matches the archive contents
5207- archive paths stay under `objects/` or supported `data/` roots
5208- symlinks, hard links, device files, and other unsafe member types are rejected
5209
5210## Restore
5211
5212Restore is a **deliberate CLI operation**, not an HTTP verb. It is
5213destructive and whole-instance, so it is intentionally not exposed on the
5214admin surface (`/admin/status` reports `capabilities.backups.can_restore:
5215false`); a ""restore"" button one misclick from wiping live data is a
5216footgun. The pairing is: **download a backup from Scroll or
5217`GET /admin/backups/{id}/download` to get it, and this CLI to apply it.**
5218
5219Runtime backups live under `data/backups/` (or `DBBASIC_BACKUPS_DIR`) and
5220are named `YYYYMMDDTHHMMSSffffffZ-<label>.tar.gz` (label `manual` for
5221on-demand, `package-<id>` for install restore points). Always verify
5222first (see above).
5223
5224### Dry-run into clean directories first
5225
5226```bash
5227mkdir -p /tmp/dbbasic-restore/objects /tmp/dbbasic-restore/data
5228
5229python -m object_backup restore \
5230 /var/lib/dbbasic-object-server/data/backups/20260708T145041382734Z-manual.tar.gz \
5231 --objects-dir /tmp/dbbasic-restore/objects \
5232 --data-dir /tmp/dbbasic-restore/data \
5233 --json
5234```
5235
5236By default restore refuses to overwrite existing files, so this dry run
5237never touches a live runtime. Start the server against the restored
5238directories and check it before trusting the archive:
5239
5240```bash
5241DBBASIC_OBJECTS_DIR=/tmp/dbbasic-restore/objects \
5242DBBASIC_DATA_DIR=/tmp/dbbasic-restore/data \
5243uvicorn object_server:app --host 127.0.0.1 --port 8001
5244```
5245
5246Then verify `/health` and representative object routes. A real recovery
5247drill should do this on a second clean VM.
5248
5249### Recovering the live runtime
5250
5251Stop the service first so nothing writes during the restore. Use
5252`--overwrite` to replace existing files, and `--prune-extra` (which
5253requires `--overwrite`) only when you want an exact match to the archive,
5254removing files added since — a powerful, opt-in flag:
5255
5256```bash
5257sudo systemctl stop dbbasic-object-server
5258
5259sudo -u dbbasic /opt/dbbasic-object-server/.venv/bin/python \
5260 -m object_backup restore \
5261 /var/lib/dbbasic-object-server/data/backups/<id>.tar.gz \
5262 --objects-dir /var/lib/dbbasic-object-server/objects \
5263 --data-dir /var/lib/dbbasic-object-server/data \
5264 --overwrite --prune-extra --json
5265
5266sudo systemctl start dbbasic-object-server
5267curl http://127.0.0.1:8001/health
5268```
5269
5270When `--overwrite` would change the permission policy (`policy.json`, or the
5271field permissions in `data/schemas/`), the CLI prints the difference first
5272-- loosening changes marked, the same classification as the package restore
5273-- and asks for `yes` on a terminal. Anything else, or no terminal, refuses
5274and restores nothing; pass `--yes` to apply non-interactively (the
5275difference is still printed, or returned as `policy_diff` with `--json`).
5276To see the difference without restoring:
5277
5278```bash
5279python -m object_backup restore <backup>.tar.gz \
5280 --objects-dir /var/lib/dbbasic-object-server/objects \
5281 --data-dir /var/lib/dbbasic-object-server/data \
5282 --preview # add --json for the structured difference
5283```
5284
5285If either side's policy or a schema cannot be read, the overwrite is
5286refused. Restores without `--overwrite` cannot replace a live policy and ask
5287nothing. The full CLI restore is disaster recovery: unlike the package
5288restore it does write back the histories, the audit log and the identity
5289registry from the archive.
5290
5291Pruning is limited to known runtime roots (`objects/`, `data/state/`,
5292`data/logs/`, `data/collections/`, `data/schemas/`, `data/source_changes/`,
5293`data/package_changes/`, `data/file_changes/`); `data/backups/` is left
5294alone, so restoring never destroys your other archives.
5295
5296## HTTP Surface
5297
5298On-demand backup and download are exposed on the admin API (and used by
5299Scroll's Backup screen) — see
5300[the HTTP contract](/docs/http-api-contract#backups):
5301
5302- `GET /admin/backups` — inventory (`id`, `created_at`, `size`, `kind`, `scope`).
5303- `POST /admin/backups` — create a full-runtime backup now.
5304- `GET /admin/backups/{id}/download` — stream the archive.
5305
5306All admin-gated (a backup holds every record, file and user on the box,
5307so never public; password hashes, sessions, API keys and service keys are
5308left out, see [the HTTP contract](/docs/http-api-contract#backups)). Restore
5309is deliberately absent from this surface — use the CLI above.
5310
5311## Scheduling
5312
5313**For backups that leave the box, use scheduled backups:**
5314set `DBBASIC_BACKUP_DESTINATION` and the daemon writes a hard-linked
5315snapshot there on an interval, keeps a bounded number, and restore-tests
5316every one, with failures reported in `/admin/status`, the dashboard's
5317attention band and the daemon log.
5318
5319The older recipe below still works. The run itself
5320is an external timer (systemd or cron) invoking `object_backup.py create`
5321on a cadence with retention; `DBBASIC_BACKUP_SCHEDULE` records the
5322operator's intent so `/admin/status` and Scroll can display it. A sample
5323daily systemd timer:
5324
5325```ini
5326# /etc/systemd/system/dbbasic-backup.service
5327[Service]
5328Type=oneshot
5329User=dbbasic
5330EnvironmentFile=/etc/dbbasic-object-server.env
5331WorkingDirectory=/opt/dbbasic-object-server
5332ExecStart=/opt/dbbasic-object-server/.venv/bin/python -m object_backup create \
5333 /var/lib/dbbasic-object-server/data/backups/scheduled-%%i.tar.gz
5334```
5335
5336```ini
5337# /etc/systemd/system/dbbasic-backup.timer
5338[Timer]
5339OnCalendar=daily
5340Persistent=true
5341[Install]
5342WantedBy=timers.target
5343```
5344
5345Note that on-box backups do not survive losing the VM — pair them with
5346provider-level disk backups (or copy archives to a bucket) for disaster
5347recovery. On-demand create and download always work regardless of any
5348schedule.
5349"
5350per-tenant-storage Per-Tenant Storage: The SaaS Decomposition Data & Storage 350 A direction note on decomposing one shared collection into per-tenant storage roots — what it buys, what it costs, and why the industry is already headed there. "A direction note, not a build plan. Recorded alongside
5351docs/append-only-storage-design.md because the two together answer ""how far
5352can one TSV go, and what happens at SaaS scale"" — and the answer to the
5353second is not ""a bigger table.""
5354
5355## The Observation
5356
5357The measured storage envelope (docs/append-only-storage-design.md: tens of
5358thousands of rows interactive today, tens of millions after append-only)
5359looks like a limit under the one-big-table model. Per-tenant storage inverts
5360it: a SaaS with 100,000 customers and ""a billion orders"" does not have a
5361billion-row problem — it has 100,000 ten-thousand-row problems, each of
5362which sits in the comfortable center of the measured envelope. The giant
5363commingled table is an artifact of shared-database design, not a law of
5364SaaS.
5365
5366## What Decomposition Buys
5367
5368- **Physical isolation.** Row-level security (`WHERE tenant_id = ?`, one
5369 missing predicate from a breach) becomes filesystem separation. The
5370 permission engine's row filters harden into file boundaries.
5371- **GDPR and export for free.** Right-to-be-forgotten is removing the
5372 tenant's directory. ""Export my data"" is handing over the tenant's own
5373 TSV files — human-readable, Excel-openable, no export pipeline.
5374- **Per-customer backup/restore already exists.** The scoped restore +
5375 read-only preview shipped this cycle applies per tenant with zero new
5376 code: ""restore customer X's notes to yesterday"" is the same operation.
5377- **Per-tenant migrations.** Package upgrades ride the provenance/reconcile
5378 system tenant-by-tenant: incremental rollout, conflicts parked per
5379 tenant, no all-customers-at-once schema locks.
5380- **Noisy neighbors decompose.** One tenant's huge collection cannot slow
5381 another's small one; the records-cache LRU bound doubles as per-tenant
5382 cache fairness.
5383- **Tenant mobility is file movement.** Rebalancing tenants across VMs,
5384 or graduating one outlier to its own instance or to the per-collection
5385 backend escape hatch, is `mv` of a directory. Shared-nothing per tenant;
5386 horizontal scale without a distributed database.
5387- **Metering is `du`.** Storage billing per tenant is a directory size.
5388
5389## Honest Costs
5390
5391- **Cross-tenant queries become scatter-gather.** Admin analytics (""orders
5392 today, all customers"") need rollup collections maintained by the daemon
5393 (aggregates are just another collection), or a scan across tenant dirs.
5394 This is the standard sharding trade and should be designed as rollups,
5395 not ad-hoc scans.
5396- **File-count hygiene.** 100k tenants x N collections is ~1M files —
5397 fine for modern filesystems, but the directory layout should shard
5398 (e.g. tenants/ab/abcd.../collections/...) from day one.
5399- **The single-TSV invariant holds per collection per tenant** — and the
5400 whole-instance view (""all tenants' notes as one TSV"") is itself just a
5401 deterministic concatenation with a tenant column, satisfying the
5402 emit-one-file rule at the aggregate level when ever needed.
5403
5404## Prior Art (the industry is arriving here)
5405
5406Cloudflare Durable Objects (SQLite per entity, storage co-located with
5407logic), Turso (database-per-tenant as a product), the SQLite-per-user
5408pattern generally. Per-tenant single-file storage next to per-tenant code
5409is the current direction of travel; this system's version is the flavor
5410you can `cat`.
5411
5412Also the oldest advice in the flat-file lineage: Strozzi NoSQL's ""Big
5413tables"" doc opens with *""big tables should be avoided in the first place""* —
5414use the Unix filesystem to pre-organize relations and keep each one small.
5415Per-tenant decomposition is that doctrine, systematized.
5416
5417## Current State and Gap
5418
5419Today the platform is multi-tenant by *rows* (owner_id row filters, one
5420shared collection per name) and multi-site by *hosts* (site_hosts). The gap
5421this note names: collections themselves are instance-global. The eventual
5422shape is tenant-scoped collection roots under one instance — same schemas,
5423same permission engine, same generators, same API surface, with the tenant
5424resolved from identity the way hosts are resolved from requests today. Not
5425scheduled; recorded so the append-only and cache work keep it reachable
5426(nothing in either conflicts with tenant-scoped roots — both operate per
5427file).
5428"
5429site-routing Site Routing Sites, UI & Realtime 400 How to turn the object server into a webserver with clean public URLs, a route table, multi-domain hosting, and static asset handling. "Site routing turns the object server into a webserver: clean public URLs
5430(`/about`, `/articles/{uuid}`) resolve to objects, so a whole website can be
5431built, edited, and rolled back through the normal object loop with no deploy
5432step and no per-page reverse-proxy rewrites.
5433
5434It is off by default and enabled per deployment:
5435
5436```text
5437DBBASIC_ENABLE_SITE_ROUTES=true
5438```
5439
5440## Resolution Order
5441
5442Site routing runs only after every built-in route family has declined the
5443path, so reserved surfaces (`/objects`, `/admin`, `/api`, `/identity`,
5444`/login`, `/health`, `/collections`, `/schemas`, `/events`, `/packages`,
5445`/daemon`, `/permissions`, `/logout`, `/signup`, `/verify`, `/reset`,
5446`/reset/confirm`) can never be shadowed by a site page.
5447
5448For everything else:
5449
54501. **Convention.** `/` maps to `site_home`, `/about` to `site_about`,
5451 `/docs/install` to `site_docs_install`. Hyphens become underscores
5452 (`/getting-started` → `site_getting_started`). Creating a page object
5453 creates its URL — the filesystem-routing feel of the original prototype,
5454 kept because it makes the common case zero-config.
54552. **The `site_routes` collection.** Records with `pattern`, `object_id`, and
5456 optional `priority` handle what conventions cannot express:
5457
5458 ```text
5459 id pattern object_id priority
5460 r1 /articles/{article_id:uuid} articles_view 10
5461 r2 /blog/{slug} blog_post 20
5462 ```
5463
5464 Pattern segments are literal text, `{name}` (any single segment), or
5465 `{name:uuid}` (segment must be UUID-shaped — the common case for record
5466 ids, which are UUIDv4 by default). Captured params are merged into the
5467 object's request payload, so `articles_view` reads
5468 `request[""article_id""]`. Lower `priority` wins; ties go to the pattern
5469 with more literal segments.
54703. **`site_404`.** If nothing resolves and a `site_404` object exists, it
5471 runs with the missed `path` in its payload and should return
5472 `status_code: 404`. Without it, the plain JSON 404 stays.
5473
5474## Design Decisions
5475
5476These choices came out of comparing the original prototype's pure filesystem
5477router, the route-table-in-object-state design from the early dbbasic.com
5478plan, and what the public server has grown since:
5479
5480- **Routing only maps URLs; authorization stays in the permission policy.**
5481 The resolved object executes through the normal execution path, so
5482 enforcement, audit entries, execution logs, timeouts, concurrency limits,
5483 and correlation ids all apply. Publishing a page is two audited steps:
5484 create the object, grant `execute` to `public` (or whichever principal).
5485 A file appearing on disk never silently becomes public under enforcement.
5486- **The route table lives in records, not object state.** Records give the
5487 table schema validation, change history, rollback, Scroll editing, and MCP
5488 tools for free. Editing the sitemap is a data change with an audit trail.
5489- **Convention for the 90%, data for the 10%.** Plain pages need no table
5490 entry. The table exists for parameterized routes, renames, and pointing
5491 multiple URLs at one object.
5492- **TLS and static assets stay in the reverse proxy.** Caddy terminates TLS
5493 and should serve `/static/*` from disk with cache headers; site routing
5494 replaces per-page rewrites with one catch-all proxy block.
5495
5496## Deployment
5497
5498With site routing enabled, the Caddy shape becomes: explicit handles for the
5499reserved admin/API surfaces you want public, a `/static/*` file server, and a
5500catch-all `reverse_proxy` instead of a catch-all 404. Under permission
5501enforcement, unrouted or unauthorized paths still return controlled 403/404
5502responses from the server.
5503
5504## Multiple Domains
5505
5506One object server can serve many websites. The `site_hosts` collection maps
5507request hosts to object prefixes:
5508
5509```text
5510id host prefix home_object not_found_object
5511h1 dbbasic.com db
5512h2 example.org eg
5513```
5514
5515With those records, `/` on dbbasic.com serves `db_home` and `/pricing`
5516serves `db_pricing`, while `/` on example.org serves `eg_home` — same server, same
5517data directory, fully separate page namespaces. `home_object` and
5518`not_found_object` default to `{prefix}_home` and `{prefix}_404` (falling
5519back to the generic `site_404`). Hosts without a record keep the default
5520`site_*` behavior, so single-site deployments need no configuration.
5521`site_routes` pattern records take an optional `host` column; host-specific
5522rows only match their domain and beat host-agnostic rows.
5523
5524Pointing a new domain at the server is then:
5525
55261. DNS: point the domain's A record at the VM.
55272. Caddy: add a site block for it and reload — Caddy only answers (and only
5528 fetches certificates) for hostnames it has a block for, and DNS must
5529 already point at the VM for the certificate challenge to succeed. With
5530 the `public_site` snippet defined once at the top of the Caddyfile, each
5531 new domain is three lines:
5532
5533 ```caddyfile
5534 (public_site) {
5535 handle /login { reverse_proxy 127.0.0.1:8001 }
5536 handle /logout { reverse_proxy 127.0.0.1:8001 }
5537 handle_path /static/* {
5538 root * /var/lib/dbbasic-static/{args[0]}
5539 file_server
5540 header Cache-Control ""public, max-age=3600""
5541 }
5542 handle { reverse_proxy 127.0.0.1:8001 }
5543 }
5544
5545 newsite.example {
5546 import public_site newsite
5547 }
5548 ```
5549
5550 Public domains expose only the site surface; keep the admin/API/MCP
5551 handles only on the operations domain, so public sites never route to
5552 the operator surface at all.
55533. Add the `site_hosts` record and create `{prefix}_home` — the site is live.
5554
5555Identity, sessions, records, policy, and audit are shared across domains:
5556one operator account works everywhere, and browsers scope session cookies
5557per domain automatically. Domains that must not share those belong on their
5558own server instance instead (one process per trust boundary).
5559
5560## Static Assets
5561
5562Site CSS, JavaScript, images, and fonts are served by the reverse proxy from
5563a plain directory — never through object execution — so they get file-server
5564performance, gzip, and cache headers:
5565
5566```caddyfile
5567handle_path /static/* {
5568 root * /var/lib/dbbasic-static
5569 file_server
5570 header Cache-Control ""public, max-age=3600""
5571}
5572```
5573
5574Pages reference them normally (`<link href=""/static/site.css"">`). The
5575directory is deploy-time content owned by the service user; treat it like
5576object source (versioned in the site package), not like runtime data.
5577User-uploaded files are different: keep those in the object file APIs so they
5578inherit permissions, audit, and backups.
5579
5580## Writing Site Pages
5581
5582Site pages are normal objects (see [`object-authoring.md`](/docs/object-authoring)): return a dict for
5583JSON, a `content_type`/`body` dict for HTML, use `request[""_identity""]` for
5584per-user rendering, and handle `POST` for forms — browser form posts arrive
5585as parsed fields with the session cookie applied. Ship a site as a package
5586([`package-authoring.md`](/docs/package-authoring)) so it installs with its schema, seed records, and
5587route table rows in one reviewed unit.
5588"
5589generative-ui Generative UI — One Renderer, Every App Sites, UI & Realtime 410 How a collection's schema alone drives list, form, and detail rendering across every app, and why customizing a generated page never means forking generated code. "There is no per-app UI code. A collection's schema drives a single set of
5590generative renderers, served as static scripts (`/list`, `/form`, `/detail`),
5591that turn records into live, permission-checked, realtime surfaces. This page
5592is the overview; the field-level contract is in
5593[`schema-forms.md`](/docs/schema-forms), the behavior decisions in
5594[`ui-decisions.md`](/docs/ui-decisions), and the visual system in
5595[`design-system.md`](/docs/design-system).
5596
5597```mermaid
5598flowchart LR
5599 SCH[""schema<br/>fields · views · capabilities""] --> LIST[""window.dbbasicList""]
5600 SCH --> FORM[""window.dbbasicForm""]
5601 SCH --> DET[""window.dbbasicDetail""]
5602 LIST --> MODES[""list · table · board · tree · calendar""]
5603 LIST --> FSR[""filters · search · sort · row cap""]
5604 FORM --> CTRL[""type-aware controls · validation""]
5605 DET --> COMP[""detail + related + capabilities""]
5606 CL[""change log (websocket)""] -. re-render .-> LIST
5607 CL -. re-render .-> DET
5608```
5609
5610## The list, in five modes
5611
5612`window.dbbasicList(collection, cfg)` resolves `views.list_mode` from the
5613schema and renders one of:
5614
5615- **list** (default) — rich rows: avatar, title, subtitle, meta, tag pills,
5616 owner edit/delete.
5617- **table** — a dense, sortable HTML table over `list_fields`; cells format by
5618 type (money `_cents` → `$`, boolean → Yes/No, datetime → relative, enum →
5619 colored badge), and **relation columns show the target's label, not the raw
5620 id**. Owned rows get the same edit/delete the list has.
5621- **board** — a kanban grouped by an enum field; dragging a card issues the
5622 ordinary status write, so `flow` transitions still gate the move. A board
5623 collection that also has `list_fields` shows a **Board ⇄ Table** toggle whose
5624 choice persists per collection.
5625- **tree** — nests a self-relation (`parent_id`) into a hierarchy.
5626- **calendar** — buckets records by a date field.
5627
5628Every mode shares **one** fetch/sort/cap/search/subscribe pipeline, so all of
5629them inherit:
5630
5631- **filters** — `views.filter_fields` renders a filter bar (enum → select,
5632 boolean → Yes/No); a pick narrows the fetch server-side (`field=value`, after
5633 the permission row filter) and composes with the search box.
5634- **search** — the toolbar box, server-side over the collection's `search`
5635 fields.
5636- **the 50-row cap** with a Show-all toggle (no surface ever renders a
5637 50,000px page).
5638- **realtime** — each surface subscribes to the change log and re-renders when
5639 a record changes, from any tab, user, or agent.
5640
5641A mode whose required field can't be derived (no enum for board, no
5642self-relation for tree, no date for calendar) falls back to the row list with a
5643visible notice — never a blank page.
5644
5645## The form
5646
5647`window.dbbasicForm(collection)` builds a record form from the schema: field
5648order from `forms.default.fields`, controls from field semantics (enum →
5649select, relation → picker, boolean → checkbox, date → date input, textarea,
5650number, text), and labels/help/required/max-length from the field. It handles
5651create (POST) and edit (PUT), sets `id`/`owner_id`/`created_at` automatically,
5652never writes computed/read-only fields, and supports conditional field
5653visibility (`visible_when`). See [`schema-forms.md`](/docs/schema-forms).
5654
5655## The detail page
5656
5657`window.dbbasicDetail` renders one record read-only by reusing the form's own
5658field renderer in read-only mode — no second field renderer to keep in sync. It
5659adds owner-only Edit/Delete (reusing the form's edit pipeline), always shows
5660record metadata (`created_at`/`updated_at`) even when `detail_fields` curates
5661the main fields, and auto-mounts any declared **capabilities** (comments,
5662attachments, sharing — see [`capabilities.md`](/docs/capabilities)) below the
5663detail. Composed detail pages are `views` records with a `detail` block plus
5664`related` child blocks; the view renderer
5665(`app-views/objects/site/view_render.py`) assembles them.
5666
5667A `textarea`-type field shown read-only gets a safe, minimal markdown
5668subset (bold, italic, links, paragraph breaks) — the same transform the
5669standalone `markdown` block below applies — instead of plain escaped text
5670in a `<span>`, which used to collapse multi-line content into one
5671run-together line.
5672
5673## Other view block kinds
5674
5675Beyond `list`/`form`/`detail`/`related`, a view's `blocks` array can also
5676declare:
5677
5678- **`markdown`** — a block of static prose baked directly into the view
5679 definition (`{kind: ""markdown"", text: ""...""}`), the same escape-first,
5680 safe-subset renderer as the textarea treatment above.
5681- **`reader`** — `{kind: ""reader"", url: ""...""}` fetches a URL through the
5682 flag-gated, signed-in-only `POST /api/read` and renders title + body text
5683 + a numbered link list. See [`shell-and-ai.md`](/docs/shell-and-ai)'s
5684 ""Reading the Web"" section for the SSRF posture and the voice-navigation
5685 loop this backs.
5686- **`count`** / **`aggregate`** — live stat cards over a collection (row
5687 count, or a sum of numeric/`_cents` fields, with an optional
5688 balanced/not-balanced badge for double-entry-style checks).
5689- **`thread`** — sugar for a comment/reply thread capability.
5690- **`object`** — mounts an arbitrary object's own rendered output inline.
5691
5692Every kind subscribes to its source collection and re-renders live, the
5693same as `list`/`related`. An unrecognized kind (or one missing a required
5694field) renders a small ""unsupported"" placeholder card rather than breaking
5695the page.
5696
5697## Why this is the point
5698
5699Adding an app is a schema file. The list, the table, the board, the toggle,
5700the filters, the form, the detail page, badges, the row cap, relation labels,
5701realtime, and owner actions all fall out of it — the same code for every app.
5702The measure isn't the feature list (anyone can claim those); it's the amount of
5703per-app code, which is a schema and at most one page object.
5704
5705## This is not scaffolding
5706
5707Rails scaffolds and Django's startapp share one failure that defined a
5708generation of frameworks: the generator emits **code**, you edit it, and from
5709that moment you own all of it. The generator can never help that screen again
5710— template improvements don't flow, upgrades don't apply, and nothing records
5711which parts you changed. The fork happens at generation time and diverges
5712silently forever. ""Eject"" is the same failure with a button on it.
5713
5714The rule that keeps this system on the other side of that line:
5715
5716> **Generated output is never materialized, so it can never be edited.**
5717> A page is a view record *interpreted at request time* by a renderer that is
5718> itself an ordinary object. Customizing never means editing emitted code,
5719> because there is no emitted code. You either change **data** (and keep
5720> receiving renderer improvements) or you write **your own object** (which was
5721> never generated, so nothing was forked).
5722
5723### The customization ladder
5724
5725Each rung says exactly what you take ownership of and what keeps flowing:
5726
57271. **Edit the block config** (filters, `title_field`, sort, `row_limit`) — you
5728 own the config; every renderer improvement still flows.
57292. **Add blocks** — a view is a list of blocks; put an `aggregate` summary or
5730 `markdown` intro above the generated list. Same ownership as (1).
57313. **Customize a shipped view record** — the upgrade system detects it against
5732 the package baseline and parks a reconcile instead of clobbering: the system
5733 *records* what you own and shows you when upstream moved. Scaffolding's
5734 fork is silent; this one has a ledger.
57354. **Drop an `object` block into a generated page** — one hand-written panel
5736 among generated ones (`{""kind"": ""object"", ""object_id"": ""site_my_panel""}`).
5737 You own that panel; the rest of the page keeps flowing. It runs through the
5738 ordinary execution path, so permissions and audit apply — the block widens
5739 what a page can *show*, never what a viewer may *see*.
57405. **Write the whole page object.** Convention routing means creating
5741 `site/notes.py` instantly overrides the generated `/notes` — and deleting
5742 the file reverts to it. The override is total, explicit, and reversible,
5743 and it is visible in the objects listing rather than buried in a diff
5744 against generator output.
5745
5746### Why replacing a page is safe here and wasn't in Rails
5747
5748The deep failure of scaffolds wasn't the HTML — it was that the scaffold
5749contained **rules** (validations in the controller, logic in the view), so
5750editing it forked the rules. Here the doctrine is that *a page may never be
5751the only place a rule exists*: enforcement lives in the schema, hooks,
5752transitions, and permissions, on the shared write path that the JSON API, MCP
5753agents, and the websocket all go through.
5754
5755That doctrine is not just policy — the architecture makes the wrong place
5756**fail loudly**. A rule written into a page object simply does not gate API or
5757MCP writes, so the mistake shows up the first time anything that isn't the
5758page touches the collection. In Rails, logic in the controller *worked* for
5759web users, which is exactly why the fork stayed invisible for years. The
5760residual risk here is someone treating rung 4–5 as a place to put gates; the
5761system's answer is that gates there provably don't hold, and the hook is one
5762file away.
5763
5764## Related
5765
5766- [`schema-forms.md`](/docs/schema-forms) — the field-level contract these
5767 renderers read.
5768- [`ui-decisions.md`](/docs/ui-decisions) — the living log of interaction
5769 decisions (detail-vs-edit, the row cap, board flex, filters, relation labels,
5770 capabilities) and the reasons behind them.
5771- [`design-system.md`](/docs/design-system) — semantic tokens, themes as data, and
5772 the stylesheet served as an object.
5773- [`capabilities.md`](/docs/capabilities) — the behavior layer mounted on detail.
5774"
5775design-system The Design System Sites, UI & Realtime 420 How DBBASIC's design system works as a semantic contract with a thin, themeable renderer, delivered as a live object rather than a static component library. "DBBASIC's design system is not a component library you depend on — it is
5776a **semantic contract with a thin, themeable renderer, delivered as an
5777object.** It has three layers, and only the top one is pixels.
5778
5779```mermaid
5780flowchart TD
5781 SEM[""Layer 1 — Semantics<br/>schema: types, enum, relation,<br/>list_mode, transitions, permissions""] --> REND
5782 TOK[""Layer 2 — Tokens<br/>semantic roles: surface, text,<br/>accent, positive/warning/danger""] --> REND
5783 REND[""Layer 3 — Renderers<br/>web pages · Scroll · shell · AI""]
5784 TOK -.theme = a set of role values.-> THEMES[""Themes as data:<br/>base · paper · terminal · yours""]
5785```
5786
5787## The governing idea: define once, project everywhere, own no copies
5788
5789Everything below is one principle seen from different angles. State the
5790design once — as tokens, as a shared stylesheet object, as a nav object,
5791as a schema — and let every surface *project* it. No page owns a copy of
5792the theme; it references `/style`. No page owns a copy of the nav; it
5793includes `/nav`. No app hardcodes a widget; it declares a field's
5794meaning. Because nothing downstream owns a copy, changing the source
5795changes the whole product at once, with nothing to chase.
5796
5797This is why rebranding the entire twelve-app suite and giving it a shared
5798navigation bar was **two objects edited live** — no deploy, no migration,
5799no per-page rework. If a future change to the look or the chrome ever
5800requires editing many pages, that is the signal that a copy leaked in and
5801should be pulled back into a shared object. Guard this property; it is the
5802whole value.
5803
5804## Layer 1 — Semantics (the source of truth)
5805
5806Design decisions live in the schema, not in markup. A field that declares
5807`enum` *means* ""one of these values""; each surface picks its own control
5808(dropdown on the web, segmented control in Scroll, a spoken list to the
5809AI). `views.list_mode` picks table / cards / feed. `transitions` says
5810which state moves are legal. Permissions decide which controls exist at
5811all. See [schema forms](/docs/schema-forms) and [permissions](/docs/permissions-model).
5812
5813**We deliberately do not use a widget-prescriptive `ui_schema`.** The
5814predecessor paired each schema with a React-JSON-Schema-Form
5815`ui_schema` that said things like `""ui:widget"": ""radio""`. That only ever
5816renders on one surface — a `radio` hint is meaningless to an AI, the
5817shell, a voice interface, or a native app. Semantics render everywhere;
5818widget instructions render once. This is the single most important choice
5819in the system, and the reason a design here can span surfaces that do not
5820exist yet.
5821
5822**Permissions are affordances.** A control exists because the caller can
5823perform the action, not because markup drew it and then hid it. A delete
5824button appears when the policy allows delete; a project filter appears
5825because there is a `project_id` relation; a column appears because
5826`list_fields` lists it. The design system renders *capability* — which is
5827why an AI acting for a user, or a shared component, can never show a
5828control the user could not actually use.
5829
5830## Layer 2 — Tokens (roles, not colors)
5831
5832The visual vocabulary is a small set of **semantic roles** — surface
5833(`bg`, `panel`, `line`), text (`text`, `muted`), `accent`, and status
5834(`positive`, `warning`, `danger`) — plus spacing, radii, shadow, and two
5835type families. Components are written against the roles, never against
5836raw colors, so a retheme changes values in one place and nothing in any
5837page moves.
5838
5839## Layer 3 — Renderers, and the design system *as an object*
5840
5841The stylesheet is itself a DBBASIC object: **`site_style`, served at
5842`/style`.** Every page links to it (`<link rel=""stylesheet"" href=""/style"">`)
5843instead of carrying its own CSS. Because it is an object, the whole visual
5844system is versioned, rollback-able, and live-editable like everything
5845else — retheming is one reversible object change, not a deploy.
5846
5847Other renderers consume the same two layers: Scroll's generated Flutter
5848forms and lists, the shell's terminal, and the AI (whose ""UI"" is the
5849schema's `label`/`help` text — good microcopy is design work that serves
5850the form, the accessibility label, and the AI tool description at once).
5851
5852## The app shell — chrome contributed, not copied
5853
5854Navigation is part of the design system, and it follows the same rule.
5855The **`site_nav` object, served at `/nav`,** injects one shared top bar
5856into every page that includes `<script src=""/nav""></script>`: brand, an
5857app switcher across installed apps, global search (`⌘K` / `Ctrl-K`) over
5858`/api/search`, an Ask-AI link to the shell, a notification bell reading
5859the `notifications` collection, and a user menu (appearance, sign out).
5860Its styling lives in `/style`, so it themes with everything else.
5861
5862The point is that a *package* (`app-theme`) contributes this bar to every
5863other app without those apps knowing — a thing a Django app could never do
5864to its siblings. Adding a nav item is one edit to one object; every app
5865gets it. If you find yourself pasting nav markup into a page, stop: add it
5866to `site_nav`.
5867
5868The bell is **live**: it subscribes to the `notifications` collection over
5869the `/ws` websocket and updates the instant something happens, with a 20s
5870poll as backup. Every app page is live the same way — each subscribes to
5871its collection and auto-refreshes (150ms debounced) when a record it can
5872see changes, over the one shared socket, via
5873`window.dbbasicSubscribe(collection, handler)`. Add a live list to a new
5874page in one line. Auto-update on events is the thing the old
5875dashboard/Channels stacks never did cleanly — see the
5876[realtime contract](/docs/http-api-contract#realtime-push-websocket).
5877
5878## Themes are data — and packages
5879
5880A **theme is just a set of values for the token roles.** `site_style`
5881ships three built in:
5882
5883- **base** — the DBBASIC identity: a warm dark (per the earth-theme rule
5884 ""warm, not cold blue-black"") with a terracotta/ember accent, carried
5885 forward from the palette an earlier project already established.
5886- **paper** — a warm light theme.
5887- **terminal** — high-contrast green-on-black.
5888
5889The active theme lives in the object's state. There is a visual chooser
5890at **`/appearance`** (the `site_appearance` object): it reads the
5891available themes and their preview swatches from `/style?info=true` and
5892lets an admin click one to reskin the whole instance; non-admins see the
5893active theme read-only. Or switch over HTTP:
5894
5895```http
5896POST /style {""theme"": ""terminal""} # admin session only
5897POST /style {""tokens"": {""accent"": ""#5aa7ff""}} # custom role overrides
5898GET /style?info=true # {active, available, previews, tokens}
5899```
5900
5901`site_style` self-gates writes to admin sessions (using the unspoofable
5902injected identity), so a public `execute` grant can serve the CSS to
5903everyone while only operators change the look.
5904
5905**A theme is a package.** Installing a package that ships its own
5906`site_style` (or that sets custom tokens) reskins the whole instance —
5907design distributed the same way apps are. A community can publish themes;
5908you install the one you like; you can fork it because it is one small,
5909readable object. Per-user theming (each account choosing a theme) is a
5910planned extension built on the same roles plus the `shell_preferences`
5911pattern.
5912
5913## Forms, tables, search, and filters
5914
5915The base stylesheet carries a genuinely complete component vocabulary so
5916generated UIs and hand-written pages share one look: form fields with
5917labels/help/required markers and validation states; tables with sortable
5918headers, hover, numeric alignment, and pagination; a toolbar with a search
5919input and filter chips; buttons as **intents** (primary / neutral /
5920danger) rather than colors; badges; and first-class empty / loading /
5921denied / error states.
5922
5923That is the visual layer. The **generative renderer** that reads a schema
5924and emits these — the successor to an earlier project's `django_tables2` + `django_filters`
5925(which worked because they were declarative from a single source) unified
5926across table, cards, and feed with search and filters wired to
5927`search.fields` — is the next build. The earlier project's honest lesson is that this
5928substrate must be *one* renderer, not the four disconnected
5929implementations it grew (django_tables2 for tables, two incompatible
5930form engines, hand-written cards and feeds). The semantics and the token
5931vocabulary are now in place for it.
5932
5933## Building a page against the design system
5934
5935```html
5936<link rel=""stylesheet"" href=""/style"">
5937...
5938<div class=""wrap"">
5939 <header class=""app""><h1>Notes</h1><div class=""who"">…</div></header>
5940 <div class=""toolbar"">
5941 <input class=""search grow"" placeholder=""Search…"">
5942 <div class=""filters""><button class=""chip"" aria-pressed=""true"">All</button></div>
5943 </div>
5944 <div class=""cards"">…</div>
5945</div>
5946```
5947
5948No inline CSS, no framework, no build step — just the shared classes. When
5949the instance's theme changes, this page changes with it. Page-unique
5950layout (a form's column grid, an edit-mode toggle) may stay in a small
5951`<style>` block, but it must use the token variables (`var(--panel)`,
5952`var(--line)`, `var(--accent)`) — never hardcoded colors — so it reskins
5953too.
5954
5955## Why this is a design system, not a style guide
5956
5957The test that separates the two: **change the source, and does the whole
5958product change with no copies to chase?** Here it does — edit `/style`,
5959every page reskins; edit `/nav`, every page's chrome updates; edit a
5960schema, every surface re-renders that field. A folder of CSS classes and a
5961component catalog is a style guide; you still hand-apply it and it drifts.
5962A design system propagates from one place. Protect that difference: the
5963day a change stops propagating is the day it quietly became a style guide.
5964
5965## Why not a dashboard template
5966
5967The web-template industry (Bootstrap admin themes, and the marketplaces
5968that sell them — an earlier project itself shipped on the ""Volt"" dashboard) assumed
5969**everything is a dashboard**: a fixed chrome of sidebar, topbar, cards,
5970and a data table, into which you pour your app. That is widgets-before-
5971meaning — the shape is the product, and the only app you can express is
5972the one the widgets already draw. It is the same mistake as a
5973widget-prescriptive `ui_schema`, at the scale of a whole product. It is
5974also why that earlier project accumulated 110 KB of override CSS *fighting* its template:
5975when the chrome is copied into every page, changing it means fighting it
5976everywhere.
5977
5978Reading modes (`table` / `cards` / `feed`) are the direct rejection of the
5979one-shape assumption: a note is read individually (cards), a task is
5980compared to others (table), a message is sequential (feed). The dashboard
5981world only had the table.
5982
5983The reason no one built it this way earlier is not taste, it is
5984arithmetic. Projecting one schema into a web form, a table, a Flutter
5985widget, an AI tool description, and an accessibility label meant
5986hand-writing five renderers per app — insane in 2015, so buying the frozen
5987template was rational. What changed is that the schema is now legible to a
5988model, a model can render a surface, and the runtime hot-loads it with no
5989deploy — so the marginal cost of a surface collapsed, and the correct
5990architecture (declare meaning once, project everywhere) finally pays. Build
5991for that, not for the dashboard era.
5992
5993## Current edges (honest)
5994
5995- **Theme-complete, component-incomplete.** The token/theme/app-shell
5996 layers are done and propagate. The component *vocabulary* exists in
5997 `/style`, but pages still assemble it by hand — the **generative
5998 renderer** (schema → dense list with row actions, filters, and relative
5999 timestamps) is not built yet. It is the next big design build, and it
6000 needs a `created_at` field added to schemas first (nothing captures
6001 creation time today, so there are no relative timestamps to show).
6002- **Web + tokens today.** Scroll shares the token *roles* but the web and
6003 Flutter renderers are not unified against one contract yet.
6004- **Instance-level theming.** Per-user theme choice is a planned extension
6005 on the same roles plus `shell_preferences`.
6006- **The shell page** (`/shell`) deliberately keeps its own terminal palette
6007 and does not link `/style` or `/nav` — a focused full-screen mode. The
6008 admin dashboard is not yet on the shared shell either.
6009
6010## Extending it correctly — rules for future builds
6011
6012When adding to the design system, keep the propagation property intact:
6013
60141. **Contribute, don't copy.** New chrome goes in a shared object
6015 (`site_style`, `site_nav`), never pasted into pages. If it must live in
6016 a page, it is page-unique and must use tokens.
60172. **Tokens are roles, never hex.** Add a role (e.g. `--info`) if you need
6018 a new meaning; never a raw color in a component or a page.
60193. **Semantics, not widgets.** Express new capability as schema meaning
6020 (a new field key, a new `views` mode) that every surface can interpret
6021 — resist any per-surface ""render as X"" instruction; that is `ui_schema`
6022 returning, and it collapses you back to one surface.
60234. **Let permissions draw the controls.** Show an action because the
6024 policy allows it, not because you wrote the button.
60255. **One renderer per concern.** When the generative renderer lands, route
6026 all lists/forms through it — do not grow a second form engine. The earlier project grew
6027 four; that fragmentation is the failure mode to avoid.
60286. **No framework to fight.** Do not adopt a CSS framework you will then
6029 override. The system is small and authoritative on purpose.
60307. **If a change stops propagating, fix the leak** — pull the copy back
6031 into the shared object — rather than editing many pages.
6032
6033Follow these and the next person (or the next model, or a stranger who
6034forks this) can retheme, re-chrome, or extend the whole product from a
6035handful of objects — which is the point.
6036"
6037rest-and-object-messages REST and Object Messages Sites, UI & Realtime 430 How the DBBASIC Object Server splits its HTTP API into RESTful resources, object messages, and realtime streams — and why that split matters. "DBBASIC should be RESTful where it exposes resources and direct where it
6038executes behavior.
6039
6040The goal is not to pretend every operation is pure REST. The goal is to keep a
6041clean split:
6042
6043```mermaid
6044flowchart LR
6045 A[""HTTP API""] --> B[""Resources""]
6046 A --> C[""Object messages""]
6047 A --> D[""Streams""]
6048
6049 B --> B1[""source""]
6050 B --> B2[""state""]
6051 B --> B3[""logs""]
6052 B --> B4[""files""]
6053 B --> B5[""versions""]
6054 B --> B6[""metadata""]
6055
6056 C --> C1[""execute method""]
6057 C --> C2[""run job""]
6058 C --> C3[""handle webhook""]
6059 C --> C4[""perform admin action""]
6060
6061 D --> D1[""WebSocket events""]
6062 D --> D2[""Server-Sent Events""]
6063```
6064
6065## Why This Matters
6066
6067Many APIs called REST are really RPC over HTTP:
6068
6069```text
6070POST /doThing
6071POST /executeAction
6072POST /api/run
6073```
6074
6075That shape is easy to add, but it hides what the system actually owns. DBBASIC
6076objects own real resources: source, state, logs, files, versions, and metadata.
6077Those should be exposed as resources with stable paths, predictable HTTP
6078methods, status codes, and JSON representations.
6079
6080Object behavior is different. Executing an object is message passing. Jobs,
6081events, webhooks, and realtime commands are also messages. They should be
6082documented as messages instead of disguised as fake CRUD resources.
6083
6084## RESTful Resource Surface
6085
6086DBBASIC should keep these resource-style endpoints boring and predictable:
6087
6088```text
6089GET /objects
6090POST /objects
6091GET /objects/{object_id}?source=true
6092PUT /objects/{object_id}?source=true
6093GET /objects/{object_id}?state=true
6094GET /objects/{object_id}?logs=true
6095GET /objects/{object_id}?versions=true
6096GET /objects/{object_id}?version=N
6097DELETE /objects/{object_id}?destroy=true
6098```
6099
6100These endpoints expose things the object server owns.
6101
6102They should preserve:
6103
6104- stable object identity
6105- standard HTTP status codes
6106- JSON response shapes existing clients can keep using
6107- explicit authorization checks
6108- useful cache behavior where safe
6109- compatibility with `docs/http-api-contract.md`
6110
6111## Object Message Surface
6112
6113Object execution is not only CRUD. It is behavior:
6114
6115```text
6116GET /objects/{object_id}
6117POST /objects/{object_id}
6118PUT /objects/{object_id}
6119DELETE /objects/{object_id}
6120```
6121
6122Those calls deliver a method and payload to the object.
6123
6124That model is closer to:
6125
6126```text
6127object_id + method + payload -> result
6128```
6129
6130than:
6131
6132```text
6133table + row + CRUD operation
6134```
6135
6136This is intentional. A DBBASIC object can represent a report, worker, webhook,
6137view, business process, queue handler, generated UI, or admin tool.
6138
6139## Rollback
6140
6141Rollback is the awkward case:
6142
6143```text
6144POST /objects/{object_id}
6145{""action"": ""rollback"", ""version_id"": 1}
6146```
6147
6148That is a message, not a pure REST resource update. It is kept for compatibility
6149with existing clients.
6150
6151Future server code may add a cleaner resource-style alias, but it should not
6152break the existing message shape without a migration:
6153
6154```text
6155POST /objects/{object_id}/versions/{version_id}/rollback
6156```
6157
6158## Design Rule
6159
6160Do not turn every operation into `/api/doThing`.
6161
6162Use resources for object-owned data:
6163
6164```text
6165source, state, logs, files, versions, metadata
6166```
6167
6168Use messages for object-owned behavior:
6169
6170```text
6171execute, run, handle, repair, migrate, broadcast
6172```
6173
6174Use streams for object-owned realtime feedback:
6175
6176```text
6177source changed, state changed, log appended, version saved, execution failed
6178```
6179
6180That is the honest shape of DBBASIC: REST where resources are real, object
6181messages where behavior is real, and streams where live feedback is real.
6182"
6183realtime Realtime: The Change Log and Live Surfaces Sites, UI & Realtime 440 How DBBASIC Object Server pushes change notifications over a websocket without ever putting record data on the wire, and why that design choice matters. "Every generative surface — every list, table, board, detail page, comment
6184thread, and attachment list — subscribes to the change log and re-renders when a
6185record it can see changes, from any tab, user, or agent. This falls out of one
6186small websocket contract with a deliberate rule: **the wire carries a signal,
6187never the record body.**
6188
6189```mermaid
6190sequenceDiagram
6191 participant Writer as any write (web/API/agent)
6192 participant Server
6193 participant Hub as realtime hub
6194 participant Client as a live surface
6195
6196 Client->>Server: connect /ws (session), subscribe [collections]
6197 Server->>Server: may this subject READ each collection?
6198 Server-->>Client: {type: subscribed, collections}
6199 Writer->>Server: create/update/delete a record
6200 Server->>Hub: publish {collection, record_id, action}
6201 Hub->>Hub: per subscriber, re-run the READ decision
6202 Hub-->>Client: {type: record, collection, record_id, action}
6203 Client->>Server: refetch through the normal permission-enforced API
6204 Client->>Client: re-render
6205```
6206
6207## Transport
6208
6209`GET /ws` (upgraded to a websocket). The connection is **authenticated** — a
6210session cookie or bearer token — and anonymous connections are refused (`1008`).
6211Realtime is behind a flag; when off, surfaces fall back to polling.
6212
6213## Client protocol
6214
6215Messages are JSON. On accept, the server sends `{""type"": ""welcome"", ""user"": ...}`.
6216Then:
6217
6218| Client sends | Server replies |
6219|--------------|----------------|
6220| `{""action"": ""subscribe"", ""collections"": [""tasks"", ""notes""]}` | `{""type"": ""subscribed"", ""collections"": [...]}` — only the collections the subject may read are kept |
6221| `{""action"": ""unsubscribe"", ""collections"": [...]}` | `{""type"": ""subscribed"", ""collections"": [...]}` |
6222| `{""action"": ""ping""}` | `{""type"": ""pong""}` |
6223
6224Subscriptions are capped per connection, and each collection name is validated.
6225
6226In the browser this is wrapped as one helper, `window.dbbasicSubscribe(collection,
6227handler)` (served by the `nav` object): it opens the socket once, subscribes on
6228demand, reconnects with backoff, and runs a ~20-second poll as a fallback for
6229missed events and multi-worker deployments. A page never talks to `/ws`
6230directly — it calls `dbbasicSubscribe` and re-renders in the handler.
6231
6232## The event
6233
6234A change pushes exactly:
6235
6236```json
6237{ ""type"": ""record"", ""collection"": ""tasks"", ""record_id"": ""…"", ""action"": ""update"" }
6238```
6239
6240`action` is `create` / `update` / `delete`. **No field values travel** — only
6241which record changed. The client reacts by *refetching* through the ordinary
6242API, which re-applies the full permission policy and field redaction. So a live
6243surface can never show a field the API wouldn't have served.
6244
6245## Permission filtering — twice
6246
6247Realtime is inside the permission engine, not beside it:
6248
62491. **On subscribe** — a subject may follow a collection only if it may `READ`
6250 it (`_ws_can_subscribe` runs the same check a `GET` would).
62512. **On publish** — for each subscriber, the server re-runs the READ decision
6252 *against the changed record*, so a row-filtered subscriber only hears about
6253 rows its filter would let it see. If the policy can't be loaded to filter
6254 safely, nothing is pushed.
6255
6256Combined with the signal-only payload, this means the change log leaks neither
6257the existence of records you can't see (filtered per-subscriber) nor their
6258contents (never sent).
6259
6260## Why signal, not body
6261
6262- **Security** — the wire can't leak a field, because it carries none. All
6263 reads go back through the one enforced path.
6264- **Simplicity** — there is no second serialization/redaction path to keep in
6265 sync with the API; the client just refetches.
6266- **Correctness under races** — the refetch always returns the current row, so a
6267 burst of edits collapses to one correct re-render rather than replaying stale
6268 bodies.
6269
6270The durable, poll-based event log remains the fallback for missed pushes and
6271for deployments with more than one worker process.
6272
6273## Related
6274
6275- [`asgi-realtime-direction.md`](/docs/asgi-realtime-direction) — why the server
6276 uses plain ASGI and how websocket/SSE object events fit the direction.
6277- [`generative-ui.md`](/docs/generative-ui) — the surfaces that subscribe.
6278- [`permissions-model.md`](/docs/permissions-model) — the READ decision reused on
6279 subscribe and on every push.
6280- `runtime-contract.md` — the daemon and event contracts
6281 behind the durable log.
6282"
6283asgi-realtime-direction ASGI and Realtime Direction Sites, UI & Realtime 450 Why DBBASIC's ASGI layer stays close to persistent CGI, what it borrows from Phoenix/Erlang, and how the websocket realtime overlay sits on top of the durable event log. "The working prototype used plain ASGI with Uvicorn, not Django ASGI, Channels,
6284FastAPI, or Starlette.
6285
6286The shape was simple:
6287
6288```mermaid
6289flowchart LR
6290 A[""Uvicorn""] --> B[""ASGI app""]
6291 B --> C[""Filesystem router""]
6292 C --> D[""api/*.py handlers""]
6293```
6294
6295That kept the useful part of classic CGI:
6296
6297```mermaid
6298flowchart LR
6299 A[""URL""] --> B[""File""]
6300 B --> C[""Function""]
6301```
6302
6303but without classic CGI's process-per-request cost.
6304
6305That is a better comparison than saying DBBASIC is a Rails-like app structure.
6306The goal is closer to persistent CGI with a reusable object runtime:
6307
6308- filesystem paths can map to runnable code
6309- the server stays warm between requests
6310- routing is derived from object source placement
6311- common helpers provide state, logs, files, versions, and scheduling
6312- object boundaries stay small enough for humans and AI tools to inspect
6313
6314Classic CGI made deployment easy but left too much work to each script. DBBASIC
6315keeps the direct path-to-code idea and adds the shared runtime pieces that make
6316objects reusable as application building blocks.
6317
6318## Why ASGI Matters
6319
6320ASGI gives DBBASIC one server surface for:
6321
6322- normal HTTP requests
6323- long-lived WebSocket connections
6324- Server-Sent Events
6325- startup and shutdown lifecycle hooks
6326
6327That matters because DBBASIC objects are not only pages or REST handlers. They
6328can also be jobs, event handlers, admin actions, realtime screens, data feeds,
6329and AI-edited live application pieces.
6330
6331The important loop is:
6332
6333```mermaid
6334flowchart LR
6335 A[""Object changes""] --> B[""Version saved""]
6336 B --> C[""Object event""]
6337 C --> D[""UI/client updates""]
6338```
6339
6340HTTP can handle the command. WebSockets or SSE can carry the feedback.
6341
6342## Phoenix And Erlang
6343
6344Phoenix and Erlang/BEAM show why realtime application systems can feel so much
6345better than request/response-only web frameworks:
6346
6347- long-lived connections are normal
6348- PubSub is a core idea
6349- server-side events can update clients quickly
6350- stateful processes can model active parts of the application
6351- failures are isolated and supervised
6352
6353DBBASIC should learn from that direction.
6354
6355The DBBASIC version is not Erlang and does not get BEAM supervision for free.
6356Python ASGI does not automatically give per-object process isolation, hot code
6357replacement, distributed process registries, or Phoenix PubSub semantics.
6358
6359What DBBASIC can still use well is the product shape:
6360
6361```mermaid
6362flowchart TD
6363 A[""Object source""]
6364 B[""Object state""]
6365 C[""Object logs""]
6366 D[""Object versions""]
6367 E[""Realtime object events""]
6368 A --> E
6369 B --> E
6370 C --> E
6371 D --> E
6372```
6373
6374That can support live admin screens, Scroll object inspectors, AI repair loops,
6375dashboards, collaborative editing, queues, and business app interfaces without
6376forcing everything through a Rails/Django-style request/deploy cycle.
6377
6378## Public V1 Direction
6379
6380The public v1 server should stay single-node first and keep clustering separate
6381until replication and conflict behavior are proven.
6382
6383The first public ASGI layer is now small and runnable. It includes:
6384
6385- `GET /health`
6386- `GET /objects?format=json`
6387- `GET /objects/{object_id}?source=true&format=json`
6388- object execution
6389- source update and rollback
6390- state/log/version endpoints
6391- metadata endpoints
6392- temporary admin-token gate for object listing and introspection reads
6393
6394Role, object, and row-level permissions, resource limits, and
6395backup/restore checks all shipped. The websocket event stream is now
6396implemented too (see below).
6397
6398## Realtime: implemented
6399
6400Realtime arrived as an event system, not a decorative feature, and it
6401reuses the durable event log rather than inventing a parallel path:
6402
6403- **Durable log (source of truth).** Every record write already publishes
6404 `collection.record.created/updated/deleted` to `object_events`, which is
6405 persisted, capped, and pollable with a cursor. This is the reliable,
6406 cross-restart, cross-worker path.
6407- **Live overlay (`/ws`).** An in-process pub/sub hub (`object_realtime`)
6408 pushes those same events to connected websockets the instant they
6409 happen. See the [HTTP API contract](/docs/http-api-contract#realtime-push-websocket)
6410 for the connect + subscribe protocol.
6411
6412Events are boring JSON signals — collection, record id, action — never the
6413record body, so a push can never leak a field. Delivery obeys the
6414permission engine: you can only subscribe to a collection you may read, and
6415with enforcement on you only receive events for records your row filters
6416would show you. The client refetches through the normal enforced API.
6417
6418**Single-process assumption.** The live hub lives in one process; with one
6419uvicorn worker every write and every socket share the event loop, so
6420push is immediate and consistent. Across multiple workers each has its own
6421hub, and clients fall back to polling the durable log — which is why the
6422durable log, not the socket, is the source of truth. Keep the public v1
6423single-worker (or add a shared broker before scaling workers) so live push
6424stays whole; either way correctness never depends on the socket.
6425
6426An object-scoped room model (`/ws/objects/{object_id}` for source/state/log
6427changes) is a natural next addition on the same hub, using the existing
6428source/state/version change events.
6429
6430## Design Rule
6431
6432Keep the ASGI layer thin.
6433
6434The server should route requests and streams to object operations. It should not
6435become a second framework with its own competing object model.
6436"
6437shell-and-ai The Shell and AI — Talk to the Whole System AI 500 How the DBBASIC shell routes instant record commands, search, and AI chat through the same MCP tools and permission engine, plus voice and web-reading features. "The shell (`/shell`) is one input that reaches everything: instant
6438record commands, global search, and an AI that operates the server
6439through the same MCP tools any agent uses — with **your key, your
6440model choice, and your permissions**.
6441
6442```mermaid
6443flowchart TD
6444 U[""You type""] --> D{""prefix?""}
6445 D -->|""$ . ^""| REC[""Create note / task / link<br/>(records API, your session)""]
6446 D -->|""~""| SRCH[""GET /api/search""]
6447 D -->|""/""| CMD[""Built-ins: /help /key /model /tools /voice""]
6448 D -->|""anything else""| CHAT[""POST /api/ai/chat""]
6449 CHAT --> PROV[""AI provider<br/>(your stored key)""]
6450 PROV -->|""tool calls""| MCP[""MCP tool subset<br/>dispatched with YOUR credentials""]
6451 MCP --> PERM[""Permission engine + audit""]
6452 PERM --> PROV
6453 PROV --> REPLY[""Reply + tool log + token usage + cost""]
6454```
6455
6456## Setup: Your Key, Your Model
6457
6458AI features use each user's own provider key — the server stores it
6459write-only and calls providers on your behalf. Key material never
6460appears in any response, record, or backup. Two providers are supported
6461today (`object_ai.SUPPORTED_SERVICES`): `anthropic` and `openai` — no
6462Gemini, no local/on-device inference. An `openai` key, once stored, also
6463covers the cloud voice paths below (`POST /api/tts` with `engine: ""openai""`,
6464`POST /api/stt`) — one key, no separate signup for voice.
6465
6466In the shell:
6467
6468```
6469/key anthropic sk-ant-... store a key (masked, never logged)
6470/keys which services have keys
6471/model anthropic:claude-haiku-5-5 pick a model (service:model)
6472/model openai:gpt-5-mini or the other provider
6473```
6474
6475Or over HTTP: `PUT /identity/users/{you}/service-keys` with your
6476session (see the [HTTP API contract](/docs/http-api-contract)).
6477
6478## Tool Subsets: Small Context, Configurable Power
6479
6480The AI is offered a **named subset** of the MCP tool catalog, not the
6481whole thing. Small subsets keep the context small enough for fast,
6482inexpensive models — and the subset is your safety dial:
6483
6484```
6485/tools global_search,list_records,get_record,create_record conversation mode
6486/tools global_search,list_objects,get_object_source,create_object,update_object_source,execute_object builder mode
6487```
6488
6489Every tool call the model makes is dispatched through the server's own
6490routing **with your credentials**: the AI can do exactly what you could
6491do yourself — row filters, field redaction, and the audit trail apply.
6492An AI acting for a user is never more powerful than the user.
6493
6494### Output Budget and Effort Per Mode
6495
6496A subset that includes `create_object` or `update_object_source` is
6497**builder mode**; anything else is **conversation mode**. The mode picks
6498two defaults:
6499
6500| | Conversation | Builder |
6501|---|---|---|
6502| `max_tokens` | 4096 | 8192 (16384 when streaming) |
6503| effort | `low` (`DBBASIC_AI_EFFORT`) | `high` (`DBBASIC_AI_BUILDER_EFFORT`) |
6504
6505A request may ask for its own `max_tokens` (capped at 8192, or 16384 when
6506streaming, since a streamed answer starts arriving at once instead of
6507holding one response open) and its own `effort` (`low`, `medium`, `high`,
6508`xhigh`, `max`). `DBBASIC_AI_MAX_TOKENS_CAP` sets an operator cap that
6509bounds both paths. Output tokens include the model's thinking, so the old
6510default of 1024 left little room for an answer, and none for a builder
6511answer that writes a whole object.
6512
6513Effort is sent as `output_config: {""effort"": ...}` only to models that
6514accept it: current Claude ids from 4.6 on (`claude-haiku-5-5`,
6515`claude-sonnet-5`, `claude-opus-4-8`, ...). `claude-haiku-4-5`, any id the
6516server cannot read as a current Claude id (including dated snapshot ids),
6517and OpenAI models get no effort field; they use their own default. The
6518server never sends `temperature`, `top_p`, `top_k` or a thinking budget:
6519Claude Haiku 5.5 thinks adaptively by default and refuses those.
6520
6521### Strict Tool Schemas
6522
6523On the same models (Claude 4.6+), every offered tool whose input schema
6524can be *closed* is sent with `""strict"": true`, so the provider guarantees
6525the call's input matches the schema. Closing means every object lists its
6526properties, sets `additionalProperties: false` and has a `required` list;
6527the server makes that copy (the MCP catalog is not changed), moving any
6528`default` into the description because the server's tool routing applies
6529defaults itself.
6530
6531Five tools take a free-form object and so stay non-strict: `create_record`
6532(`record`), `update_record` (`changes`), `list_records` (`where`),
6533`execute_object` (`payload`) and `update_schema` (`schema`). Closing those
6534would refuse the very fields the tools exist to carry. Every other tool in
6535the catalog -- including `create_object`, `update_object_source`,
6536`global_search`, `get_record` and `read_page` -- can be strict. OpenAI tool
6537definitions are unchanged.
6538
6539The provider accepts at most 20 strict tools in one request (a live call
6540with 25 was refused with HTTP 400). A tool subset with more closable tools
6541than that keeps `strict` on the ones that change something (`create_*`,
6542`update_*`, `delete_*`, `rollback_*`, `setup_*`, `start_*`, `stop_*`) first,
6543then the others in the order offered; the rest are sent unmarked. The
6544shell's usual subsets are far below the limit.
6545
6546## Conversation Memory
6547
6548The shell logs every exchange to the `shell_commands` collection (your
6549history is just records — searchable and owner-scoped). A new browser
6550session replays recent history and sends prior AI turns back with each
6551message, so conversations resume. The server stays stateless about
6552chats: `POST /api/ai/chat` accepts a `history` list, and what to
6553remember is the client's choice.
6554
6555## Streaming
6556
6557`POST /api/ai/chat` with `""stream"": true` answers in server-sent events,
6558so the shell and Talk show the reply as it is written instead of after
6559the whole turn. It is the same turn, not a second implementation:
6560
65611. Every refusal that can happen before the provider is called (flag,
6562 session, origin, body, model, tool names, attachments, missing key)
6563 runs first and stays a plain JSON error with its real status.
65642. The turn runs in a worker thread through the same `object_ai.run_chat`
6565 loop. Anthropic is asked for `stream: true`; its events are parsed as
6566 they arrive and each text delta is forwarded to the browser as a
6567 `text` event.
65683. When a round asks for tools, each tool's input is assembled from its
6569 streamed fragments and parsed only once its block has stopped. Input
6570 that does not parse into a JSON object is never dispatched: the model
6571 gets an error result (`is_error`) and may retry. Valid calls dispatch
6572 through the server's own routing with the caller's credentials, exactly
6573 as on the JSON path, and each is reported as a `tool_call` event. Then
6574 the next round streams.
65754. When the turn ends, it is priced and recorded by the same code as a JSON
6576 turn, and the final `done` event carries the same object the JSON
6577 endpoint returns. A failure mid-turn ends with an `error` event instead
6578 (and, as on the JSON path, records nothing).
6579
6580Text events are a preview; `done.reply` is the answer (a refusal can
6581arrive after some words streamed). A browser that disconnects mid-turn
6582does not stop the turn: the provider is being paid either way, so it
6583finishes, runs its tools and is recorded; only the writes to the closed
6584connection are dropped. OpenAI turns are not streamed from OpenAI: each
6585round's text arrives as one `text` event when the round finishes.
6586
6587The shell and Talk pages ask for a stream: the shell fills the pending
6588line and Talk fills the caption as the words arrive, then both render the
6589final `done` reply exactly as before (Talk speaks only that final reply,
6590never a partial one). A response that is not `text/event-stream` -- a
6591refusal made before the provider call, or a proxy that answers JSON -- is
6592read as the JSON reply it always was.
6593
6594## When a Turn Stops Early
6595
6596The server reads each response's `stop_reason` before its content, and
6597the chat response carries it (`stop_reason`) so a surface can tell the
6598cases apart:
6599
6600- **`refusal`**: the model declined. Whatever content came with it is
6601 not an answer and is not shown; `reply` says the model declined and
6602 names the provider's category and explanation, which also come back as
6603 `refusal: {category, explanation}`. No tool from that response runs.
6604- **`max_tokens`**: the answer hit the output limit. `reply` is the
6605 partial text followed by a note that it was cut off, and `cut_off` is
6606 `true`. A tool call in the same response is **not** run: its input may
6607 stop mid-argument. (OpenAI's `length` is treated the same way.)
6608- **`pause_turn`**: the provider paused a long turn. The paused content
6609 is sent back unchanged and the turn resumes, counting as a round. If
6610 the round limit comes first, `reply` says so and `truncated` is `true`.
6611
6612A refused or cut-off turn still spent tokens, so its usage and cost are
6613recorded like any other.
6614
6615## Prompt Caching
6616
6617Anthropic requests mark their stable prefix for prompt caching. A request
6618renders as tools, then system, then messages, and a cached entry is a
6619prefix of that, so the breakpoints (`cache_control: {""type"":
6620""ephemeral""}`) go on the parts that are identical turn after turn: the
6621last tool definition and the `system` text. Text that changes every turn
6622-- the local time, the last web page read -- goes in the request's
6623`context` field instead, which is sent as a second system block *after*
6624the cached one. A timestamp inside `system` would make every request's
6625prefix unique: each turn would pay to write a cache entry nobody reads.
6626
6627The simpler top-level `cache_control` (cache up to the last block) is not
6628used on purpose: a turn's last block is the new user message, and the next
6629turn's history carries that message without its context, so what one turn
6630wrote is not what the next turn sends.
6631
6632A prefix shorter than the model's minimum cacheable length is not cached
6633(no error; the cache token counts are 0). OpenAI requests are unchanged:
6634`system` and `context` are joined into its one system message, and OpenAI
6635caches on its own.
6636
6637## Cost Recording
6638
6639Every chat turn is priced server-side, not by the caller. `POST
6640/api/ai/chat` reads token counts straight from the provider's own response,
6641looks up the model's price in the `ai_prices` collection (editable records,
6642never a hardcoded table -- so a price change is a data edit, not a
6643deploy), and computes the cost in integer cents: `tokens *
6644per_million_cents // 1_000_000`, input and output added separately, no
6645float division on money. The result -- `tokens_in`, `tokens_out`,
6646`tokens_cache_read`, `tokens_cache_write`, `cost_cents`, `model`,
6647`provider` -- lands in the `ai_usage` collection, written by the chat
6648handler itself with the caller's user id as actor, so the record can't be
6649skipped or forged the way a client-written log could be. The same numbers
6650come back in the chat response's `usage` object (`input_tokens`,
6651`output_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens`,
6652`largest_prompt_tokens`, `cost_cents`) so a surface can show them
6653immediately.
6654
6655Cached prompt tokens (see Prompt Caching above) are reported by Anthropic
6656*beside* `input_tokens`, not inside it, and are billed at their own rates:
6657`ai_prices` has `cache_read_per_million_cents` and
6658`cache_write_per_million_cents` for them. A blank cache rate means
6659*unknown*, not free.
6660
6661The cost is null -- tokens still recorded -- when the turn cannot be priced
6662honestly:
6663
6664- no `ai_prices` row matches the model;
6665- the turn read or wrote prompt cache and the matching cache rate is blank;
6666- the row sets `price_max_prompt_tokens` and one request's whole prompt
6667 (uncached + cache read + cache write) went over it.
6668
6669The last rule exists for models whose rate rises above a prompt size.
6670Claude Haiku 5.5 costs $0.10 in / $0.50 out per million tokens for
6671prompts up to 100K tokens and $0.50 / $2.50 beyond. A price row holds one
6672rate, so the seeded Haiku 5.5 row covers prompts up to 100,000 tokens and a
6673turn with a bigger request is left unpriced rather than recorded at a fifth
6674of its real cost. Pricing the higher tier would need a second rate on the
6675row and per-request (not per-turn) cost math; it is not implemented.
6676
6677Seeded rates (cents per million tokens):
6678
6679| Model | In | Out | Cache read | Cache write | Priced up to |
6680|---|---|---|---|---|---|
6681| `claude-haiku-5-5` | 10 | 50 | 1* | 13* | 100,000 |
6682| `claude-sonnet-5-5` | 200 | 1000 | 10 | 250* | |
6683| `claude-opus-5-5` | 400 | 2000 | 20 | 500* | |
6684
6685The cache-read rates for Sonnet 5.5 and Opus 5.5 are published prices.
6686The starred rates are derived, not published: Anthropic prices cache
6687reads at 0.05x the input rate and 5-minute cache writes at 1.25x, so
6688Haiku 5.5 reads come to 0.5 cents per million and writes to 12.5, and the
6689seed rounds every derived rate UP to a whole cent (1 and 13). The recorded
6690cost is informational -- these turns run on the user's own key -- and must
6691never under-report, so a slightly high number beats a missing one. An
6692operator who has the exact published rate edits the row; the most recent
6693`effective_date` wins.
6694
6695The older rows (`claude-haiku-4-5`, `claude-sonnet-5`, `claude-opus-4-8`,
6696`gpt-5-mini`, `gpt-5`) stay, with blank cache rates: for them a turn that
6697touches the cache is recorded with a null cost. Upgrading
6698`app-settings` on an existing server merges the new rows by id and leaves
6699rows already there untouched.
6700
6701## Coding Without Coding
6702
6703With builder-mode tools, the AI can create and edit live objects:
6704
6705> make an object called site_dice that renders a page rolling two dice
6706
6707The model writes the source, calls `create_object`, and the page is
6708live at `/dice` immediately — objects load per execution, so there is
6709no deploy step between the AI writing code and the code serving
6710traffic. Edits use `update_object_source`; every version lands in
6711source history with rollback; and create/update responses report the
6712methods the code actually exposes, so the model can self-correct.
6713
6714Object writes ride the admin gate (an admin-role session today), and
6715source writes require `DBBASIC_ENABLE_SOURCE_WRITES=true` — the same
6716boundaries that govern humans.
6717
6718## Voice
6719
6720The shell doubles as a push-to-talk terminal. Speech in and speech out each
6721have two paths: browser-native (free, on-device, always available if the
6722browser supports it) and cloud (a real per-user OpenAI key, real cost, but
6723""not on device"" — works on browsers/hardware the native APIs don't cover,
6724and sounds noticeably better than the local synthesis engines).
6725
6726- **Speech in, browser path**: the mic button uses `window.SpeechRecognition`
6727 (or the `webkit` prefix); interim words show live in the input, and the
6728 final transcript submits through the same form-submit path a typed line
6729 does — no separate send code. Neither Chrome nor Safari expose the API
6730 outside a secure context (`https://` or `localhost`), and without it the
6731 button simply stays hidden. This is the default (`talk_stt_engine: ""browser""`).
6732- **Speech in, cloud path**: when `talk_stt_engine` is `""openai""`, the mic
6733 becomes push-to-talk instead of continuous listening — tap to start a
6734 real `MediaRecorder` capture, tap again to stop and upload the clip to
6735 `POST /api/stt`, which transcribes it via the caller's own stored OpenAI
6736 key and returns text. No wake word, no VAD silence endpoint: raw audio has
6737 no equivalent to `SpeechRecognition`'s live partial-result signal, so
6738 there is no live signal to drive one. See `POST /api/stt` below.
6739- **Speech out, browser path**: `speechSynthesis.speak` — free, on-device,
6740 no server round-trip.
6741- **Speech out, cloud path**: when `talk_tts_engine` is `""openai""`, assistant
6742 replies (markdown and code fences stripped first — only prose is spoken,
6743 never tool-call noise) POST to `POST /api/tts` with `""engine"": ""openai""`
6744 and play the returned `audio/mpeg`, via the caller's own stored OpenAI key.
6745 If the request fails for any reason, the browser's own `speechSynthesis`
6746 says the line instead, so voice mode never goes silent because of a
6747 server-side gap.
6748
6749`/voice`, `/voice on`, `/voice off` toggle voice mode inline (mirrors
6750`/model`); the setting persists on `shell_preferences.voice_enabled` and is
6751honored on page load like `ai_model` and `tools`. `talk_tts_engine` and
6752`talk_stt_engine` (both default to the free/local path) live on the same
6753`shell_preferences` record — the Talk page (`/talk`) additionally has a
6754single in-page toggle that flips both together, since ""cloud voice"" is one
6755combined mode to remember, not two settings.
6756
6757### `POST /api/tts`
6758
6759```http
6760POST /api/tts
6761Authorization: Bearer <session-token> (or the session cookie)
6762
6763{""text"": ""one note matches"", ""voice"": ""en-us"", ""engine"": ""local""}
6764```
6765
6766Response: audio bytes (`audio/wav` for `engine: ""local""`, `audio/mpeg` for
6767`engine: ""openai""`), or the usual `{""status"": ""error"", ""error""}` JSON shape
6768on failure. Requires `DBBASIC_ENABLE_TTS=true` (off by default) and a
6769signed-in session — same posture as `/api/ai/chat`. `text` is capped at 800
6770characters (413 beyond that). `engine` is optional, `""local""` or `""openai""`,
6771defaulting to `""local""` — the two paths never silently fall back to each
6772other; a caller who asked for cloud quality and hits a provider error sees
6773that error.
6774
6775**`engine: ""local""`** (default): discovered at call time, first match wins:
6776`espeak-ng`, `espeak`, then macOS `say` (development convenience — `say`
6777writes AIFF and the also-stock `afconvert` turns it into WAV; if `afconvert`
6778isn't present the endpoint returns 501 rather than growing a bespoke audio
6779pipeline). No engine on `PATH` at all is a 503 with a clear message.
6780
6781**`engine: ""openai""`**: calls OpenAI's TTS API (`gpt-4o-mini-tts` by
6782default) using the caller's own key, stored via `PUT
6783/identity/users/{user_id}/service-keys` (`service: ""openai""`) — no key
6784stored is a 400 with the exact PUT to fix it. A provider-side failure (bad
6785key, rate limit) is a 502. `DBBASIC_TTS_CLOUD_TIMEOUT_SECONDS` bounds the
6786outbound call (default 30s).
6787
6788Successful audio is cached at
6789`data/tts-cache/{sha256(engine|voice|text[|model])}.wav` regardless of
6790engine — a repeat of the same line is a cache read, not a re-synthesis.
6791There's no eviction in v1; operators who want a bound should prune that
6792directory on their own schedule.
6793
6794### `POST /api/stt`
6795
6796```http
6797POST /api/stt
6798Authorization: Bearer <session-token> (or the session cookie)
6799Content-Type: audio/webm
6800
6801<raw audio bytes>
6802```
6803
6804Response: `{""status"": ""ok"", ""text"": ""...""}`, or the usual
6805`{""status"": ""error"", ""error""}` shape. The request body is the raw audio
6806bytes themselves (whatever `MediaRecorder` produced client-side — typically
6807`audio/webm` on Chrome/Firefox, `audio/mp4`-ish on Safari), not JSON; the
6808`Content-Type` header says what format it is. Requires
6809`DBBASIC_ENABLE_STT=true` (off by default, unlike TTS which many operators
6810turn on immediately — STT costs money on every utterance, not just the
6811occasional reply) and a signed-in session. Capped at 10MB per clip (413
6812beyond that).
6813
6814Unlike TTS, there is **no local-engine path here at all** — every call goes
6815to OpenAI's transcription API (`gpt-4o-mini-transcribe` by default), using
6816the caller's own stored key exactly like the TTS cloud path. No key stored
6817is a 400; a provider-side failure is a 502.
6818`DBBASIC_STT_TIMEOUT_SECONDS` bounds the outbound call (default 30s).
6819Nothing is persisted server-side beyond the ordinary `ai_usage`/cost
6820accounting every provider call gets — the audio itself is uploaded,
6821transcribed, and discarded within the request.
6822
6823## Reading the Web
6824
6825The AI can fetch and read a real web page — the lynx/w3m move for an AI +
6826voice consumer: strip a URL down to `{title, text, links}`, links numbered
6827in document order so they double as speakable navigation targets (""open
6828link three""). It is a real, tested loop: read a page, get a short spoken
6829summary with numbered links, say ""open link one,"" and it resolves against
6830the previous turn's link list, fetches that page, and summarizes it too —
6831follow a chain of pages by voice alone.
6832
6833The `read_page` tool is offered like any other MCP tool (add it to a
6834`/tools` subset to use it) and calls `object_reader.py` server-side, gated
6835behind `DBBASIC_ENABLE_READER` (off by default). Fetching is SSRF-hardened:
6836every hostname — the original and every redirect hop — is resolved and
6837checked before the socket opens, refusing loopback/link-local/private
6838ranges and failing closed on any resolution ambiguity; `http`/`https` only,
6839a small redirect cap, and hard timeout/size limits. HTML is stripped with
6840`html.parser` (no regex scraping), never a headless browser — JS-rendered
6841pages, images, and login-walled pages are out of scope by design.
6842
6843A fetched page can also be shown on screen as a `{""kind"": ""reader"", ""url"":
6844...}` view block (title + body text + the numbered link list), fetched
6845client-side through `POST /api/read` — the same flag and SSRF posture
6846apply.
6847
6848## The Instant Commands
6849
6850| Input | Effect |
6851|---|---|
6852| `$ pay the hosting bill` | quick note |
6853| `. fix the header` | quick task |
6854| `^https://example.com docs` | save a link |
6855| `~flywheel` | global search across collections |
6856| `/help` | list commands |
6857
6858These never touch the AI — they are one permission-checked record
6859write each, which is why they feel instant.
6860
6861## For Agents
6862
6863Everything above is equally available to AI agents connecting over MCP
6864(`POST /api/mcp`) with their own identities and labeled sessions, and
6865to headless callers hitting `POST /api/ai/chat` directly. One surface,
6866many kinds of operator.
6867"
6868permissions-model Permissions Model Security & Limits 600 A reference guide to DBBASIC's server-side permissions primitive: access modes, rules, row/field filters, sharing, subscriptions, and route enforcement. "DBBASIC permissions are a server-side primitive. Scroll can edit, preview, and
6869explain rules, but the object server must make the final allow/deny decision.
6870
6871Many web frameworks treat permissions as something each app has to rediscover:
6872blog visibility, admin-only pages, intranet roles, or social-app follows. Those
6873cases matter, but they are not enough for a general business platform.
6874
6875DBBASIC needs object-level permissions that can model SaaS, customer portals,
6876employee roles, contractors, paid content, shared workspaces, internal admin
6877tools, and AI-generated app surfaces with the same small set of primitives.
6878Getting this right means most apps need less custom permission code.
6879
6880The model needs to cover the common app cases without forcing every object into
6881one framework shape:
6882
6883- public visitors
6884- signed-in users
6885- paid subscribers
6886- temporary paid access
6887- admins and employees
6888- customer accounts with their own employees
6889- object owners
6890- users or accounts an owner shared with
6891- per-row and per-field restrictions
6892
6893Permissions decide who may *call* an object. What the object's code may then
6894*do* is a separate boundary: user-namespace objects (`u_<uid>_*`) run in a
6895Landlock-sandboxed worker, as a separate OS user that owns nothing, that
6896cannot read secrets, files, other users' data or the network, nor change or
6897inspect other users' files, and reaches its own state, logs and files only through
6898proxies the server checks. See
6899runtime-contract.md ""User Object Isolation"".
6900A system object that user code calls runs with the identity of the original
6901request, never one the user code supplied.
6902
6903## Decision Shape
6904
6905The core API is:
6906
6907```python
6908check_permission(subject, action, policy, collection=None, object_id=None, record=None)
6909```
6910
6911It returns:
6912
6913```python
6914PermissionDecision(
6915 allowed=True/False,
6916 reason=""..."",
6917 code=""allowed|authentication_required|payment_required|forbidden"",
6918 http_status=200|401|402|403,
6919 row_filter={...},
6920)
6921```
6922
6923When a list/query request has a row filter but no specific record, the decision
6924can return `allowed=True` with the row filter attached. The caller then applies
6925that filter before returning rows.
6926
6927```mermaid
6928flowchart TD
6929 A[""request""] --> B[""identify subject""]
6930 B --> C[""load policy""]
6931 C --> D{""admin role?""}
6932 D -- yes --> Z[""allow""]
6933 D -- no --> E{""explicit deny matches?""}
6934 E -- yes --> Y[""deny with reason""]
6935 E -- no --> F{""access mode allows?""}
6936 F -- yes --> Z
6937 F -- no --> G{""allow rule matches?""}
6938 G -- yes --> H[""allow with optional row/field filters""]
6939 G -- no --> I{""owner fallback?""}
6940 I -- yes --> J{""switched off by an owner_fallback rule?""}
6941 J -- no --> Z
6942 J -- yes --> Y
6943 I -- no --> Y
6944```
6945
6946## Persistence And API
6947
6948The current public server stores the active policy as:
6949
6950```text
6951data/permissions/policy.json
6952```
6953
6954If the file does not exist, the server uses a conservative default:
6955
6956```json
6957{
6958 ""access_mode"": ""role_based"",
6959 ""roles"": {},
6960 ""user_roles"": {},
6961 ""rules"": [],
6962 ""admin_roles"": [""admin"", ""superuser""]
6963}
6964```
6965
6966That default has no allow grants. With enforcement on it is enforced as
6967deny-all: every non-admin request is refused, the admin token still works,
6968and `/permissions/status` warns until a real policy is written (by you, or by
6969installing packages). `object_permission_store.starter_policy_payload()`
6970returns the documented starter policy for a fresh deployment: anonymous
6971visitors can execute the public pages (`site_home`, `system_dashboard`,
6972`system_write_probe`) and read the `dbbasic_probe` demo records; signed-in
6973users can write probe records; admin-role subjects bypass rules. It grants a
6974signed-in user nothing else: what they can read and run is what the
6975installed packages' rules (and your own, written per collection or object)
6976give them. Install it with the policy endpoint:
6977
6978```bash
6979python3 -c ""import json, object_permission_store as s; print(json.dumps({'policy': s.starter_policy_payload()}))"" \
6980 | curl -s -X PUT https://your-host/permissions/policy \
6981 -H ""Authorization: Token <admin-token>"" \
6982 -H ""Content-Type: application/json"" --data-binary @-
6983```
6984
6985Then edit grants per app instead of widening the starter rules in place. Run
6986audit mode before enforcement to see what live traffic would be denied.
6987
6988### A wide rule left over from an older starter policy
6989
6990Until 2026-11-29 the starter policy also carried
6991
6992```json
6993{""effect"": ""allow"", ""principal"": ""registered"", ""actions"": [""read"", ""execute""],
6994 ""reason"": ""signed-in users can read and run objects""}
6995```
6996
6997with no collection and no object_id. A rule that names no resource matches
6998every resource, and the engine returns the first allow rule that matches
6999without comparing it with the others, so on a box that started from that
7000policy every signed-in account could run every object (the billing runner,
7001recurring journals, sweepers, every hook, generators a package restricts to a
7002role) and read every collection, and the row filters packages ship on
7003`wallets`, `notes` and the rest decided nothing. With open signup,
7004""signed-in"" means anyone with an email address.
7005
7006New boxes no longer get it. **An existing box still has it**, and nothing
7007removes it for you: it carries no `package` tag, so a package upgrade's
7008retraction never touches it, and the server will not delete an operator's rule
7009on its own. It is made visible instead:
7010
7011- `GET /permissions/unshipped` lists it (state `operator`) with a `wide` line
7012 saying what it grants, and `wide_rules` lists every wide rule in the policy
7013 (an allow for `registered` or `public` with no `collection` and no
7014 `object_id`), whoever it is tagged for;
7015- the startup log prints one `[dbbasic] WIDE permission rule #N ...` line per
7016 such rule when permission checks are on.
7017
7018To remove it: read the policy, drop the rule at the `index` the report gives,
7019and write the policy back. Take the policy as it is, do not retype it.
7020
7021```bash
7022curl -s https://your-host/permissions/policy -H ""Authorization: Token $TOKEN"" \
7023 | python3 -c '
7024import json, sys
7025policy = json.load(sys.stdin)[""policy""]
7026policy[""rules""] = [r for r in policy[""rules""]
7027 if not (r[""effect""] == ""allow"" and r[""principal""] in (""registered"", ""public"")
7028 and not r.get(""collection"") and not r.get(""object_id""))]
7029print(json.dumps({""policy"": policy}))' \
7030 | curl -s -X PUT https://your-host/permissions/policy \
7031 -H ""Authorization: Token $TOKEN"" -H ""Content-Type: application/json"" --data-binary @-
7032```
7033
7034Before you do, run audit mode (or read `GET /permissions/audit`) to see
7035whether anything you rely on was only reachable through it. Packages ship the
7036grants their own pages need; a page or action no package grants and your users
7037must reach needs a rule of your own naming that object or collection. The
7038changed policy takes effect without a restart.
7039
7040The policy endpoints are still admin-gated while broader login, account
7041management, and permission editing mature:
7042
7043```http
7044GET /permissions/policy
7045Authorization: Token <token>
7046```
7047
7048```http
7049PUT /permissions/policy
7050Authorization: Token <token>
7051Content-Type: application/json
7052```
7053
7054```json
7055{
7056 ""policy"": {
7057 ""access_mode"": ""role_based"",
7058 ""roles"": {""sales"": {""label"": ""Sales""}},
7059 ""user_roles"": {""7"": [""sales""]},
7060 ""rules"": []
7061 }
7062}
7063```
7064
7065### Saving a policy is checked; reading one is not
7066
7067A save (`PUT /permissions/policy`, or `object_permission_store.replace_policy`
7068from a shell, which is how the starter policy is installed) is held to DRON
7069(`dron/dron-policy.schema.json`, `docs/dron.md`), the same check a package's
7070`rules.json` gets at install. Before anything is written it refuses:
7071
7072- a key it does not know, on the policy or on a rule, with the closest
7073 spelling (`unknown key 'rowfilter' (did you mean 'row_filter'?)`): the
7074 engine would drop it, and a dropped `row_filter` turns ""each user their own
7075 rows"" into ""every row"";
7076- an effect, action, principal, row-filter operator or `$`-variable that is not
7077 one, a `valid_from`/`expires_at` that does not parse, and any value of the
7078 wrong type the engine would quietly coerce (a number for a collection or a
7079 role, a role listed twice, an `access_mode` left null).
7080
7081The answer is a `400` naming every mistake by rule index, package tag and key
7082(`problems` in the body). Rules the stored policy already holds, as the engine
7083reads them, are not judged again: a save is not refused over rules you did not
7084just write, so `GET /permissions/policy` then `PUT` of the same document
7085saves, including on a box that carries rules from an older release, with one
7086exception below: a serious mistake in the stored file must be fixed in the
7087save that would otherwise write it back.
7088
7089The stored file is different. A policy written by hand on disk, or left by an
7090older release, is read exactly as before: **nothing is refused and no decision
7091changes on upgrade** (unless you turn on the setting described under ""Not
7092applying an allow that is wider than written"" below). Instead each mistake is
7093reported, with what the engine is
7094doing with it today and how to fix it:
7095
7096- an `/admin/status` alert (""Permission policy file has N mistake(s) that let
7097 it allow MORE than written: rule 3 (package app-notes) key 'rowfilter': the
7098 engine ignores this key, so this allow applies to every row ..."");
7099- `policy.findings` in `GET /permissions/status`, one entry per mistake
7100 (`index`, `package`, `key`, `message`, `today`, `fix`, `serious`, and
7101 `applied` on a serious one about an allow rule), and a warning for each
7102 serious one;
7103- `findings` in `GET /permissions/unshipped`;
7104- a `[dbbasic] SERIOUS permission policy mistake, rule N key ...` startup
7105 line per mistake while permission checks are on;
7106- `findings` in a restore's policy-difference preview, for the file the
7107 restore would put back.
7108
7109`serious` marks the mistakes that make the policy allow more than written: a
7110key that would narrow an allow (`row_filter`, `collection`, `object_id`,
7111`fields`, `denied_fields`, `valid_from`, `expires_at`) that is ignored or null,
7112a deny that can never apply (a principal that matches nobody, an expiry that
7113does not parse, a filter that matches no row), and an ignored `rules` or
7114`admin_roles`. The text names rules by index and package tag and keys only:
7115never a rule's `reason` or a user id. To fix one, edit the rule as the `fix`
7116says and save the policy; the save checks your edit.
7117
7118A save cannot quietly make a serious mistake ""written"". Saving rewrites the
7119file as the engine reads it, so a dropped `rowfilter` would come back as an
7120explicit allow on every row and the report would vanish without anyone having
7121decided it. So while the stored file has a serious finding, a save whose policy
7122still holds the affected rule in that widened form (as `GET` returns it) is
7123refused with a `400` naming the finding: rule index, package tag, key, what it
7124does today and how to fix it (`problems` carries the findings, indexed as in
7125the stored file). Fix the rule or remove it in the same save; any other edit
7126waits until then. For an ignored `rulez` or `admin_role`, write the `rules` or
7127`admin_roles` you meant. Smaller (non-serious) findings never block a save.
7128
7129A package install does not erase a serious finding either. Installing (or
7130retiring a package's rules) rewrites the policy file, and it used to write
7131every rule as the engine reads it, so a misspelt `rowfilter` came back as a
7132plain allow on every row and the alert went away. A stored rule with a
7133serious finding is now written back exactly as the file held it, mistake
7134included. The engine reads it the same way, so no decision changes, and the
7135finding stays reported until you fix the rule with your own save.
7136
7137The same holds for a misspelt top-level key with a serious finding (`rulez`,
7138`admin_role`): an install writes the key back under the same name with the
7139same value. The engine goes on ignoring it, so the rules under `rulez` still
7140do not apply and the default admin roles still do; the finding and its alert
7141stay until your own save writes the `rules` or `admin_roles` you meant. An
7142unknown key whose finding is not serious is dropped by an install, as before.
7143
7144### Not applying an allow that is wider than written
7145
7146`DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS` (default: off; `1`, `true`, `yes`
7147or `on` turns it on) changes what the engine does with one kind of serious
7148finding. While it is on, **every stored allow rule with a serious finding
7149grants nothing**: decisions are made as if the rule were not in the policy.
7150That is an allow whose narrowing key (`row_filter`, `collection`, `object_id`,
7151`fields`, `denied_fields`, `valid_from`, `expires_at`) is misspelt and so
7152ignored, or is null. The own-rows allow with a misspelt `row_filter` then
7153shows its users none of the rows, their own included, instead of all of them:
7154the engine does not guess what the key was meant to say. Rules written
7155correctly in the same policy grant as before.
7156
7157The rule is not removed. It stays in the file and in `GET /permissions/policy`,
7158a save still has to fix or remove it, and a package install that rewrites the
7159policy writes the rule back as the file held it. Fix the key as the finding's
7160`fix` says and save, and the rule grants what was written.
7161
7162The finding says which of the two applies, in `today`, in the `/admin/status`
7163alert and in the `/permissions/status` warning, and a serious finding on an
7164allow rule carries `applied`:
7165
7166- setting on: ""... ; this rule is not applied"", `""applied"": false`;
7167- setting off: ""... ; this rule applies more widely than written; set
7168 DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS to stop applying it"",
7169 `""applied"": true`.
7170
7171With the setting off no decision changes. Rules a package installs carry no
7172findings, so they are unaffected either way. If the findings cannot be worked
7173out while the setting is on, the policy is treated as one that cannot be read:
7174requests are refused the way they are for a policy file that does not parse,
7175and `/admin/status` says so.
7176
7177**Deny rules are never touched by this setting.** A deny with a finding (one
7178that can never apply, or one whose dropped key makes it apply more widely) is
7179applied, or not, exactly as before, on and off. Whether a deny that never
7180applies should also fail closed when read is still the owner's open decision
7181(`docs/dron.md`). The serious findings that are not about a rule (an ignored
7182`rules` or `admin_roles` key) are not changed either. The default is off in
7183this release and may turn on in a later one; set the variable to `false` to
7184keep today's behaviour whatever the default becomes.
7185
7186Identity subjects can come from trusted headers, the admin token, or DBBASIC
7187session tokens. The session tokens are backed by a small local registry:
7188
7189```text
7190data/identity/accounts.tsv
7191data/identity/users.tsv
7192data/identity/sessions.tsv
7193```
7194
7195Accounts carry tenant/subscription defaults. Users carry account membership,
7196roles, and user-level subscriptions. A session minted for a registered user
7197takes that account, role, and subscription data from the user's current rows on
7198every request (see ""When a role change, disable or delete takes effect""),
7199giving permission checks the same subject shape whether the request came from
7200Scroll, a gateway, or a future DBBASIC login object.
7201
7202New DBBASIC-created accounts, users, sessions, shared links, record IDs, and
7203change/audit IDs should use UUIDv4 values. Imported systems can keep their old
7204integer or slug IDs as compatibility columns, but new routes and generated UI
7205should not depend on sequential IDs. This keeps SaaS-style tenant data,
7206temporary links, subscriptions, shared records, and future package exports from
7207being tied to one database sequence. The identity registry still accepts string
7208IDs so Django/PostgreSQL data and older Scroll prototypes can migrate without a
7209flag day.
7210
7211Scroll and tests can preview decisions without persisting draft rules:
7212
7213```http
7214POST /permissions/check
7215Authorization: Token <token>
7216Content-Type: application/json
7217```
7218
7219```json
7220{
7221 ""policy"": {
7222 ""access_mode"": ""role_based"",
7223 ""rules"": [
7224 {
7225 ""effect"": ""allow"",
7226 ""principal"": ""role:sales"",
7227 ""actions"": [""read""],
7228 ""collection"": ""contacts"",
7229 ""row_filter"": {""owner_id"": ""$user_id""}
7230 }
7231 ]
7232 },
7233 ""subject"": {""user_id"": ""7"", ""roles"": [""sales""]},
7234 ""action"": ""read"",
7235 ""collection"": ""contacts""
7236}
7237```
7238
7239If `policy` is omitted, `/permissions/check` uses the persisted policy file.
7240The optional `now` field accepts an ISO timestamp for testing temporary access
7241windows.
7242
7243A check that names an `object_id` is answered by the same function the
7244object routes' gate uses, so the preview and the gate cannot disagree: the
7245collection comes from the id, not from the request, and a user object is
7246decided as [Access Modes](#access-modes) and [Sharing](#sharing) describe.
7247
7248## Route Enforcement
7249
7250The public server can enforce the persisted policy against object routes and
7251collection-record routes, but it is intentionally opt-in while auth and Scroll
7252editing mature.
7253
7254```text
7255DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true
7256```
7257
7258**Requested enforcement is always enforced.** With that flag set, every
7259request is decided by the policy, from the first request to the last. There
7260are three modes, and `permissions.mode` in `/permissions/status`, `/identity`
7261and `/admin/status` names the one in force:
7262
7263| `mode` | Flags | What requests get |
7264|---|---|---|
7265| `off` | neither | objects open per route rules, collection data admin-gated, no audit |
7266| `audit` | `DBBASIC_ENABLE_PERMISSION_AUDIT=true` alone | the same as `off`; every decision is logged with `enforced: false` |
7267| `enforced` | `DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true` | every decision applied (and audited) |
7268
7269Shadow (audit) mode exists only when you ask for it. It used to be a
7270fallback as well: the readiness checks below ran on every request, and while
7271any of them failed a requested enforcement was quietly switched off, so the
7272request was decided, logged and **served anyway**, to anonymous callers too.
7273A box that started fenced went open at runtime when its last session
7274expired, its last user was disabled, its users file became unreadable or its
7275policy file was corrupted. Nothing does that any more.
7276
7277**Readiness problems are reported, not acted on by opening.** Each one is
7278handled by what the enforced request path does about it:
7279
7280| Problem | What non-admin requests get | Way back in |
7281|---|---|---|
7282| no admin token (`DBBASIC_ADMIN_TOKEN`) | the policy's decisions; nobody can use the admin APIs over HTTP | the server refuses to start without one (below) |
7283| identity store unreadable (`data/identity/*.tsv`) | a request carrying a session or API key: `503` `identity_store_unavailable` with `Retry-After`; a request without one: what the policy grants anonymous callers | fix the file on the box; the admin token still works for diagnosis |
7284| a user's account row missing or broken (their `account_id` has no row in `accounts.tsv`, there is no `accounts.tsv`, or the row does not parse), or their rows in `users.tsv` naming different accounts | that user's sessions and API keys: `403` `account_unusable`; their sign-in: `403` `account_unusable` after the right password; other users: unaffected | restore or fix the row (`GET /admin/ops?kind=auth&event=account_unusable` names the user, account and reason); or move the user out of the account; for `reason=conflicting`, remove the duplicate user row |
7285| policy invalid or unreadable | `503` `permission_policy_unavailable`; the parse error is shown only to the admin token | `PUT /permissions/policy` with the admin token, or the shell |
7286| `password` access mode (no verifier exists) | `401` unless an explicit allow rule matches | `PUT /permissions/policy` with another mode |
7287| no non-admin sign-in path (the last session expired, the last user was disabled, none configured) | anonymous: what the policy grants anonymous callers, the rest `401`/`403` | the admin token: create users and mint sessions; `/setup` on a waiting one-click box; turn on a sign-in path and restart |
7288
7289Every request loads the policy, the admin token's included. When the load
7290fails, an admin-token request is decided against the built-in default policy
7291instead (whose admin roles let it through), so the owner still reads, runs
7292and repairs while the policy file is broken; everyone else gets the `503`.
7293What the console sees with the admin token on a broken policy:
7294
7295- `GET /admin/status` and `GET /permissions/status`: `200`, with a leading
7296 alert ""Permission policy file is invalid: <error>"" (or ""could not be read""),
7297 `permissions.policy.valid: false`, mode still `enforced`; counts that need
7298 the policy are `null` (`inventory.unavailable` lists them).
7299- `GET /permissions/policy`: `200` with `{""policy"": null, ""error"": ""..."",
7300 ""raw"": ""<file text, first 64 KB>"", ""raw_truncated"": false}`; `raw` is
7301 omitted when the file cannot be read at all. A non-admin gets the `503`
7302 with no detail. Repair with `PUT /permissions/policy`.
7303- Routes whose answer depends on the policy's rules (collection and schema
7304 listings, collection detail and change history, `GET /permissions/unshipped`,
7305 search) answer `503` `permission_policy_unavailable` with `error_detail`, so
7306 a collection never quietly becomes known or unknown.
7307An admin-role user signed in with a session is not the admin token: which
7308roles are admin is named in the policy, so they wait for the repair like
7309everyone else, and with `DBBASIC_ENABLE_SESSION_ADMIN_GATES` their session
7310does not pass the admin gates either until the policy can be read. WebDAV
7311answers the same `503` rather than an empty folder, which a sync client
7312would take as every file deleted.
7313
7314A single-record read (`GET /collections/{c}/records/{id}`, `GET /api/files/{id}`)
7315is decided at the collection level before the record is looked up, and a row
7316the caller may not read answers the same `404` as an id that does not exist,
7317so the status tells nobody which ids exist.
7318
7319A person's files have two ways in, `/api/files` and the WebDAV folder
7320`/dav/files/`, and under enforcement both ask the same questions in the
7321same order: may this subject do the action on the `files` collection at all
7322(no record, so no owner fallback), and only then may they do it to this
7323file. Every WebDAV verb that reads the folder (`PROPFIND`, `PROPPATCH`,
7324`GET`, `HEAD`, `PUT`, `DELETE`, `MOVE`, `COPY`) needs `read` on the
7325collection first; then `DELETE` needs `delete`, a rename or a replacing
7326`PUT` `update`, a new file `create`. A folder the caller may not read is a
7327`403`, never an empty listing. Under a policy with no `files` rules the
7328owner is refused on both, as on the record routes ([Ownership](#ownership)).
7329
7330At startup the server logs a `WARNING` naming each problem and the fix, and
7331`GET /admin/status` leads with it in `alerts` (""Permission enforcement is ON,
7332and ...""). After startup, at most once a minute per process, the server
7333re-checks: a new problem is logged as an `ERROR`, a cleared one as `INFO`,
7334and each change is an ops-log row (`GET /admin/ops?kind=permission_readiness`).
7335
7336**The one refusal: no admin token.** Enforcement without
7337`DBBASIC_ADMIN_TOKEN` refuses to start (the ASGI lifespan reports startup
7338failed, so uvicorn exits): the token is the way in for every other problem,
7339and the only way to repair a broken policy over HTTP. For one release,
7340`DBBASIC_ALLOW_START_WITH_BLOCKED_ENFORCEMENT=true` starts it anyway,
7341**enforced**, with a startup line saying so; the repair for any problem is
7342then the shell. It used to start the server unenforced, and no longer does;
7343it goes away in a later release. To serve without enforcement on purpose,
7344set `DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=false` and
7345`DBBASIC_ENABLE_PERMISSION_AUDIT=true`.
7346
7347**Requiring enforcement.** A hosted, multi-user box should set
7348`DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT=true`. The server then refuses to
7349start unless the mode is `enforced` (`off` and `audit` both refuse), with
7350one line: `Refusing to start: DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT=true and
7351permission enforcement is off; set DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true.`
7352It is opt-in and changes nothing unset. Like the admin-token refusal it is
7353checked in the ASGI lifespan, so a server run with the lifespan turned off
7354(`uvicorn --lifespan off`) skips it.
7355
7356`DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT` no longer does anything (it
7357used to force enforcement despite the readiness checks, which is now what
7358always happens); the server says so at startup. Remove it.
7359
7360A fresh box is enforced from its first request. The supported order for a
7361fresh box with enforcement on:
7362
73631. set `DBBASIC_ADMIN_TOKEN` (the way in while nobody else can sign in);
73642. turn on a sign-in path: `DBBASIC_ENABLE_PASSWORD_LOGIN=true`, trusted
7365 headers, guarded session login, or an identity source;
73663. save a policy before the first start, e.g.
7367 `object_permission_store.replace_policy(object_permission_store.starter_policy_payload(), base_dir=DATA_DIR)`
7368 if you want the starter grants (a one-click box does not: its policy is the
7369 rules its starting apps ship). Skipping it is safe: the box
7370 starts deny-all and you save one later with `PUT /permissions/policy` or
7371 by installing packages, using the admin token;
73724. start, and make the first admin through `/setup` (a one-click box, which
7373 answers only `/health` and `/setup` until then) or with the admin token.
7374
7375Without step 1 the server refuses to start. Without step 2 it starts
7376enforced with a warning: only the admin token and public grants get in.
7377
7378Operators can see the state through:
7379
7380```json
7381{
7382 ""permissions"": {
7383 ""mode"": ""enforced"",
7384 ""enforcement_requested"": true,
7385 ""enforcement_enabled"": true,
7386 ""enforcement_blocked"": false
7387 }
7388}
7389```
7390
7391`enforcement_blocked` is always `false` now and is kept for one release for
7392clients that read it.
7393
7394When enforcement is on, protected routes call the same decision engine
7395before serving or executing data:
7396
7397```mermaid
7398flowchart LR
7399 A[""HTTP request""] --> B[""map subject""]
7400 B --> C[""map route to action""]
7401 C --> D[""load data/permissions/policy.json""]
7402 D --> E[""check_permission""]
7403 E --> F{""allowed?""}
7404 F -- yes --> G[""serve route""]
7405 F -- no --> H[""return 401 / 402 / 403""]
7406 E --> I[""append data/permissions/audit.jsonl""]
7407```
7408
7409Route actions currently map like this:
7410
7411- `GET /objects/{id}` -> `execute`
7412- `POST /objects/{id}` -> `execute`
7413- `PUT /objects/{id}` -> `update`
7414- `DELETE /objects/{id}` -> `delete`
7415- `?source=true` -> `source`
7416- `?state=true` -> `state`
7417- `?logs=true` -> `logs`
7418- `?versions=true` or `?version=N` -> `versions`
7419- `?metadata=true` -> `read`
7420- `GET /collections/{collection}/records` -> `read`
7421- `POST /collections/{collection}/records` -> `create`
7422- `GET /collections/{collection}/records/{record_id}` -> `read`
7423- `PUT /collections/{collection}/records/{record_id}` -> `update`
7424- `DELETE /collections/{collection}/records/{record_id}` -> `delete`
7425
7426Collection record lists apply row filters before pagination. Record detail
7427checks include the selected record, so owner, account, subscription, temporary
7428access, row-filter, and field-redaction rules can all be enforced by the server.
7429Record writes check the affected record. Updates also check the candidate row
7430after applying the submitted changes, so a user cannot pass a row filter on the
7431old row and then move the row into another owner/account by changing fields.
7432Both checks read the row before the write lock, so the write carries that
7433row's fingerprint and is refused with `409` `""code"": ""conflict""` (nothing
7434written) when the row under the lock is another one: a row given to someone
7435else between the check and the write is not written on the old decision.
7436The client reads it again and retries, and the retry is decided on the row
7437as it now is (docs/dron-write-semantics.md S52).
7438
7439By default the collection record routes are admin-token gated. Read routes can
7440use audit or enforcement mode with the active policy. Write routes require the
7441admin token unless permission enforcement is enabled and the active policy
7442allows the matching `create`, `update`, or `delete` action. Audit-only mode logs
7443write decisions, but it does not authorize mutations by itself.
7444
7445### Row-filter index
7446
7447With enforcement on, a list of a collection (and `/api/search`, an
7448anonymous visitor's public rows, and the relation-label fetches a form
7449makes) runs the decision engine once per row of the WHOLE collection, for a
7450user who may see a handful. Measured in a full install: 10,044 engine calls
7451and about 94% of the request to list 40 visible notes out of 10,000.
7452
7453```text
7454DBBASIC_ROW_FILTER_INDEX=off | shadow | on (default: off)
7455```
7456
7457- `off` -- every row is read and checked. Today's behaviour.
7458- `on` -- the server first plans, from the policy and the subject alone,
7459 the equality lookups that are a superset of the rows the subject could be
7460 allowed (""`owner_id` is u7"", ""`project_id` is one of p1, p2"",
7461 ""`is_public` is true""), finds those rows through a per-field index kept
7462 beside the records cache, and runs the engine on them only. The engine
7463 still decides every row that is returned, so the index can never show a
7464 row it should not; the differential tests
7465 (`tests/test_row_filter_pushdown.py`, `..._http.py`) are what stop it
7466 from hiding one. Responses are identical to `off`: same rows, order,
7467 `total`, `count`, `has_more`, `revs`, redaction.
7468- `shadow` -- both are computed, the full scan is served, and any
7469 difference is recorded as a `row_filter_shadow` row in the ops log
7470 (`GET /admin/ops?kind=row_filter_shadow`): ids and counts, never record
7471 contents. At most one row per collection per minute and 200 in the life
7472 of a process, so a wrong index cannot crowd login failures out of the
7473 log the lockout reads. Run this before `on`; it costs more than `off`.
7474
7475A list is not narrowed, and costs what it does today, when: the subject is
7476an admin; the access mode allows reads without rules (`public`,
7477`registered`, `subscription`); a rule that applies has no row filter (the
7478subject sees everything) or only `ne` / range conditions; any filter in the
7479policy uses an unknown operator; the collection is too large for the
7480records cache (`DBBASIC_RECORDS_CACHE_MAX_ROWS`); or the only equality a
7481rule has is on a `store: extra` field. Deny rules never narrow.
7482
7483The index is built lazily, one field at a time, by the first narrowed read
7484after each write to a collection, and only for the fields that rules and
7485the owner keys (`owner_id`, `user_id`, `created_by`) compare by equality.
7486It costs 4 bytes per row per field plus about 120 bytes per distinct value
7487of that field, and 0.3-0.9 ms per field per 10,000 rows to build. Measured
7488on 10,000 notes with the five fields the notes rules use: 3 ms to build,
74890.4 MiB (40 bytes per row in all); 30,000 notes: 9 ms, 1.2 MiB. The worst
7490case is a field whose every value is different, about 120 bytes per row
7491(60 MB for one such field at the cache's 500,000-row ceiling); `id`, the
7492usual such field, reuses the cache's existing id index and costs nothing.
7493The index lives and dies with the records cache entry it describes, so it
7494has no invalidation of its own, no file, and no knob beyond the cache's
7495(`DBBASIC_RECORDS_CACHE_MAX_ENTRIES`, `DBBASIC_RECORDS_CACHE_MAX_ROWS`).
7496
7497Time-windowed rules (`valid_from` / `expires_at`) are evaluated at one
7498instant per list request, in every mode: the collection check, the row
7499filter, a field filter and the field redaction all decide at the same
7500reading of the clock. (Before 2026-12, `off` read the clock once per check,
7501so a list running across the instant a rule's window closed could let a row
7502through under the rule and then redact it under no rule, which removed
7503nothing.)
7504
7505Audit-only mode logs decisions without blocking the request:
7506
7507```text
7508DBBASIC_ENABLE_PERMISSION_AUDIT=true
7509```
7510
7511It serves exactly what `off` serves: collection records, record detail,
7512search and user files still need the admin token, as they do with no
7513permission flag at all; objects answer per their route rules. (Until this
7514release, turning the audit log on skipped those admin gates and served every
7515row to anyone, so the observer changed what was served.) That is useful
7516before turning enforcement on for a live app. Enforcement also writes audit
7517entries.
7518
7519The audit log is bounded like object logs. When `data/permissions/audit.jsonl`
7520reaches `DBBASIC_PERMISSION_AUDIT_MAX_BYTES` (default `10485760`; `0` or less
7521never rotates) it is cut into `audit-<sequence>-<timestamp>.jsonl` beside it.
7522Each segment is gzip-compressed at the following cut, and only the newest
7523`DBBASIC_PERMISSION_AUDIT_KEEP_ROTATED` segments are kept (default `32`; `0` or
7524less keeps all). The audit endpoint reads back through the segments when the
7525active file holds fewer matching entries than `limit`.
7526
7527Operators and Scroll can read recent audit entries through the admin-gated audit
7528endpoint:
7529
7530```http
7531GET /permissions/audit?limit=100&object_id=site_home
7532Authorization: Token <token>
7533```
7534
7535Supported filters are `action`, `object_id`, `collection`, `allowed`, and
7536`enforced`.
7537
7538By default, route checks only trust the admin token and anonymous public traffic.
7539If a reverse proxy or auth gateway has already authenticated the request, trusted
7540identity headers can be enabled explicitly:
7541
7542```text
7543DBBASIC_PERMISSION_TRUST_HEADERS=true
7544```
7545
7546Supported headers:
7547
7548- `X-DBBASIC-User-Id`
7549- `X-DBBASIC-Account-Id`
7550- `X-DBBASIC-Roles`
7551- `X-DBBASIC-Subscriptions`
7552
7553Only enable trusted headers behind infrastructure that strips or overwrites
7554client-supplied copies.
7555
7556### Identity sources
7557
7558An *identity source* is another service vouching for who a caller is
7559(`object_identity_sources.py`). It takes the request headers and returns a
7560principal -- user id, optional account id, roles, display name -- or nothing.
7561Sources are configured from the environment, consulted in order (first answer
7562wins), and **fail closed**: an exception, a timeout, a non-200, an oversized,
7563redirected or non-JSON answer all mean ""not authenticated by this source"".
7564
7565Order of resolution for a request (`_permission_identity`):
7566
75671. the admin token -- always wins, and is never forwarded anywhere;
75682. a `dbk_` API key;
75693. a local session (Authorization header or cookie);
75704. configured identity sources, for an Authorization token none of the
7571 above recognised (cookies are never forwarded);
75725. trusted headers, when `DBBASIC_PERMISSION_TRUST_HEADERS=true`;
75736. anonymous.
7574
7575A principal becomes the same `PermissionSubject` a session user gets (user
7576id, account id, roles, then project grants and record shares), so the
7577permission engine, owner fallback, audit log and the `_identity` an object
7578sees treat it exactly like a local user; `GET /identity` reports
7579`auth.method` as `identity_source:<name>`.
7580
7581**A remote identity may not take over a local user.** When the upstream's
7582`user_id` names a user in this box's registry (`users.tsv`; users are keyed
7583by user id here, and the verify answer carries no email), the identity is
7584refused unless that local user is explicitly linked to the source -- the
7585user's `identity_source` field equals the source name (`http_verify`).
7586Unlinked is the default for every user. Link one with
7587`identity_source` in `POST /identity/users`, or from the shell:
7588
7589```text
7590python -m object_identity_cli set-identity-source --user-id 7 --source http_verify
7591python -m object_identity_cli set-identity-source --user-id 7 --unlink
7592```
7593
7594Only a row in `users.tsv` makes a user id local. A password, sessions or API
7595keys left under an id with no row (a user removed by hand) do not, and a
7596remote identity with that id cannot reach them: keys and passwords are
7597managed only with that user's own local session or the admin gate, password
7598sign-in needs a user row, and a session or key works only for whoever holds
7599its token. Creating a local user under such an id refuses or clears them
7600first (`POST /identity/users`, `clear-leftovers`).
7601
7602A refusal is an `auth` ops-log row, `event: identity_source_collision`, with
7603the user id and `auth_method: identity_source:<name>` (never the token or its
7604hash), at most one a minute per source and user id. A linked user id the
7605local registry has disabled is refused too, as for trusted headers.
7606
7607**A source confers only the roles you allow.**
7608`DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES` (comma-separated, e.g.
7609`viewer,editor`) lists the role names the verify source may confer. **Unset
7610or empty, it confers none**: the upstream says who somebody is, and only an
7611operator decides which of its role names mean anything here. Roles the
7612upstream names outside the list are dropped, and the drop is an `auth`
7613ops-log row (`event: identity_source_roles_dropped`, `label:
7614roles=<names>`, the user id; at most one a minute per source and user id).
7615A malformed name in the setting refuses the source (an `ERROR` at startup).
7616
7617**A source can never make anyone admin.** `admin`, `superuser` and every
7618role in the policy's `admin_roles` are stripped from what a source says even
7619when the allowlist names them (all roles are dropped if the policy cannot be
7620read), upstream flags such as `is_staff`/`is_superuser` are not read, and
7621the operator gates (admin token, admin session) never consult sources. Note
7622that a policy's own `user_roles` entry for that user id still applies --
7623that is the operator granting it, not the upstream.
7624
7625The user id must be a canonical positive integer -- a JSON int, or a string
7626of digits with no sign, whitespace or leading zero -- because it is the
7627`u_<id>_` object namespace (see
7628[User objects](/docs/http-api-contract#user-objects-non-admin-callers)). `""007""`,
7629`"" 7""`, `7.0` and `true` have authenticated nobody. An `account_id`, when the
7630answer carries one, must match the account id rules (letters, digits and
7631`_ . : @ -`, starting with a letter or digit, at most 128 characters), so
7632`""../x""` is refused. The answer must also declare `Content-Type:
7633application/json` (a `; charset=` suffix is fine); an HTML error page with a
7634JSON-looking body is not an answer.
7635
7636The first source is `http_verify`:
7637
7638```text
7639DBBASIC_IDENTITY_VERIFY_URL=https://app-internal:8443/api/auth/verify/
7640DBBASIC_IDENTITY_VERIFY_SECRET=<shared secret, 16-512 visible ASCII characters>
7641DBBASIC_IDENTITY_AUDIENCE=box-a.example.com
7642```
7643
7644Off when unset. The source is **refused** -- not used at all, an `ERROR`
7645line at startup says why (never quoting the secret), `GET /admin/status`
7646lists the same reason in `alerts` and in
7647`capabilities.identity.identity_source_refused`, `GET /permissions/status`
7648in `permissions.identity_source_refused` and `warnings` (none of them quote
7649the secret or the URL), and its users arrive as anonymous -- when:
7650
7651- the URL is not `https://`, unless its host is loopback (`127.0.0.0/8`,
7652 `::1` or the name `localhost`; a Compose service name or a private
7653 address is not loopback). A URL with `user:password@` is refused too.
7654 The same check runs again before every call, and redirects are never
7655 followed, so a credential never crosses plain http to another host;
7656- the host is not loopback and `DBBASIC_IDENTITY_VERIFY_SECRET` is unset
7657 (or is not 16 to 512 visible ASCII characters with no spaces);
7658- `DBBASIC_IDENTITY_AUDIENCE` is unset or not a name (letters, digits and
7659 `_ . : @ / -`, starting with a letter or digit, at most 256 characters).
7660
7661A configured source also counts as a user sign-in path in the
7662enforcement readiness check (`/permissions/status` shows
7663`permissions.identity_source_configured`). For a request carrying `Authorization: Token ...` (or
7664`Bearer ...`) it sends that header verbatim in a `GET` with
7665`Accept: application/json` to the URL (a 3 s deadline for the whole exchange -- connect, TLS, headers and body -- 64 KiB response
7666cap, no redirects followed, no proxy), and maps an HTTP 200 JSON body naming
7667this server as its audience to a principal.
7668
7669**Wire shape, for whoever implements the verify endpoint.** The request:
7670
7671```http
7672GET /api/auth/verify/
7673Authorization: Token <the caller's token, verbatim>
7674Accept: application/json
7675X-DBBASIC-Audience: box-a.example.com
7676X-DBBASIC-Verify-Secret: <DBBASIC_IDENTITY_VERIFY_SECRET>
7677```
7678
7679`X-DBBASIC-Verify-Secret` is omitted when no secret is configured (loopback
7680only). The endpoint should compare it in constant time and refuse a request
7681without it, and should check that the token may be used at the box named in
7682`X-DBBASIC-Audience`. A token it recognises is answered `200` with
7683`Content-Type: application/json`:
7684
7685```json
7686{""audience"": ""box-a.example.com"", ""user_id"": 7, ""username"": ""alice"",
7687 ""account_id"": ""acct_1"", ""roles"": [""editor""]}
7688```
7689
7690`audience` is required and must be a string equal to this server's
7691`DBBASIC_IDENTITY_AUDIENCE` -- a missing, different or list-valued audience
7692authenticates nobody (cached as a refusal for 10 s). `user_id` is required;
7693`username`, `account_id` and `roles` are optional.
7694
7695The two refusals mean different things, so send the right one:
7696
7697- `401`: **the token is not valid** (unknown, expired, revoked, not usable
7698 at this audience). The request itself was acceptable: the shared secret
7699 matched and the audience is one the endpoint serves. One user's sign-in
7700 fails; nothing is recorded.
7701- `403`: **this server is not accepted**, whatever the token: a missing or
7702 wrong `X-DBBASIC-Verify-Secret`, or an `X-DBBASIC-Audience` the endpoint
7703 does not serve. Every sign-in fails, so the server records it for the
7704 operator (below).
7705
7706For the caller both are the same: the token is refused and the request goes
7707on as anonymous. Anything else (another status, a redirect, a
7708timeout, a body over 64 KiB) means ""could not check"" and the caller gets
7709`503`. Answers are cached, keyed by a SHA-256 of the header
7710value -- raw tokens are never stored or logged -- in a cache bounded to 4,096
7711entries: positive answers for `DBBASIC_IDENTITY_CACHE_TTL_SECONDS` (default
771230; a larger value than 60 is clamped to 60 with a `WARNING` at startup, and
7713nothing in the upstream's answer extends it), a definite refusal (401, 403, or a 200 that is not a valid
7714principal) for 10 s. The lookup runs in a thread before routing so a slow
7715upstream never blocks the event loop.
7716
7717An upstream that answers `403` (it refuses this server), or answers `200`
7718without this server's audience, or with something that is not a JSON object,
7719refuses every user it vouches for, which from outside looks like ""everyone is logged out"".
7720The sign of it: an `auth` ops-log row, `event:
7721identity_source_audience_refused` (one event for every ""the upstream is not
7722accepting this server"" reason), `auth_method: identity_source:<name>` and
7723`label: reason=upstream_forbidden refused=<n>` (the upstream answered `403`:
7724check that `DBBASIC_IDENTITY_VERIFY_SECRET` here and the upstream's secret
7725match, and that `DBBASIC_IDENTITY_AUDIENCE` matches the upstream's audience
7726setting) or `reason=audience_missing` (the answer has no `audience`
7727key -- an upstream not yet updated to echo it) or `reason=audience_mismatch`
7728(the key is there but is not this server's name) or `reason=not_json` (the
7729`200` is not a JSON object: an HTML page such as a login page the upstream
7730redirected to, a list, text that does not parse), at most one row a minute
7731per source and reason, `<n>` counting the answers refused since the previous
7732row. `GET /admin/status` lists an alert saying the same in plain words for
7733ten minutes after the last such answer, naming every reason seen; it clears
7734at once when the upstream answers `200` with the right audience. Neither
7735quotes a token, a user, the URL, the secret or the audience value. A `401`
7736leaves no row and no alert, even when every answer is one: on a quiet box
7737that is just users with stale tokens.
7738
7739**A credential the server could not check is a 503, not ""anonymous"".** When
7740all 8 verify slots are busy (each is held for at most the 3 s deadline, so a
7741slow upstream cannot keep them), or the verify service is unreachable, times out
7742or answers 5xx (or anything other than 200/401/403), a request that carried an
7743`Authorization` token meant for the sources is answered `503` with
7744`Retry-After: 2`. Such failures are never cached, so users are recognised
7745again the moment the service is back. Requests with no Authorization header,
7746the admin token, `dbk_` keys and local sessions never touch the verify path.
7747
7748**Revocation.** A revoked token keeps working until its cache entry expires
7749(at most the TTL). To cut that short, the upstream calls, with the admin token:
7750
7751```http
7752POST /admin/identity/sources/forget
7753Authorization: Token <admin-token>
7754Content-Type: application/json
7755
7756{""token_hash"": ""<sha256 hex of the Authorization header value>""}
7757```
7758
7759or `{""all"": true}`. The hash is `sha256(""Token abc123"")` over the full header
7760value, lower-case hex -- the server never accepts, logs or echoes a raw token
7761here. The answer is `{""status"": ""ok"", ""forgotten"": <n>}`. A lookup that was in
7762flight when the entry was forgotten does not store its answer.
7763
7764**One Authorization header only.** A request with more than one
7765`Authorization` header is refused with `400` on every route, so a proxy and
7766this server cannot pick different credentials.
7767
7768**Point it only at a trusted internal service you control.** Every caller's
7769credential is sent to it, and whatever it answers for this audience is
7770believed. Only `https` URLs (or `http` to loopback) are accepted; anything
7771else configures no source.
7772
7773The verify service's user ids share the id space with the local identity
7774registry (and so the `u_<id>_` objects, grants and shares). A box can use
7775both only for ids that do not collide, or for local users an operator has
7776linked to the source (above).
7777
7778The server can also mint DBBASIC identity sessions:
7779
7780```http
7781POST /identity/sessions
7782Authorization: Token <admin-token>
7783```
7784
7785The admin route can mint arbitrary operator-controlled sessions. For a login
7786gateway or local trusted client, `POST /identity/session` can mint a session for
7787an existing active user when `DBBASIC_ENABLE_SESSION_LOGIN=true` and the caller
7788presents `DBBASIC_SESSION_LOGIN_TOKEN`. That token is separate from the admin
7789token. The route accepts only `user_id`, `label`, and `ttl_seconds`; role,
7790account, and subscription overrides are rejected so the subject comes from the
7791registered user and account.
7792
7793Sessions store only a token hash under `data/identity/sessions.tsv`. Requests
7794can then send `Authorization: Token <session-token>` or
7795`Authorization: Bearer <session-token>`, and the server resolves the subject
7796directly from its local identity store. This is the first built-in replacement
7797for each app hand-rolling the same ""current user, current account, current
7798roles, current subscription"" lookup.
7799
7800### When a role change, disable or delete takes effect
7801
7802A credential never carries more than its user has now. Sessions and API keys
7803name a user; on every request the server reads that user's row in
7804`data/identity/users.tsv` (a stat-cached parse, re-read when the file changes,
7805whoever changed it) and takes the user's standing and roles from it. So,
7806whether the change came through the admin routes, the CLI, another process or
7807a hand edit of the file:
7808
7809| Change | Sessions | API keys |
7810| --- | --- | --- |
7811| a role removed | gone on the next request | gone on the next request |
7812| a role granted | applies on the next request, no new sign-in | applies on the next request |
7813| user disabled (any status but `active`) | refused on the next request and ended (marked revoked) | refused on the next request and deleted |
7814| user's row deleted | refused on the next request and ended | refused on the next request and deleted |
7815| user re-enabled, or re-created with the same id | old sessions stay ended: sign in again | old keys stay deleted: mint new ones |
7816| password reset by emailed link | every session revoked | not touched |
7817| password set, changed or removed by an admin (HTTP route or CLI) | every session revoked | not touched |
7818| an admin changing or removing their own password with their session | every session revoked except the one making the request | not touched |
7819| first password (signup confirmation, first-time setup, `create-superuser`) | nothing to revoke | not touched |
7820| the user's account disabled (`PUT /identity/accounts/{id}/status`, `disable-account`) | refused on the next request and ended | refused on the next request, **kept** |
7821| the account re-enabled | old sessions stay ended: sign in again | work again, unchanged |
7822| the account's subscription removed (a billing lapse) | still signed in; `subscription:` rules stop matching on the next request | unaffected: keys never carry the account's subscriptions |
7823
7824Password changes revoke at the moment of the change, in the one function
7825that writes the password (`object_credentials`), so it does not depend on
7826enforcement or on which route or tool did it. If the new password is saved
7827but the sessions cannot be ended, the change is reported as a failure (HTTP
7828`500 password_sessions_not_ended`, CLI exit 1), not success; setting the
7829password again retries. API keys are a separate credential and survive a
7830password change. If the account may be compromised, a new password is not
7831enough on its own: revoke the user's keys
7832(`DELETE /identity/users/{id}/api-keys/{key_id}`) or disable the user
7833(`PUT /identity/users/{id}/status` or `/offboard`, which end sessions and delete keys).
7834
7835""Ended"" for the other rows happens when the credential is next presented. The status and
7836offboard routes revoke everything at once anyway; a status or deletion made
7837outside them is refused immediately and ended at first use. A user deleted
7838by hand and re-created with the same id before an old session or key is
7839presented again would find it alive, with the new row's roles, so creating a
7840user looks for credentials left under its id first: a password, sessions
7841still signed in, API keys. By default (`POST /identity/users`, the CLI's
7842`create-user`) the create is refused and nothing changes, with an error
7843naming what was found; `python -m object_identity_cli clear-leftovers
7844--user-id <id>` removes them (only for an id with no user), and then the id
7845is free. A signup clears them itself, with a warning in the log, since its id
7846is new and random. First-time setup and `create-superuser` keep the password
7847they have just written but end leftover sessions and delete leftover keys,
7848since they wrote neither.
7849
7850Roles granted through the policy's `user_roles` map are policy, not identity,
7851and always applied on the next request.
7852
7853Subscriptions and account membership follow the same rules as roles. A
7854session's account is the user's current `account_id`, and its subscriptions
7855are the user's own plus their account's, read from `users.tsv` and
7856`data/identity/accounts.tsv` (stat-cached the same way) on every request. So
7857a subscription cancelled on the user or on the account stops matching
7858`subscription:` rules on the next request; a user moved to another account
7859is in the new one (`account:` rules, `$account_id` row filters) on the next
7860request, and a user taken out of one has no account. An account whose row is
7861gone contributes no subscriptions; a disabled account refuses its users
7862altogether (below). API keys read the user's row on every request too and
7863have the user's own subscriptions and account; they do not add the account's
7864subscriptions.
7865
7866#### Disabling an account, and a billing lapse
7867
7868Two different operations, for two different situations:
7869
7870- **Disable the account** (`PUT /identity/accounts/{id}/status`
7871 `{""status"": ""disabled""}`, or `object_identity_cli.py disable-account
7872 --account-id {id}`) when nobody from that account may use the box at all:
7873 abuse, a compromised tenant, a contract ended. On the next request every
7874 session and API key of its users is refused (whatever their roles, admin
7875 included, as for a disabled admin user), its users cannot sign in, and
7876 their sessions are ended. API keys are kept but refused, so a mistaken or
7877 temporary disable does not break the customer's integrations for good.
7878 Re-enabling (`{""status"": ""active""}`, `enable-account`) lets them sign in
7879 again and makes the same keys work again; no session comes back. The admin
7880 token, and admins who are not in the account, are never affected, so an
7881 operator cannot lock themselves out this way. The route writes an
7882 `account_status_set` ops line. Details in
7883 [http-api-contract.md](/docs/http-api-contract) (""Account Status"").
7884- **Remove the subscription** for non-payment. A billing lapse is not a
7885 disable: the customer has to be able to sign in to pay. Take the plan out
7886 of the account's `subscriptions` (and the user's, if it was granted there):
7887 on the next request `subscription:` rules stop matching, while the user
7888 stays signed in, can sign in fresh, keeps the account (`account:` rules,
7889 `$account_id` filters) and their API keys. Putting the subscription back
7890 applies on the next request, with no new sign-in. Use
7891 `PUT /identity/accounts/{id}/subscriptions` `{""subscriptions"": [...]}` (the
7892 whole list; `[]` for none) or `object_identity_cli.py
7893 set-account-subscriptions --account-id {id} --subscriptions pro,team`:
7894 input is validated, the write is atomic, and each change leaves an
7895 `account_subscriptions_set` ops line with who did it and the list before
7896 and after ([http-api-contract.md](/docs/http-api-contract), ""Account
7897 Subscriptions""). A hand edit of the `subscriptions` column of
7898 `data/identity/accounts.tsv` is still picked up on the next request, but
7899 is neither validated nor recorded. A member's subscriptions are their own
7900 (user row) plus the account's, so a name the user holds on their own row
7901 survives its removal from the account; API keys carry only the user's own.
7902 Plan the rules so that what a lapsed customer still
7903 needs (their invoices, the billing page) is granted to `registered` or
7904 `account:` principals, not only to `subscription:` ones.
7905
7906To check this, `accounts.tsv` is consulted on every request of a user who
7907has an account, by session or API key (one `stat`, re-parsed only when the
7908file changes; users with no account do not touch it). If it cannot be read the request is
7909`503 identity_store_unavailable` under enforcement and carries no credential
7910otherwise, as for `users.tsv` (below); nothing is revoked or deleted. An
7911account row that does not parse refuses its users without ending anything,
7912so fixing the row restores them. A user whose `account_id` names an account
7913with no row at all (or when there is no `accounts.tsv`) is refused the same
7914way; this used to refuse nobody. Both are fail-closed refusals with their
7915own code: under enforcement every request with such a user's session or API
7916key is `403 account_unusable` (a fixed message; the admin token sees which
7917account and why in `error_detail` on admin routes), otherwise the
7918credential carries no authority; signing in is `403 account_unusable` in
7919both modes, and only after the right password, so nobody learns of it
7920without one (the browser form redirects to `/login?error=account`). Each
7921refusal writes an `account_unusable` ops `auth` line naming the user, the
7922account and `reason=missing` or `reason=unparsed` (at most one a minute per
7923user, account, reason and method). A user with several rows in `users.tsv`
7924that name different accounts (or where one names none) is refused the same
7925way, `reason=conflicting`, with every account named as the `identifier`
7926(`acme,globex`; `(none)` for a row naming none): those rows used to merge
7927into a user with no account, which skipped every account check. Duplicate
7928rows that agree are read as before. Nothing is ended or deleted, so
7929restoring the row restores everyone. Users whose row names no account (a
7930single-user install, users created before accounts existed: an empty
7931`account_id` or no such column) never read `accounts.tsv` and are not
7932affected by its state. An ad hoc session for a user id with no row, and an
7933account id asserted by a gateway or identity source, are not refused for
7934naming an account this box has no row for. A disable written outside the route ends each session the
7935first time it is presented, like a user disabled by hand.
7936
7937Which roles, subscriptions and account a session has depends on how it was
7938minted:
7939
7940- **From the user's row** (every sign-in route, and `POST /identity/sessions`
7941 without `roles` or `subscriptions`): the user's current roles, account and
7942 subscriptions.
7943- **With explicit `roles` or `subscriptions`** (`POST /identity/sessions` for
7944 a registered user): the roles and subscriptions it was minted with less any
7945 the user no longer has, and its account only while the user is still in it.
7946 A narrowed session stays narrow; nothing the user does not hold gets
7947 through; a role, subscription or account the user gains later needs a new
7948 session.
7949- **For a user id with no row** (an ad hoc gateway session; refused under
7950 `DBBASIC_REQUIRE_KNOWN_IDENTITY_USERS=true`): the roles it was minted with,
7951 since there is nothing to compare them with. If a row for that id appears
7952 later, the row caps them. An API key for such an id authenticates as the
7953 id with no roles, as before.
7954- **Written by an older server** (a `sessions.tsv` row with no `roles_from`
7955 column, or an `api_keys.tsv` row with no `user_bound` column): capped by the
7956 user's roles, subscriptions and account while the row exists, like an
7957 explicit session; a deleted user's old session keeps its stored values, and an old key the user id with no roles, until they expire or
7958 are revoked, because such rows cannot tell ""deleted"" from ""never
7959 registered"". Revoke them (`PUT /identity/users/{id}/status`) or wait out
7960 the session TTL (at most 30 days, 24 hours by default).
7961
7962If `users.tsv` cannot be read, or is missing while a credential names a
7963registered user, or `accounts.tsv` cannot be read when a session needs its
7964user's account's subscriptions, the request is not guessed at: under enforcement it is
7965`503 identity_store_unavailable` with `Retry-After` (see Route Enforcement),
7966otherwise it carries no credential. Nothing is revoked, so restoring the file
7967restores everyone. A row that does not parse refuses that user's credentials
7968without ending them, so fixing the row restores them.
7969
7970Users from an identity source (above) have no local session and no stored
7971roles here: their roles are the upstream's latest answer (less anything
7972outside `DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES`), trusted for
7973`DBBASIC_IDENTITY_CACHE_TTL_SECONDS` (30 s by default, never more than 60), or
7974until `POST /admin/identity/sources/forget` drops it. That TTL is the bound on
7975a role the upstream removed. A local row for the same id refuses them unless it
7976is linked to the source (`identity_source`, above). A linked row that is disabled,
7977or that names a local account that is disabled, refuses them on the next
7978request, and so does an account id the upstream names when that account has
7979a local row that is disabled; local roles do not cap or add to theirs. The
7980trusted-header path (`X-DBBASIC-User-Id`, `X-DBBASIC-Account-Id`) refuses the
7981same cases.
7982
7983Clients can inspect or revoke their own active session without the admin token:
7984
7985```http
7986GET /identity/session
7987DELETE /identity/session
7988Authorization: Token <session-token>
7989```
7990
7991Those routes require an active session token and do not treat the admin token as
7992a user session.
7993
7994The active subject can be inspected through:
7995
7996```http
7997GET /identity
7998Authorization: Token <token>
7999```
8000
8001Admin-token-gated operator routes still require `DBBASIC_ADMIN_TOKEN` by
8002default. A deployment can opt in to `DBBASIC_ENABLE_SESSION_ADMIN_GATES=true`;
8003when enabled, an active DBBASIC session whose subject has one of the policy
8004admin roles can pass the same gate. This is intended for Scroll/operator clients
8005that should stop carrying the raw deployment token after login exists.
8006
8007That endpoint returns the normalized `user_id`, `account_id`, roles,
8008subscriptions, auth method, and permission-mode flags the server will use for
8009route checks.
8010
8011Operators and Scroll can inspect permission rollout readiness through:
8012
8013```http
8014GET /permissions/status
8015Authorization: Token <admin-token>
8016```
8017
8018That endpoint summarizes the active mode flags, identity counts, persisted
8019policy shape, covered route groups, readiness, and warnings. Readiness is
8020advisory: it says what would hurt if enforcement were on now (or, when it is
8021on, what is hurting), and never switches enforcement on or off. It is meant
8022to be read before enabling enforcement on a live app. For identity-gated
8023modes, one of these non-admin identity paths should exist, or only the admin
8024token and public grants get in:
8025trusted proxy headers, guarded session login for existing users, password
8026login (`DBBASIC_ENABLE_PASSWORD_LOGIN=true`, counted before any user exists:
8027the first one arrives through `/setup`, signup or the admin token), an active
8028DBBASIC session, or a configured identity source (a valid
8029`DBBASIC_IDENTITY_VERIFY_URL`; see below). The startup check counts an identity
8030source as a sign-in path, so a deployment whose users sign in only through one
8031reports no problem. A verify source that is set but refused (not `https://` or
8032loopback `http://`, no secret for a remote host, no audience, or empty) does not count, and the server makes no network call at startup to
8033check that the verifier answers.
8034
8035## Access Modes
8036
8037Access modes answer who gets through the front door.
8038
8039- `public` - anyone can read or execute public objects.
8040- `password` - a shared gate authenticates before policy checks.
8041- `registered` - any signed-in user can read or execute.
8042- `subscription` - signed-in users with an active subscription can read or
8043 execute.
8044- `role_based` - rules decide by role, user, account, owner, row, field, and
8045 action.
8046- `private` - owner-only fallback unless explicit rules grant access.
8047
8048An access mode never opens a user object (`u_<id>_<name>`) to anyone but
8049its owner. `public`, `registered` and `subscription` allow read and execute
8050without a rule on system and package objects only; on a user object the
8051mode's grant reaches user `<id>` alone, and everybody else is decided as in
8052`role_based`: an admin role or an allow rule naming the `object_id` (see
8053[Sharing](#sharing)), otherwise `403` with
8054`""user object is not shared with this caller""`. A caller the mode itself
8055refuses (anonymous under `registered`, no subscription under
8056`subscription`) gets the mode's `401` / `402` as before.
8057
8058This matters where the gate is asked about a user object on someone else's
8059behalf: a site route or an override whose `object_id` is a user object.
8060(`/objects/{id}` already answers a non-owner `404` before the gate is
8061asked, in every mode.) Earlier releases ran such a route for any caller the
8062mode let in. To keep a route to a user object open to others, add a rule
8063naming the object:
8064
8065```json
8066{""effect"": ""allow"", ""principal"": ""public"", ""actions"": [""read"", ""execute""],
8067 ""object_id"": ""u_42_report""}
8068```
8069
8070Use `registered`, `role:<name>` or `user:<id>` as the principal to open it
8071to fewer callers.
8072
8073## Rules
8074
8075Rules answer what the subject can do once they are known.
8076
8077Actions should stay small and explicit:
8078
8079- `create`
8080- `read`
8081- `update`
8082- `delete`
8083- `execute`
8084- `source`
8085- `state`
8086- `logs`
8087- `files`
8088- `versions`
8089- `share`
8090- `admin`
8091
8092Principal strings are portable on purpose:
8093
8094- `public`
8095- `registered`
8096- `owner`
8097- `role:admin`
8098- `role:sales`
8099- `user:42`
8100- `account:customer-acme`
8101- `subscription:pro`
8102
8103One more principal is not a subject at all: `owner_fallback`, valid only on
8104a deny rule, switches the owner fallback off for the rule's actions and
8105resource. See [Ownership](#ownership).
8106
8107Explicit denies are checked before allow rules.
8108
8109A deny rule with a `row_filter` is about some rows, so it does not match the
8110collection-level question (a list, a search, a `/ws` subscribe, asked with
8111no record): the list is allowed and the deny hides exactly the rows its
8112filter names, per record. Before 2026-11-28 such a deny refused the whole
8113list with 403 for every principal except `owner`.
8114
8115## Pointing at a record you may not act on
8116
8117A rule decides who may write a row. It says nothing about the row that row
8118points at, and a row that points at something usually acts on it: a refund
8119takes money out of its payment, a payment marks its invoice paid, a line
8120changes its order's total, a stock move changes a product's level. Until
81212026-11-30 the shipped rules for all of those were ""registered users create
8122rows whose `owner_id` is their own"", so any signed-in user could refund any
8123customer's payment: the refund was theirs, the money was somebody else's.
8124
8125A relation states what its writer must be allowed to do to the target:
8126
8127```json
8128{""name"": ""payment_id"",
8129 ""relation"": {""collection"": ""payments"", ""display_field"": ""reference"", ""requires"": ""update""}}
8130```
8131
8132On a `POST` or `PUT` through the record API with enforcement on, the server
8133reads the target and asks the engine, for the same subject and policy,
8134whether it may `read` it and (for `""update""`) `update` it -- exactly the
8135question `PUT /collections/payments/records/{id}` would ask, owner fallback,
8136project grants and roles included. Admins pass, as they pass every rule.
8137
8138- Checked on create for every such field with a value, and on update for each
8139 one whose value changes.
8140- A target the writer may not read gets the same 400 a missing one gets
8141 (`references a missing record`), so the check is no oracle for ids. One
8142 they may read but not update gets a 403 naming the field.
8143- An unreadable target collection is a 503; nothing is written.
8144- `update` where the child moves money, stock or state of the parent (or a
8145 rollup on the parent sums it); `read` where it is a reference (the contact
8146 an invoice is for, the project a note is filed under, a public category).
8147 A project member with a read grant can therefore still file a note under
8148 the project: the engine has no ""write member"" action on a project row to
8149 ask for.
8150- Trusted server-side writers (actions, webhooks, the daemon) write through
8151 `object_records` and never reach it. An action that writes a child of a
8152 record it was handed asks `object_access` about that record itself (below).
8153
8154`tests/test_relation_requires_guard.py` fails when a shipped collection that a
8155non-admin principal may create or update has a relation with no `requires`
8156and no stated reason (its `EXEMPT`) for going without, and when a writable
8157child that a parent rolls up requires less than `update` on it.
8158`tests/test_relation_requires_collections.py` probes every declared pointer
8159over HTTP as a registered user who owns nothing involved.
8160
8161## Objects That Read Storage Directly
8162
8163A page or action that reads records with `object_records` gets the raw row:
8164the collection API's rules, row filters and owner checks do not run. Such an
8165object is the only gate in front of what it shows or changes, so it asks the
8166same engine with `object_access`:
8167
8168```python
8169access = object_access.Access(request.get(""_identity""), base_dir=base)
8170order = access.get(""orders"", order_id) # None when missing OR refused
8171if order is None:
8172 return not_found() # one answer for both: no oracle
8173if not access.can(""update"", ""disputes"", dispute):
8174 return {""status"": 404, ...}
8175rows = access.visible(""wallet_entries"", rows) # the rows the API would list
8176```
8177
8178It answers what the API would for the same subject under the active policy,
8179with two differences, both towards refusing: a request with no `_identity`
8180is anonymous (an in-process caller that wants authority passes one
8181explicitly); and an unreadable policy refuses everybody. Project and
8182record-share grants are resolved by the server's own code
8183(`object_access.with_grants`), so a rule that matches through
8184`$accessible_projects` or `$shared_records` matches for a project member
8185or a sharee exactly as it does over the API. Field redaction is not
8186applied: the object renders the fields it chooses.
8187
8188One difference goes the other way, and it matters for `update` and
8189`delete`: the record API first asks the collection-level question with no
8190record, and `can()` with a record does not. So where a collection has no
8191rule for the action, the API refuses and `can()` answers with the owner
8192fallback: yes, for the row's owner. A collection that must be
8193read-only to its owners says so with an `owner_fallback` rule
8194([Ownership](#ownership)); do not infer it from the absence of a grant.
8195
8196### The guard test: forgetting is a CI failure
8197
8198Most access bugs found in November 2026 were an object that read or changed
8199someone's record through `object_records` and never asked. The platform
8200remembers the other rules for people; this one it checks.
8201`tests/test_object_access_guard.py` parses (with `ast`, not grep) every
8202`packages/*/objects/site/*.py` and `packages/*/objects/action/*.py` and
8203fails on any reference to a public `object_records` reader or writer
8204(`read_collection_records`, `get_collection_record`, `create_`/`update_`/
8205`delete_collection_record`, `read_collection_records_where` and the rest of
8206the lists in the test) unless one of these holds:
8207
82081. **The file asks `object_access` about that collection.** An `Access`
8209 object's `.get(collection, id)`, `.can(action, collection, record)`,
8210 `.visible(collection, rows)` or `.reads_every_row(collection)` appears in
8211 the same file, with the same collection (a literal, a module constant, or
8212 the same variable expression). Asking about `orders` does not cover
8213 `order_lines`: each collection needs its own question or its own
8214 exemption. The test checks that the file asks, not that the answer is
8215 used; reading the diff for that is still a person's job.
82162. **The call carries an exemption comment** on its own line or on a comment
8217 line directly above it:
8218
8219 ```python
8220 # access: box configuration
8221 rows = object_records.read_collection_records(""app_settings"", base_dir=base)
8222 ```
8223
8224 The reason is a sentence a reviewer can check against the code around it
8225 (""box configuration"", ""system write after the access check above"",
8226 ""capability link: the invoice is found by its secret portal_token"",
8227 ""public catalog"", ""the caller's own row: owner_id is the caller's
8228 user_id""). Two reasons are checked against the rules files: `admin-only
8229 object (...)` needs every `execute` grant for the object to be
8230 `role:admin` (none at all also counts), and `role-only object (...)`
8231 needs at least one grant, all of them `role:*`. `public ...` needs a
8232 rule letting `public` read the collection, and covers reads only.
8233
8234A hand-written `owner_id == user_id` test is not an exemption for the
8235reason in [Objects That Read Storage Directly](#objects-that-read-storage-directly):
8236the ones that let a row with a blank owner through disagreed with the API
8237for admins, roles and unowned rows, and were the bugs. Where the filter is
8238strictly tighter than the engine (the caller's own rows and nothing else)
8239say so in the comment; where it can pass a row the engine would refuse, use
8240`object_access`.
8241
8242New public functions in `object_records` must be classified in the test
8243(reads rows, writes rows, or neither), so the list the guard enforces
8244cannot go stale. Objects under `objects/system`, `hook` and `webhook`, and
8245helper modules at the repository root, are not scanned.
8246
8247## Package Rules And Upgrades
8248
8249An installed package's rules sit in the same policy file as the operator's,
8250each stamped `""package"": ""<id>""` when the install appended it. Installing a
8251package again (an upgrade) does two things to that file, in this order:
8252
82531. **Retires the rules the package has withdrawn.** A live rule is removed
8254 only when BOTH hold: it is tagged as this package's, and it is identical
8255 (everything but `reason`) to a rule the package is known to have shipped
8256 and no longer ships. ""Known"" is the rules recorded at the package's last
8257 install (`permissions` in `data/package_baselines/<id>.json`), or the
8258 `retracted` list in the package's permissions file
8259 ([`package-authoring.md`](/docs/package-authoring)).
82602. **Appends the rules it ships that are not in the policy.**
8261
8262Until 2026-11-28 only step 2 existed, so a package that deleted a grant or
8263added a row filter to one (a different rule) fixed new installs only: an
8264existing box kept the old, wider rule, and an allow rule that is still in
8265the policy still allows.
8266
8267What an upgrade will not do is remove something it cannot prove the package
8268put there:
8269
8270- a rule with no `package` tag is the operator's, even when it is identical
8271 to one a package withdrew (reported as `operator_rule`: it is now the
8272 only thing keeping that grant alive);
8273- a rule the operator edited keeps its tag but no longer matches what was
8274 shipped, so it stays (reported as `unaccounted`). To keep such a rule and
8275 stop it being reported, delete its `package` field; to drop it, delete the
8276 rule;
8277- a rule another installed package still ships changes hands
8278 (`reassign`) instead of being removed.
8279
8280A box installed before the baseline recorded rules has no record of what it
8281was given. On it, only the rules a package explicitly `retracted` are
8282removed; any other tagged rule the package does not ship is `unaccounted`
8283until its first upgrade has recorded a baseline.
8284
8285Where to look:
8286
8287- the dry run (`GET /packages/{id}?dry_run=true`) and the install response
8288 carry `permission_retractions`: one entry per rule with `action`
8289 (`remove`, `reassign`, `keep`), `because`, `why` and the whole `rule`;
8290- `GET /packages/{id}/changes` keeps every removed or reassigned rule
8291 whole, so a grant an upgrade took away can be read back and, if it was
8292 wanted, put back by hand without a package tag;
8293- the restore point taken before the install includes the policy file;
8294- at any time, the rules in the policy that no installed package ships:
8295
8296```http
8297GET /permissions/unshipped
8298Authorization: Token <admin-token>
8299```
8300
8301```json
8302{
8303 ""status"": ""ok"",
8304 ""rules"": [
8305 {""index"": 41, ""state"": ""retracted"", ""package"": ""app-notes"",
8306 ""rule"": {""effect"": ""allow"", ""principal"": ""public"", ""actions"": [""execute""],
8307 ""object_id"": ""site_notes"", ""package"": ""app-notes"", ""..."": ""...""}}
8308 ],
8309 ""count"": 1,
8310 ""policy_rules"": 212,
8311 ""installed_packages"": [""app-notes"", ""app-tasks""],
8312 ""wide_rules"": [],
8313 ""warnings"": []
8314}
8315```
8316
8317`state` is `operator` (no package tag), `retracted` (the package's next
8318install will remove it), `unaccounted` (tagged for an installed package
8319that neither ships nor retracts it) or `package_missing` (tagged for a
8320package that is not installed or whose files are not on this box). A listed
8321rule that is wide (see ""A wide rule left over from an older starter policy"")
8322also has a `wide` string, and `wide_rules` lists every wide rule in the whole
8323policy as `{index, package, why, rule}`. The report is read-only.
8324
8325**Upgrading a box that predates this:** reinstall each installed package
8326(`POST /packages/{id}/install` with `{""allow_replace"": true}`; take one
8327`POST /admin/backups` first and add `""restore_point"": ""<backup id>""` to each
8328install so the run does not write a full archive per package), read
8329`permission_retractions` in each response, then read
8330`GET /permissions/unshipped` once and decide about whatever is left.
8331
8332## What Runs Outside The Policy
8333
8334The policy decides what a *request* may do. The daemon and the scheduler are
8335not requests. They run as the system, with no user behind them, so the policy
8336is never consulted for what they do:
8337
8338- The daemon (`object_daemon.py`) imports no permission code. Its passes
8339 (scheduler, queue, rollups, auto-transitions, notifications, mail sync,
8340 scheduled backups and the rest) read and write through `object_records`
8341 with a fixed system actor such as `daemon:scheduler`, which never asks
8342 `object_permissions` for a decision.
8343- A scheduled object method runs through `execute_object` with an empty
8344 payload and no identity: it runs as itself, not as whoever scheduled it and
8345 not as the admin. `execute_object` makes no policy decision either; the
8346 policy is only applied by the HTTP routes in front of it.
8347
8348Why: there is nobody to ask. A nightly backup or a queue drain has no session,
8349and a rule written for ""registered users"" or ""owners"" has no meaning for it.
8350Making these jobs depend on the policy would also let a broken or restrictive
8351policy stop backups and queues.
8352
8353What an admin should take from this:
8354
8355- A deny-all policy does not stop scheduled work. Rules cannot be used to
8356 switch off a scheduled job; remove the task instead (the scheduler task
8357 endpoints under `/daemon/scheduler/tasks` need the admin token).
8358- Whoever can install an object that schedules itself, or create a scheduler
8359 task, is in effect granting that code system-level access to records. Treat
8360 that as an admin decision.
8361- User-namespace objects (`u_<uid>_*`) are the exception to ""unrestricted"":
8362 when scheduled they still run in the sandboxed worker described at the top
8363 of this page, so they reach only their own state, logs and files. The
8364 sandbox is the boundary there, not the policy.
8365- Decisions made by these jobs are not in the permission audit log, because no
8366 decision is made. Look at the daemon log, `scheduler_runs` and the activity
8367 log instead.
8368
8369## Ownership
8370
8371The old object convention still matters:
8372
8373```text
8374u_42_report
8375```
8376
8377That object belongs to user `42`. Owners can read, execute, update, inspect,
8378share, and delete their own user objects unless a future stricter policy blocks
8379that behavior.
8380
8381Records can also carry ownership fields:
8382
8383```json
8384{
8385 ""owner_id"": ""42"",
8386 ""customer_account_id"": ""customer-acme""
8387}
8388```
8389
8390The server can use `owner_id`, `user_id`, or `created_by` as owner fields for the
8391basic fallback. Application objects can add richer policy around account,
8392department, project, team, or customer ownership.
8393
8394### The fallback applies after your rules, not instead of them
8395
8396The owner fallback is the last step of the decision: when no allow rule
8397matches, whoever one of those three fields names may still `read`, `update`
8398and `delete` the record (and `execute`, `source`, `state`, `logs`, `files`,
8399`versions`, `share`). **Leaving an action out of a collection's rules
8400therefore does not refuse it to the row's owner.** A collection whose only
8401rule is ""the owner may read their own rows"" is, as far as the engine is
8402concerned, also updatable and deletable by that owner.
8403
8404Where that answer reaches:
8405
8406- `object_access` (pages, actions, hooks): always. `Access.can(""update"",
8407 collection, record)` is true for the owner.
8408- The record API (`PUT` / `DELETE /collections/{c}/records/{id}`): only when
8409 the subject first passes the collection-level question the API asks
8410 before it looks the record up, which has no record and so no fallback.
8411 With no update or delete rule on the collection that question is a 403,
8412 which is why a stock install refuses the owner. It stops refusing as
8413 soon as ANY allow rule for that action matches the subject at the
8414 collection level, row filter or not: a rule ""support may update runs
8415 that need review"" lets a support user update their own settled runs,
8416 through the fallback. Do not rely on the first question as access
8417 control; it exists so a missing id cannot be told from a forbidden one.
8418- Files (`/api/files/{id}`, the WebDAV folder, and a file attached to an
8419 AI chat turn, `POST /api/ai/chat` with `attachments`): the same as the
8420 record API. With no `files` rule for the action, the owner is refused
8421 there too. An attachment is a `read`; a refused one fails the turn with
8422 a 400 before anything is sent to the provider, and a file refused on
8423 its record reads like a missing one. Attachments are owner-only on top
8424 of that, whatever the policy says. In audit mode the attachment is sent
8425 as before, and both questions are recorded in the permission audit log
8426 (`enforced: false`), a would-be refusal included.
8427- ""Owner"" is whoever those fields name. A grant row that names its grantee
8428 in `user_id` makes the grantee its owner.
8429
8430### Switching the fallback off for a collection
8431
8432A package (or an operator) that means ""only what the rules say"" ships a
8433rule that says so:
8434
8435```json
8436{
8437 ""effect"": ""deny"",
8438 ""principal"": ""owner_fallback"",
8439 ""actions"": [""update"", ""delete""],
8440 ""collection"": ""template_runs"",
8441 ""reason"": ""a run is read-only to the person it belongs to""
8442}
8443```
8444
8445It is consulted in one place: after the allow rules have found nothing, and
8446only when the fallback would otherwise have allowed. So:
8447
8448- an explicit allow rule for the same action still grants. This is the
8449 difference from an ordinary `deny`, which is checked first and beats
8450 every allow. ""Owners may edit their own drafts"" beside an opt-out for
8451 `update` lets drafts be edited and nothing else;
8452- admins are decided before any rule, and in-process writers
8453 (`object_records`, the daemon, an action's own writes) never ask;
8454- the refusal is a 403 carrying the rule's `reason`;
8455- `actions` may be `[""*""]`; a rule naming neither a collection nor an
8456 object switches the fallback off for the whole policy; a `row_filter`
8457 limits it to the rows it names; `valid_from` / `expires_at` work as on
8458 any rule;
8459- naming an `object_id` covers the `u_<id>_...` convention above, except in
8460 `private` access mode, where object ownership is the access mode itself.
8461
8462`owner_fallback` on an allow rule does not parse: it would grant nothing
8463while reading as if it did.
8464
8465The packages that ship one, and the collections whose packages are silent
8466about whether the owner may update or delete, are both listed in
8467`tests/test_owner_fallback_opt_out.py` (`OPTED_OUT`, `UNDECIDED`), which
8468fails when a new collection or a narrowed grant leaves an owner's update
8469or delete resting on the fallback alone.
8470
8471### Who owns a record you create
8472
8473On `POST /collections/<name>/records`, for a collection whose schema declares
8474an `owner_id` field and a caller signed in as a person (a session or one of
8475their API keys):
8476
8477| `owner_id` sent | What happens |
8478|---|---|
8479| left out, or blank | The caller owns the row: the server fills in their id **before** the permission check, so a rule filtered on `{""owner_id"": ""$user_id""}` judges the row they will actually own. The returned record shows it. |
8480| the caller's own id | Kept. |
8481| somebody else's id | Kept exactly as sent, and refused with `403 {""code"": ""forbidden"", ""field"": ""owner_id""}` unless the caller holds an admin role or an allow rule with `""on_behalf"": true` covers this create. Nothing is written. |
8482
8483The server never rewrites an `owner_id` the client sent. It used to: a
8484treasurer recording a donation for a donor got `201` and a row the server had
8485quietly made the treasurer's own, so the donor never saw it.
8486
8487`on_behalf` is the grant for staff entering records for members, donors or
8488patients:
8489
8490```json
8491{""effect"": ""allow"", ""principal"": ""role:treasurer"", ""actions"": [""create"", ""read""],
8492 ""collection"": ""donations"", ""on_behalf"": true,
8493 ""reason"": ""the treasurer enters donations for donors""}
8494```
8495
8496It is deliberately narrow, and a rule outside this shape makes the policy
8497invalid rather than granting nothing: an allow, naming a collection, covering
8498`create`, for a `role:<name>` or `user:<id>` principal. `registered`, `public`,
8499`owner`, `account:` and `subscription:` are refused, because a row owned by
8500someone else is theirs to read, change and delete (the owner fallback above),
8501and ""any signed-in user may plant rows in anyone's account"" is the forgery
8502this check exists to stop. The rule's `row_filter` still has to match the
8503record as sent (an on-behalf grant limited to `{""fund"": ""general""}` does not
8504cover other funds), and an explicit deny still wins. A create grant without
8505`on_behalf` -- even one with no row filter -- lets its principal create rows
8506they own, and only those.
8507
8508The admin token is not a person: seeding, migration and scripts that send an
8509`owner_id` keep it. Only `owner_id` is handled this way; `user_id` and
8510`created_by` are written as sent and judged by the rules like any other field.
8511`tests/test_create_owner_id.py` walks each case through HTTP.
8512
8513### Changing who owns a record
8514
8515On `PUT /collections/<name>/records/<id>` under enforcement, an `owner_id`
8516that differs from the stored one is a change of owner, and it needs exactly
8517what creating the row with that `owner_id` needs: an admin role, or an allow
8518rule with `""on_behalf"": true` covering `create` on the collection whose row
8519filter matches the record as it would be. Anything else is
8520`403 {""code"": ""forbidden"", ""field"": ""owner_id""}` and nothing is written.
8521
8522- An `owner_id` sent unchanged is no change: clients that PUT back the whole
8523 record they read are not refused.
8524- Taking a row for yourself, or clearing its owner, is a change of owner too
8525 (the old owner loses it) and is asked the same way.
8526- An owner's own row-filtered grant (`owner_id: $user_id`) already refused
8527 giving a row away, because the rule is judged on the record as it would
8528 be. This closes the other door: a role with an unconditional update grant
8529 (a billing manager on invoices, a manager on expenses and time logs, an
8530 assignee on a task) could hand any row to any user.
8531- The admin token and in-process writers (actions, the daemon) are not
8532 asked; an action that moves records between owners decides that itself.
8533
8534## Sharing
8535
8536Sharing is just a rule:
8537
8538```python
8539PermissionRule.allow(
8540 ""user:99"",
8541 [""read"", ""update""],
8542 object_id=""u_42_shared_report"",
8543 reason=""shared by owner"",
8544)
8545```
8546
8547A user object is shared only this way, by `object_id`. An object is
8548checked under the collection its name starts with (`tools_export` under
8549`tools`), but a user object `u_<id>_<name>` is in no collection's scope:
8550an allow rule that names a collection never grants on it, whatever the
8551owner called it (`u_42_tools_export` is not opened by a grant on `tools`).
8552Deny rules that name the collection still apply to it, as they always did.
8553The access mode does not share it either: see
8554[Access Modes](#access-modes).
8555
8556Account sharing uses the same shape:
8557
8558```python
8559PermissionRule.allow(
8560 ""account:customer-acme"",
8561 [""read""],
8562 collection=""invoices"",
8563 row_filter={""customer_account_id"": ""$account_id""},
8564)
8565```
8566
8567That covers the common case where a customer has multiple employees and they all
8568need access to the customer portal, invoices, files, or support tickets.
8569
8570Project sharing — ""records I own OR records in a project shared with me"" —
8571uses grant records plus one filter value. Grants are rows in the plain
8572`project_access` collection (`project_id`, `user_id`), so sharing is data:
8573browseable, audited, versioned. Before checks run, the server resolves the
8574subject's grants; rules opt in with `$accessible_projects`, which matches
8575when the record's field value is any granted project id:
8576
8577```python
8578PermissionRule.allow(
8579 ""registered"",
8580 [""read""],
8581 collection=""notes"",
8582 row_filter={""project_id"": ""$accessible_projects""},
8583 reason=""notes in shared projects are readable"",
8584)
8585```
8586
8587Pair it with an owner rule on the same collection: matching stays
8588first-rule-wins at the collection level, but list, single-record, and
8589search reads evaluate rules per record, so ""own"" and ""shared"" rules
8590combine naturally. The engine itself stays pure — grant resolution is IO
8591the server does once per request, and the subject carries the result.
8592
8593Granting is self-serve through the companion value `$owned_projects`,
8594which resolves to the projects whose `owner_id` is the subject. ""Only a
8595project's owner may share it"" — a cross-record condition — becomes a
8596plain row filter on the grant collection itself:
8597
8598```python
8599PermissionRule.allow(
8600 ""registered"",
8601 [""create"", ""read"", ""delete""],
8602 collection=""project_access"",
8603 row_filter={""project_id"": ""$owned_projects""},
8604 reason=""project owners share and revoke access to their own projects"",
8605)
8606```
8607
8608Creating a grant is creating a record; revoking is deleting it; both are
8609audited and appear in the change history like every other write.
8610
8611Grants carry a `permission` of `read` or `write`. Most rules only need
8612membership (`$accessible_projects`), but some need to tell read grants
8613apart from write grants — ""only project writers may publish"" — and that
8614narrower set is `$writable_projects`, resolved from the same
8615`project_access` rows filtered to `permission == ""write""`:
8616
8617```python
8618PermissionRule.allow(
8619 ""registered"",
8620 [""update""],
8621 collection=""docs"",
8622 row_filter={""project_id"": ""$writable_projects""},
8623 reason=""only writers may edit docs in a shared project"",
8624)
8625```
8626
8627It resolves the same way and is available everywhere
8628`$accessible_projects` and `$owned_projects` are: row filters and, for
8629schema-declared lifecycle fields, transition guards (see the
8630`transitions` field key in `docs/schema-forms.md`).
8631
8632## Row And Field Rules
8633
8634Row filters model rules like:
8635
8636```text
8637sales reps only see their own leads
8638```
8639
8640As data:
8641
8642```python
8643PermissionRule.allow(
8644 ""role:sales"",
8645 [""read""],
8646 collection=""contacts"",
8647 row_filter={""owner_id"": ""$user_id""},
8648)
8649```
8650
8651A row filter never matches a field the record does not have. A collection's
8652file only gains a column once some record is written with it, so ""the record
8653has no `owner_id` at all"" is an ordinary state, not a corrupt one, and it is
8654treated exactly like the column being present and empty:
8655
8656| the filter value | field missing or null | field present, empty | field has a value |
8657|---|---|---|---|
8658| `$user_id` / `$account_id`, resolved | no match | no match | match when equal |
8659| `$user_id` / `$account_id`, unresolved (anonymous visitor, user with no account) | no match | no match | no match |
8660| `$accessible_projects` and the other set-valued variables | no match | no match | match when a member |
8661| a literal value | no match | match only for the literal `""""` | match when equal |
8662| a literal `null` | no match | no match | no match |
8663
8664This is the same answer for an allow rule and for a deny rule: there is one
8665comparison, and the effect only decides what a match means. So the account
8666example above stays correct if it is generalised from
8667`account:customer-acme` to `registered` (""every customer sees their own
8668invoices""): a signed-in user with no account matches no invoice, including
8669in a collection where no invoice has a `customer_account_id` yet. Before
8670this was pinned (tests/test_permission_missing_column.py) an unresolved
8671variable compared equal to a missing field and such a rule matched every
8672row until the column was first written.
8673
8674(The set-valued row assumes what the server guarantees: it drops grant rows
8675with an empty id before building those sets, so `""""` is never a member.)
8676
8677The table is about equality and membership. The `ne` operator is not part
8678of it and is unchanged: `{""op"": ""ne"", ""value"": X}` is plain inequality with
8679a missing field read as null, so a missing field matches `ne` for any real
8680`X` and does not match it when `X` is unresolved or null -- while an empty
8681field does match `ne` against an unresolved `X`. A rule that depends on
8682that corner should say what it means with a second clause.
8683
8684The ordered operators (`gte`, `lte`, `gt`, `lt`) compare numbers as numbers
8685and ISO dates and datetimes as instants in UTC: a trailing `Z` or an offset
8686says the zone, a value with no offset is UTC, and a date alone is UTC
8687midnight. So `{""created_at"": {""op"": ""lt"", ""value"": ""2026-01-01""}}` compares
8688with the `created_at` the server stamps (`...Z`). Before 2026-12-03 a date
8689alone was read with no zone, comparing it with a stamped datetime failed,
8690and the failure was read as ""no match"": such a deny refused nothing and
8691such an allow granted nothing.
8692
8693An ordered condition can also be impossible to judge: the record has no
8694such field, the bound is a `$`-variable with no value (or a set), or the
8695bound is a number or a date and the stored value is blank or text. That is
8696the one place the effect changes the answer:
8697
8698| rule | cannot judge |
8699|---|---|
8700| allow (and attention counts, list filters) | no match: grants nothing |
8701| deny (and the `owner_fallback` opt-out) | the deny holds: refused |
8702
8703A deny's other conditions still decide, since a filter's conditions are
8704ANDed: a deny that names a status or an owner still spares a row with
8705another one. A deny that should spare blank rows says so beside its bound:
8706`{""approved_at"": [{""op"": ""lt"", ""value"": ""2026-01-01""}, {""op"": ""ne"", ""value"": """"}]}`.
8707A bound that is plain text (neither a number nor a date) is compared as
8708text and can always be judged.
8709
8710Field rules model cases like hiding salary, internal notes, cost, or private
8711metadata:
8712
8713```python
8714PermissionRule.allow(
8715 ""account:customer-acme"",
8716 [""read""],
8717 collection=""invoices"",
8718 fields=[""invoice_id"", ""status"", ""total""],
8719 denied_fields=[""internal_notes""],
8720)
8721```
8722
8723Schema field permissions add the generated-form version of the same idea. They
8724live next to field metadata so Scroll can render the right controls and the
8725server can enforce the same decision:
8726
8727```json
8728{
8729 ""name"": ""margin"",
8730 ""type"": ""currency"",
8731 ""permissions"": {
8732 ""admin"": ""edit"",
8733 ""sales"": ""hidden"",
8734 ""viewer"": ""hidden""
8735 }
8736}
8737```
8738
8739The access levels are:
8740
8741- `edit` - visible and writable
8742- `read` - visible but not writable
8743- `hidden` - removed from reads and not writable
8744
8745Principal keys can be role names such as `sales`, or full principals such as
8746`role:sales`, `user:42`, `account:customer-acme`, `subscription:pro`,
8747`registered`, `public`, or `owner`. Grouped access lists are also accepted:
8748
8749```json
8750{
8751 ""name"": ""notes"",
8752 ""permissions"": {
8753 ""edit"": [""owner"", ""role:admin""],
8754 ""read"": [""role:support""],
8755 ""default"": ""hidden""
8756 }
8757}
8758```
8759
8760When multiple principals match one subject, the most restrictive field access
8761wins. Schema field permissions only refine fields after the broader policy has
8762already allowed access to the row.
8763
8764### Field permissions on writes: what is checked, and the known limits
8765
8766**Known limits, pending the owner's rule-combining design.** This is what the
8767engine does today, pinned by `tests/test_field_permission_semantics.py`; do
8768not build on the corners below as if they were promises, and expect them to
8769change together with that design.
8770
8771- **Only the keys a write submits are checked.** A `PUT` that sends `title`
8772 is not stopped by a field it did not send, however restricted that field
8773 is. A key that is sent is checked even when its value is unchanged or
8774 blank (`{""secret"": """"}` is refused where the field is `read`).
8775- **Create is checked too**, against the keys of the new record, with
8776 `owner` evaluated on the record being created. The refusal is `403` with
8777 `""code"": ""forbidden""` and `""denied_fields"": [...]`; nothing is written.
8778- **The most restrictive access across ALL of a subject's matching
8779 principals wins, in either direction.** A field set `{""owner"": ""edit"",
8780 ""role:auditor"": ""read""}` is read-only for a person who is both the row's
8781 owner and an auditor: holding the extra role takes edit rights away. There
8782 is no ""most specific wins"" and no way to say ""owner overrides role"". Give
8783 a person who must edit their own rows a role set that does not also appear
8784 in the field's restricted list, or restrict by `default` and list who may
8785 edit.
8786- **An allow rule's `fields` and `denied_fields` apply to reads only.** They
8787 remove keys from what a read returns (and from what can be filtered on);
8788 they do not stop a write that sends those keys. The answer to a create,
8789 update or delete is the row as the writer's own `GET` shows it, so it
8790 leaves those keys out too (docs/http-api-contract.md, ""Write answers"").
8791 To stop writes to a field, use the field's schema `permissions`.
8792- **Transition guards cannot reference roles.** A guarded move's `when` is
8793 the row-filter language over the record's current values with the closed
8794 set of subject variables (`$user_id`, `$account_id`, and the project and
8795 shared-record sets). Each `when` value is a single string, a literal or
8796 one of those variables, compared for equality: no `ne`, `in` or other
8797 operators, so a guard cannot say ""not your own row"". To let only a role
8798 make a move, put the move behind a field permission on the field it
8799 changes, or a pre-write hook that gets the caller.
8800
8801### Notifications, activity feeds and history lines
8802
8803With enforcement on (`DBBASIC_ENABLE_PERMISSION_ENFORCEMENT`, the mode
8804`/permissions/status` calls ""enforced""; the daemon reads the same setting
8805through `object_access.enforcement_enabled`), anything shown to a user that
8806is built from a change to a record follows the same read decision as the
8807record, for that user, on that row, at the moment it is built. With
8808enforcement off or audit-only the record API serves that user every row and
8809field, so notifications and history lines are delivered whole, exactly as
8810before; if the mode cannot be determined, notifications are not delivered. Fields a rule's `fields` / `denied_fields` or the
8811schema's field `permissions` hide from them are left out, and a change that
8812touched only such fields produces nothing for them.
8813
8814- **Notify rules** (`app-notify`, in-app and email), with enforcement on. A recipient gets a
8815 notification only if they are an active user who may read the row; its
8816 text is rendered from the row as that user may read it, so a template's
8817 `{salary_band}` renders empty for someone who cannot read it. A rule whose
8818 `match` names a field the recipient cannot read does not fire for them
8819 (firing would tell them the value). An update none of whose changed fields
8820 they can read notifies them of nothing. An unknown recipient id, an
8821 inactive user, or an unreadable policy delivers nothing. The check is made
8822 when the daemon processes the change, not when the rule is written.
8823- **Declared attention counts** (a package's `attention` entry with
8824 `collection` + `where`, shown on the home page and the menu), with
8825 enforcement on. The count, and the sums, ages and sub-counts of its
8826 detail sentence, are computed from each row as the viewer may read it. A
8827 row they may not read is not counted. A `where` condition on a field they
8828 cannot read is false for that row, so the count means ""rows where this
8829 field, which you can see, matches"" and is `0` for someone who cannot read
8830 the field at all. A sum or age adds nothing from a row whose field is
8831 hidden, and a detail part that depends on a field hidden in every counted
8832 row is left out of the sentence, zero or not. With enforcement off the
8833 counts are row-level, as before; if the mode cannot be determined nothing
8834 is counted. Counts are computed on each page view, so there is no stored
8835 number to go stale. A code provider's number (`object_id`) is not
8836 per-viewer: it is shown only to a viewer who reads every row of each
8837 collection in its `reads`, and, with enforcement on, from whom no schema
8838 field permission of those collections could hide a field
8839 ([package-authoring.md](/docs/package-authoring#who-sees-a-providers-number)).
8840- **`GET /api/activity`** (a user's own recent changes): with enforcement on,
8841 an entry's title comes from the fields the caller may read; a row they may
8842 not read is titled by its id.
8843- **`action_counter_history`**: before/after snapshots and `changed_fields`
8844 carry only the fields the caller may read.
8845- **Realtime (`/ws`)** sends only collection, id and action, after a read
8846 check on the row. It does not look at which fields changed: a reader of a
8847 row is told the row changed even when only a field they cannot read did,
8848 exactly as the row's `rev` tells them on the next read. That the row
8849 changed is treated as visible to anyone who can read the row; which field,
8850 and to what, never is.
8851- **Admin routes** (`/collections/{c}/changes`, `/admin/changes`, the event
8852 log, subscriptions) are admin-token only and show everything, including
8853 `changed_fields`.
8854
8855Known limits: a notification already stored in `notifications` was rendered
8856for its recipient when it was written; if their access to the row or field
8857is narrowed afterwards, the stored text stays as it was. Nothing re-renders
8858or purges stored notifications on a permission change.
8859
8860### Comment moderation
8861
8862Both comment collections are moderated by one role, `moderator`, and
8863nobody else: app-thread's `thread_comments` (statuses `published`,
8864`pending`, `flagged`, `removed`) and app-worker's guestbook
8865`profile_comments` (`pending`, `approved`, `rejected`). The admin token is
8866not a moderator. It is built from the pieces above, and the limits above
8867are why it has the shape it has:
8868
8869- **A rule lets a moderator reach every comment.** Each package ships
8870 `role:moderator` `read` (pending, flagged, removed and rejected rows
8871 included: the pending ones are the queue) and `update`, with no row
8872 filter. No `delete`: a moderated comment is removed or rejected by its
8873 status, not erased.
8874- **Field permissions make `status` the only thing that update can
8875 change.** An allow rule's `fields` do not restrict writes, so the other
8876 client-writable fields (the text, the author's name and URL, the thread
8877 or profile a comment hangs off, the reply target, `owner_id` on the
8878 guestbook) say `{""owner"": ""edit"", ""role:admin"": ""edit"",
8879 ""role:superuser"": ""edit"", ""default"": ""read""}`: the comment's author and
8880 admins edit them, everyone else (moderators included) reads them. A
8881 moderator's `PUT` that sends any of them is `403` with `denied_fields`,
8882 and nothing is written, status included. A change of owner is refused
8883 before that anyway (""Changing who owns a record""). Server-owned fields
8884 (`created_at`, `edited_at`) were never writable by a client.
8885- **`status` says `{""owner"": ""read"", ""role:moderator"": ""edit"", ""default"":
8886 ""hidden""}`.** The author reads their own comment's status and cannot set
8887 it; a moderator edits it on other people's comments; on a moderator's own
8888 comment both entries match and the more restrictive, `read`, wins, so
8889 **nobody approves their own comment**. Everyone else (other users,
8890 visitors, the admin token) does not see the field at all; the read rules
8891 give them only published or approved rows.
8892- **The moves are the schema's `transitions` map**, unguarded:
8893 `thread_comments` pending to published (approve), flagged or removed
8894 (reject); published to flagged or removed; flagged to published or
8895 removed; removed is final. `profile_comments` pending to approved or
8896 rejected; approved to rejected (un-approving); rejected is final. Nothing
8897 moves back to pending. Any other move is `400`.
8898- **Moderators have a queue on the home page**: the declared attention
8899 counts `thread_comments_to_moderate` and `profile_comments_to_moderate`
8900 count other people's pending comments the viewer may read, so they are
8901 zero for everyone who is not a moderator (or an admin, who reads every
8902 row). Each count opens a seeded page listing the pending comments
8903 oldest first, `/comments/pending` and `/guestbook/pending` (app-views
8904 list views; site routes must be on, `DBBASIC_ENABLE_SITE_ROUTES=true`).
8905 The page lists, it does not decide: a decision is a `PUT` of `status`
8906 over the record API. It also lists the moderator's own pending comments,
8907 which the count leaves out (a list's `where` cannot say ""not mine""); to
8908 anyone who may not filter on `status` (authors, other users, visitors)
8909 it says ""Not available"". The same queue over the API is
8910 `GET /collections/<collection>/records?status=pending`.
8911
8912What changes for whom, against app-thread 0.1.1 and app-worker 0.1.2:
8913
8914| Caller | Before | After |
8915|---|---|---|
8916| the author | reads their comment and its status in any state; edits its text; cannot set status | the same |
8917| a moderator, someone else's comment | thread: reads it, status included, cannot update it. Guestbook: approved rows only (with their status), cannot update | reads it in any state with its status; moves status along the map; cannot change any other field or delete it |
8918| a moderator, their own comment | reads it, edits its text, cannot set status | the same |
8919| another signed-in user | thread: published rows; guestbook: approved rows; no status, cannot update | the same |
8920| a visitor | thread: nothing; guestbook: approved rows, no status | the same |
8921| the admin token | reads every row, status hidden; edits the text; cannot set status | the same |
8922| anyone else an operator's own rule lets update other people's comments (a role other than `moderator`, `admin`, `superuser`; also a custom name in the policy's `admin_roles`) | could change any field | can change none of the fields above (they are `read` for it) |
8923
8924On upgrade, reinstall both packages (`POST /packages/app-thread/install`
8925and `/packages/app-worker/install` with `{""allow_replace"": true}`): the
8926moderator rules are added and nothing is retracted. Then give the role to
8927whoever moderates, `PUT /identity/users/{user_id}/roles` with
8928`{""roles"": [..., ""moderator""]}` (it takes effect on their next request).
8929The guestbook's commenters' rule keeps its old `reason` text on an upgraded
8930box, because an upgrade matches rules on everything but `reason`; edit it
8931in the policy if the stale wording bothers you.
8932
8933**An AI agent that moderates is a user with the moderator role and an API
8934key, not the admin token.** Create a user for it (`POST /identity/users`
8935with `""roles"": [""moderator""]`), mint it a key (`POST
8936/identity/users/{user_id}/api-keys`), and give the agent that key. It then
8937works the queue exactly as a person would (`GET ...?status=pending`, `PUT
8938{""status"": ""approved""}`), can do nothing else a moderator cannot, is recorded
8939under its own user id in the change history, and is switched off by revoking the key
8940or the role. The admin token would be the wrong credential twice over: it
8941reaches every collection on the box, and it cannot moderate at all
8942(`status` does not name it).
8943
8944## Subscription And Temporary Access
8945
8946Subscriptions can be broad:
8947
8948```python
8949PermissionPolicy(access_mode=""subscription"")
8950```
8951
8952Or plan-specific:
8953
8954```python
8955PermissionRule.allow(
8956 ""subscription:pro"",
8957 [""read""],
8958 collection=""premium_reports"",
8959)
8960```
8961
8962Temporary pay-per-view style access is a time-boxed grant:
8963
8964```python
8965PermissionRule.allow(
8966 ""user:42"",
8967 [""read""],
8968 object_id=""reports_market_snapshot"",
8969 valid_from=""2026-06-01T00:00:00Z"",
8970 expires_at=""2026-07-01T00:00:00Z"",
8971)
8972```
8973
8974If access should be consumed after one or more views, that should be tracked by
8975an entitlement or ledger object. The permission rule says access is possible;
8976the ledger object records purchases, consumption, refunds, and audit history.
8977
8978For HTTP APIs, missing or expired paid entitlement should map to:
8979
8980```text
8981402 Payment Required
8982```
8983
8984That is different from:
8985
8986- `401 Unauthorized` - the server does not know who the user is yet.
8987- `403 Forbidden` - the server knows the user, but the user is not allowed.
8988- `402 Payment Required` - the user may be allowed after subscription,
8989 purchase, credit, or another payment entitlement.
8990
8991## Scroll Contract
8992
8993Scroll should eventually call a server endpoint that exposes the same decision
8994shape:
8995
8996```json
8997{
8998 ""allowed"": true,
8999 ""reason"": ""sales reps only see own contacts"",
9000 ""code"": ""allowed"",
9001 ""http_status"": 200,
9002 ""row_filter"": {""owner_id"": ""$user_id""},
9003 ""fields"": null,
9004 ""denied_fields"": []
9005}
9006```
9007
9008That lets Scroll show permission previews, generated matrices, ""test as role"",
9009and AI-generated rules without becoming the authority.
9010"
9011secrets-and-credentials Secrets, Credentials, and the Trust Boundary Security & Limits 610 Where secrets live in DBBASIC, why a secret is never a record field, and the honest threat model behind the write-only identity vault. "This is the doctrine for **where secrets live** in DBBASIC and why. It matters
9012to anyone writing a package that touches a credential — a user's third-party
9013API key, an outbound-mail relay password, an email-hosting mailbox password, a
9014signing token. Get this wrong and a secret ends up in a record collection,
9015which means it ends up in an export, a backup, or an API read. Get it right and
9016secrets stay in one place, with one honest boundary, that every other part of
9017the system already trusts.
9018
9019The one-line rule: **a secret is never a record field.** Records are readable,
9020listable, exportable, and included in portable backups by design. A secret must
9021be none of those things. So secrets go somewhere else, through a different door.
9022
9023## Where secrets live
9024
9025There are exactly two homes, by lifetime and ownership:
9026
9027### 1. Deploy-time, server-wide secrets → the environment file
9028
9029A credential the *whole deployment* shares — the SMTP relay password
9030(`DBBASIC_SMTP_PASSWORD`), a connector's API key (`DBBASIC_MAILCOW_API_KEY`),
9031the admin token (`DBBASIC_ADMIN_TOKEN`) — lives in
9032`/etc/dbbasic-object-server.env`, `640 root:dbbasic` (see
9033[`single-vm-deployment.md`](/docs/single-vm-deployment)). It is set by the operator, read by the server
9034process, and never appears in a schema field, a record, an API response, or a
9035backup archive. A package that needs one **declares the env var name in its
9036docs and reads it at runtime** — it never ships the value and never stores it.
9037
9038### 1a. The box's exchange signing key → a file the server makes
9039
9040Box-to-box exchange (`box-to-box-exchange.md`) signs
9041with an Ed25519 private key the server generates itself, so it cannot come
9042from the environment file. It is written once to
9043`<data dir>/exchange/private/<hex>.key`, mode 0600 in a 0700 directory, with
9044O_EXCL so it is never briefly readable by others. It is never a record, never
9045served (only its public half is, in `/.well-known/dbbasic`), never logged,
9046and never in a runtime backup: that directory is outside every directory a
9047backup copies, and `tests/test_exchange_core.py` opens a real archive to
9048check. Back it up yourself, with the other deployment secrets. A rotated
9049key's file is deleted.
9050
9051### 1b. The record revision key → a file the server makes
9052
9053The `_rev` a client is given for a record is an HMAC keyed with 32 random
9054bytes the server writes on first use to `<data dir>/record_rev/secret.key`,
9055mode 0600 in a 0700 directory (written under a temporary name and linked
9056into place, so workers racing to make it all read the same one). Every
9057worker on the data dir reads that file; it is never served, logged, or in a
9058runtime backup. Losing it only means every `_rev` changes once (each held
9059`If-Match` gets one `409`); copy it with the other deployment secrets to
9060keep revs across a move to a new box. A damaged file is refused, not
9061replaced: delete it and restart. See ""Optimistic Concurrency"" in
9062[`http-api-contract.md`](/docs/http-api-contract).
9063
9064### 2. Per-user recoverable secrets → the identity vault
9065
9066A secret that belongs to *one user* and must be *recoverable to be used* (a BYO
9067API key the server calls a provider with; a mailbox password handed to the mail
9068server) lives in the **write-only identity vault**, `object_service_keys`
9069(`identity/service_keys.tsv`). Its contract:
9070
9071- **Owner-only file**, `0600`, next to `credentials.tsv` — same filesystem
9072 trust boundary as the admin token.
9073- **Write-only**: a caller can *set* a key, *list which services have one*, and
9074 *delete* one. **No surface ever reads key material back** — not the HTTP API,
9075 not the shell, not an agent, not a package. The server uses a stored key
9076 internally (to call the provider) so it never travels to a browser.
9077- **Stored as-provided, not encrypted, not hashed.** Passwords are hashed
9078 because they only need to be *verified*; these must be *used*, so they must be
9079 recoverable. On-record encryption with a key derived from a server secret
9080 (the pattern many frameworks reach for) is *theater* here — the ciphertext and
9081 the key it's decrypted with live in the same blast radius, so they leak
9082 together (see the Trust Boundary section). The real protection is the `0600`
9083 file and the write-only contract, not a cipher.
9084- **Excluded from portable backups and source control** — so a leaked backup
9085 archive, the most common accidental exposure, contains no secret material.
9086 (See [`backup-restore.md`](/docs/backup-restore); a package must never undo this by copying a secret
9087 into a record it *does* back up.)
9088
9089**Concrete example**: the AI chat, cloud TTS, and cloud STT features
9090(`docs/shell-and-ai.md`) all read from this vault, not the env file — a
9091user's own `anthropic` and/or `openai` key, set via `PUT
9092/identity/users/{you}/service-keys`. One stored `openai` key covers chat,
9093`POST /api/tts` with `engine: ""openai""`, and `POST /api/stt` — no separate
9094signup per feature. This is also why those features are per-user opt-in
9095rather than deployment-wide: `DBBASIC_ENABLE_AI_CHAT`/`_TTS`/`_STT` in the
9096env file only unlock the *capability*; each user still needs their own
9097stored key before any of it does anything for them.
9098
9099A second example with one entry per record: mail sync (`app-mail-sync`)
9100keeps each IMAP account's password as `imap-<account id>`, resolved by the
9101**account row's** `owner_id`. The account record has no password field,
9102and its page shows only whether the entry is set.
9103
9104## How a secret gets written (it is not a record write)
9105
9106The vault has its own door, deliberately separate from the generic record API:
9107
9108```
9109GET /identity/users/{user_id}/service-keys → which services are set (status only)
9110PUT /identity/users/{user_id}/service-keys → { ""service"": ""..."", ""key"": ""..."" }
9111DELETE /identity/users/{user_id}/service-keys/{service} → clear one
9112```
9113
9114- **Owner-scoped**: only the account owner's own session may write their vault
9115 (or the operator admin gate). Identity is resolved server-side from an opaque
9116 session token — it cannot be spoofed by a client-supplied user id.
9117- **CSRF-guarded**: cross-origin cookie writes are refused.
9118- **Never echoes material**: `PUT` returns metadata (`service`, timestamps)
9119 only; `GET` returns presence only.
9120
9121`POST /collections/{c}/records` — the generic record write — **cannot reach the
9122vault at all.** That is the point: there is no record surface to misconfigure
9123into leaking a secret.
9124
9125**In a generated UI**, a secret is a *write-only field*: it renders as ""set /
9126not set"" with an input that only ever POSTs to the vault endpoint above and
9127never displays a stored value. The form still looks uniform to the user — one
9128field just writes to a different door than the record.
9129
9130## Reserved namespaces: user-writable vs platform-owned
9131
9132A vault entry is keyed by a **service name**. Two kinds:
9133
9134- **User-writable** (a person's own BYO credential): a plain name — `openai`,
9135 `anthropic`, `stripe`. The self-service endpoint above writes these.
9136- **Platform-owned** (a secret the *platform* provisions on the user's behalf —
9137 a generated mailbox password): a **reserved name**, prefixed `sys-`
9138 (e.g. `sys-mailbox-<mailbox_id>`). **The self-service HTTP endpoint refuses to
9139 write or delete a reserved name.** Only in-process server code (a connector, a
9140 provisioning verb) may set one.
9141
9142This is the control that stops a user from **overwriting a secret the platform
9143owns**. Without it, a user could `PUT` their own `sys-mailbox-<id>` and clobber
9144the password the mail server actually uses. `object_service_keys.is_reserved_service()`
9145is the single source of truth for the rule; the HTTP handler enforces it.
9146
9147Two more rules for platform-owned secrets a package must follow:
9148
9149- **Scope every read by the record's owner**, never by caller input. Resolve a
9150 mailbox's secret from *the mailbox record's `owner_id`* — never from a
9151 `mailbox_id` a request supplied — or a user could plant an entry in their own
9152 vault and hope a global lookup reads it.
9153- **Generate, don't collect, when you can.** A provisioned password should be
9154 generated server-side (`secrets.token_urlsafe`), stored in the vault, and
9155 revealed to the user *exactly once* in the provisioning response — never read
9156 back afterward.
9157
9158## The trust boundary (threat model)
9159
9160Be honest about what actually protects the vault, because it changes what's
9161worth building. A secret is reachable only by one of these, and **every one of
9162them also compromises the entire system** — so the vault is not a weaker link,
9163it inherits the system's security:
9164
9165| Vector | What it takes | Does encryption-at-rest help? |
9166|---|---|---|
9167| **A logged-in user** reaching another user's secret | Impossible via the API: owner-scoped, server-derived identity, reserved-namespace guard | N/A — blocked at the app layer |
9168| **Code execution as the service user** | An RCE in the server, or an installed package/connector (both run as the service user and legitimately read the vault) | **No** — the running process holds the key too |
9169| **Root on the host** | Kernel/sudo/other-service exploit; `0600` is nothing to root | **No** — same blast radius |
9170| **The raw disk** | A VM snapshot, an attached volume, a stolen *unencrypted* backup | **Only here** — and only if the key lives off-box (a KMS) |
9171| **The deploy path** | A dev-box SSH key or a push-to-prod pipeline → arbitrary code as the service user | **No** — it's code execution with a login |
9172
9173Conclusions that follow:
9174
9175- **A plain user cannot reach it.** They are boxed into their own namespace by a
9176 server-resolved identity and the reserved-namespace guard.
9177- **On-box encryption of the vault is theater** against every vector except a
9178 raw-disk/snapshot theft — because for all the others the decryption key rides
9179 in the same boundary. The genuinely stronger option is **envelope encryption
9180 with a KMS-held root key**, and only when you have a KMS (not on a single VM).
9181 Until then, the higher-leverage move is to **encrypt backups/snapshots with an
9182 off-box key and lock the hosting account with 2FA** — the deploy credential
9183 and the hosting account are, in effect, vault keys.
9184- **""Installed package = code execution as the service user""** is a stated trust
9185 fact, which is why package installs (and any dynamically loaded connector
9186 code) are admin-gated. Fine while packages are first-party; it needs a
9187 stronger answer before any third-party marketplace.
9188
9189## Checklist for package authors
9190
9191- [ ] **Never** put a secret in a schema field or a record.
9192- [ ] Server-wide credential → read from a documented `DBBASIC_*` env var; never ship or store the value.
9193- [ ] Per-user recoverable secret → the identity vault (`object_service_keys`), write-only.
9194- [ ] Platform-provisioned secret → a `sys-`-prefixed reserved service name; write it only from server-side code.
9195- [ ] Resolve a secret by the owning record's `owner_id`, never by caller-supplied input.
9196- [ ] Prefer generating a secret and revealing it once over collecting and storing it.
9197- [ ] In a UI, a secret field is write-only (set/not-set), posting to the vault endpoint, never rendering the value.
9198- [ ] Never copy a secret into anything that lands in a backup or an export.
9199
9200## See also
9201
9202- [`single-vm-deployment.md`](/docs/single-vm-deployment) — the env-file trust boundary and admin-route posture.
9203- [`permissions-model.md`](/docs/permissions-model) — owner-scoping and the admin bypass.
9204- [`backup-restore.md`](/docs/backup-restore) — what is and isn't in a portable backup.
9205- [`package-authoring.md`](/docs/package-authoring) — how a package ships schemas, permissions, and (soon) connectors.
9206"
9207traffic-limits Traffic Limits Security & Limits 620 How the DBBASIC Object Server rejects oversized, overloaded, or runaway traffic before object code runs, and the env vars that control each limit. "DBBASIC should reject bad or oversized traffic before object code runs. The
9208runtime keeps the object loop fast by failing early when a request is too large
9209or when the server is under pressure.
9210
9211## Request Body Size
9212
9213The ASGI server enforces a request body cap:
9214
9215```text
9216DBBASIC_MAX_REQUEST_BYTES=1048576
9217```
9218
9219The default is `1048576` bytes, or 1 MiB. If a request body is larger than the
9220configured value, the server returns:
9221
9222```http
9223413 Payload Too Large
9224```
9225
9226```json
9227{
9228 ""status"": ""error"",
9229 ""error"": ""Request body too large"",
9230 ""max_bytes"": 1048576
9231}
9232```
9233
9234This applies before JSON parsing and before object execution. It checks
9235`Content-Length` when present and also counts streamed ASGI body chunks.
9236
9237Large file upload paths should get their own file API and their own explicit
9238limits. Normal object `POST`, `PUT`, and `DELETE` requests should stay small.
9239
9240## Concurrency
9241
9242The ASGI server also enforces per-process concurrency caps:
9243
9244```text
9245DBBASIC_MAX_CONCURRENT_REQUESTS=64
9246DBBASIC_MAX_CONCURRENT_EXECUTIONS=8
9247```
9248
9249`DBBASIC_MAX_CONCURRENT_REQUESTS` limits non-health HTTP requests that are in
9250flight inside one server process. `/health` bypasses this limit so a monitor can
9251still check whether the process is alive under load.
9252
9253`DBBASIC_MAX_CONCURRENT_EXECUTIONS` limits object method executions inside one
9254server process. Introspection routes, health checks, and other non-execution
9255requests do not consume object execution slots.
9256
9257When either limit is full, the server returns:
9258
9259```http
9260503 Service Unavailable
9261```
9262
9263```json
9264{
9265 ""status"": ""error"",
9266 ""error"": ""Server is busy"",
9267 ""limit"": ""object_executions"",
9268 ""max_concurrent"": 8
9269}
9270```
9271
9272A third cap protects customers from each other: a user's objects
9273(`u_<id>_*`) may run at most `DBBASIC_MAX_CONCURRENT_EXECUTIONS_PER_USER=3`
9274at once, and the next request is `429` with `Retry-After` for that user only,
9275so one customer's slow requests cannot fill the shared pool. The operator and
9276system objects are not capped per user.
9277
9278Set either concurrency value to `0` to disable that app-level limit for local
9279experiments. Production and staging deployments should keep explicit limits.
9280
9281These caps are per process. If uvicorn runs multiple workers, each worker has
9282its own counters. A reverse proxy or process manager still controls the total
9283machine-level shape.
9284
9285## Rate Limits
9286
9287Rate limiting is opt-in:
9288
9289```text
9290DBBASIC_RATE_LIMIT_REQUESTS=1000
9291DBBASIC_RATE_LIMIT_WINDOW_SECONDS=60
9292```
9293
9294The default `DBBASIC_RATE_LIMIT_REQUESTS=0` leaves the app-level limiter
9295disabled for local development. Public staging and production deployments should
9296set an explicit value.
9297
9298When enabled, the server checks the rate limit before reading the request body
9299or running object code. Plain `GET /health` is excluded so external monitoring
9300can still tell whether the process is alive. Detailed health via
9301`capacity=true` or `metrics=true` is rate-limited and still requires the admin
9302token.
9303
9304The limiter stores one timestamp bucket per identity under:
9305
9306```text
9307data/ratelimit/
9308```
9309
9310Those files are runtime guardrails, not application data. Backups exclude them.
9311
9312Valid admin-token requests use a token bucket. Other requests use the client IP.
9313By default the server ignores `X-Forwarded-For` and `X-Real-IP`; enable proxy
9314header trust only when uvicorn is bound privately behind a trusted reverse
9315proxy:
9316
9317```text
9318DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS=true
9319```
9320
9321When the limit is full, the server returns:
9322
9323```http
9324429 Too Many Requests
9325Retry-After: 30
9326```
9327
9328```json
9329{
9330 ""status"": ""error"",
9331 ""error"": ""Rate limit exceeded"",
9332 ""retry_after"": 30,
9333 ""limit"": 1000,
9334 ""window_seconds"": 60
9335}
9336```
9337
9338## Object Execution Timeout
9339
9340Object execution timeout is opt-in:
9341
9342```text
9343DBBASIC_OBJECT_TIMEOUT_SECONDS=5
9344```
9345
9346The default `0` keeps local development on the direct in-process execution path.
9347When the value is above zero, object methods run in a short-lived worker process.
9348If the object does not finish before the wall-clock timeout, the server
9349terminates the worker and returns:
9350
9351```http
9352504 Gateway Timeout
9353```
9354
9355```json
9356{
9357 ""status"": ""error"",
9358 ""error"": ""Execution failed: GET timed out for object basics_slow after 5 seconds""
9359}
9360```
9361
9362Timeout failures are written to the object log with
9363`ObjectExecutionTimeoutError`, so Scroll and operators can see which object
9364timed out.
9365
9366Trusted server-owned objects can opt back into the fast in-process path even
9367when timeouts are enabled:
9368
9369```text
9370DBBASIC_TRUSTED_IN_PROCESS_OBJECTS=site_home,system_health
9371```
9372
9373Use that only for reviewed objects shipped or controlled by the server operator,
9374such as a public homepage that receives frequent hits. Untrusted user objects
9375should stay on the timeout-enabled worker path.
9376
9377### Warm worker pool
9378
9379With a timeout set and nothing else, every HTTP-invoked object (page objects
9380served by site routes, `/objects/*`, webhooks) runs in a freshly spawned
9381interpreter. That is safe but slow. `DBBASIC_WORKER_POOL_SIZE` is off by
9382default (`0`); set it to keep that many long-lived worker processes warm:
9383
9384```text
9385DBBASIC_OBJECT_TIMEOUT_SECONDS=5
9386DBBASIC_WORKER_POOL_SIZE=2
9387```
9388
9389A pooled worker hands its result back as JSON. An object that returns a value
9390JSON cannot hold (bytes, a set, a tuple as a dict key) is answered `500` with
9391`Execution failed: object returned a value that is not JSON: bytes at body`
9392-- the type and the key path -- and the worker writes one line to the server
9393log with the object id and the type, never the value. The worker stays up. Without
9394the pool the answer is the same `500` and log line, given by the server when
9395it builds the JSON answer (a `bytes` body beside a `content_type` is not JSON
9396and is served as before, though not through the pool).
9397
9398What stays the same: objects still run outside the server process, a call that
9399exceeds the timeout still returns the same `504` (the worker is replaced and
9400the pool keeps serving), errors come back in the same shape, and a source edit
9401to an object is picked up on the next request. The pool's workers are shut down
9402with the server. Objects listed in `DBBASIC_TRUSTED_IN_PROCESS_OBJECTS` still
9403bypass the pool and run in the server process. `DBBASIC_MAX_CONCURRENT_EXECUTIONS`
9404still caps how many executions are admitted; the pool size is how many of them
9405can actually run in parallel, so keep the pool at or below that cap.
9406
9407A reasonable starting size is `2` on a small VM. Each worker used about 32 MB
9408of RSS after rendering one page, so budget that per worker.
9409
9410Measured on one machine (Apple M1 Pro), rendering the real app-notes `/notes`
9411page (`site_view_render`) with 200 notes, so treat these as indicative, not as
9412a capacity plan:
9413
9414| Mode | Page shell | Throughput |
9415| --- | --- | --- |
9416| in-process (no timeout) | about 5 ms | |
9417| timeout, no pool (spawn per call) | about 68 ms | about 14 req/s at 8 connections, p50 544 ms |
9418| timeout + pool of 4 | about 5.7 ms | about 257 req/s at 8 connections |
9419
9420The benchmark is `scripts/bench/experiments/real_page_modes.sh`. The test
9421`tests/test_worker_pool_real_pages.py` checks that the real notes page, the
9422identity payload, error shape, live edits and the timeout behave the same with
9423and without the pool.
9424
9425This boundary is intentionally narrow. It stops hung object work and releases
9426the execution slot, but it is not the final sandbox. CPU quotas and memory
9427limits are still future hardening steps.
9428
9429## Capacity Health
9430
9431`GET /health` stays public and cheap:
9432
9433```json
9434{
9435 ""status"": ""ok""
9436}
9437```
9438
9439Detailed capacity is an operator surface and requires the admin token:
9440
9441```http
9442GET /health?capacity=true
9443Authorization: Token <token>
9444```
9445
9446It reports the configured request and object execution limits, current
9447in-flight slot counts, object count, storage status, version, uptime, request
9448counts, recent response timing, and basic process/system information. Scroll and
9449future station routers should use this detailed shape instead of guessing from
9450logs.
9451
9452`GET /health?metrics=true` includes the same capacity payload plus detailed
9453request metrics such as status counts, top paths, and recent HTTP errors.
9454
9455## High-Traffic Shape
9456
9457Use layered limits:
9458
9459- reverse proxy body limit before Python receives the request
9460- app body limit through `DBBASIC_MAX_REQUEST_BYTES`
9461- app request and object execution limits through the concurrency env vars
9462- per-IP and per-token rate limits before write or execute paths
9463- object execution wall-clock timeouts
9464- later CPU and memory isolation around worker processes
9465
9466When the server is overloaded, it should return `429 Too Many Requests` for rate
9467limits or `503 Service Unavailable` for temporary capacity pressure. That is
9468better than letting a small VM run out of memory or accumulate unbounded object
9469work.
9470
9471## Staging Defaults
9472
9473For the first public staging VM:
9474
9475```text
9476DBBASIC_MAX_REQUEST_BYTES=1048576
9477DBBASIC_MAX_CONCURRENT_REQUESTS=64
9478DBBASIC_MAX_CONCURRENT_EXECUTIONS=8
9479DBBASIC_OBJECT_TIMEOUT_SECONDS=5
9480DBBASIC_WORKER_POOL_SIZE=2
9481DBBASIC_RATE_LIMIT_REQUESTS=1000
9482DBBASIC_RATE_LIMIT_WINDOW_SECONDS=60
9483DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS=true
9484DBBASIC_ENABLE_SOURCE_WRITES=false
9485```
9486
9487Keep source writes closed until auth, permissions, backups, and rollback checks
9488are working. Keep public routes narrow. Let the object server prove the loop
9489without allowing arbitrary public code changes.
9490
9491## Cluster Direction
9492
9493Local capacity should become a station signal. A single station can already
9494return `503` when it is full. Later, station heartbeat or health data should
9495include capacity fields so a cluster router can avoid saturated stations before
9496forwarding object work.
9497
9498That signal should include request slots, execution slots, recent error rate,
9499and basic machine load such as CPU and memory pressure. That keeps the cluster
9500model simple: each station knows its own limits, and the router uses those
9501limits to choose where work should go.
9502
9503## Logs And Garbage Collection
9504
9505Traffic controls also need disk controls:
9506
9507- rotate object logs before they grow forever
9508- gzip rotated logs at rest
9509- keep a bounded number of rotated logs per object
9510- disable noisy uvicorn access logs in systemd and rely on object logs,
9511 request metrics, and deliberate analytics objects
9512- cap journald retention for process logs
9513- keep backup retention explicit
9514- delete temp files and stale lock files only through known runtime paths
9515
9516The active object log stays plain TSV so tools can tail it. Rotated logs can be
9517read in place with normal Unix tools such as `gzip -cd`.
9518
9519## Next Limits
9520
9521The request, concurrency, rate-limit, and timeout caps are only the first
9522boundaries. The next production-hardening steps are:
9523
9524- CPU and memory isolation for untrusted object code
9525- a longer-lived worker pool so timeout-enabled execution does not need a new
9526 process per request
9527"
9528single-vm-deployment Single VM Deployment Deployment & Operations 700 How to deploy DBBASIC Object Server on a single VM: layout, install, environment, systemd, HTTPS proxy, backups, and upgrade procedure. "This is the first deployment target for DBBASIC Object Server: one small VM,
9529one ASGI process, one object source directory, and one data directory.
9530
9531The goal is not to claim the public runtime is production-ready. The goal is to
9532keep a clean staging server running so install, restart, logs, object storage,
9533and the edit/run/inspect loop are tested on a real machine.
9534
9535This shape should stay cheap and understandable: one small VM can run the
9536server, objects, TSV-backed state, logs, versions, HTTPS proxy, and monitoring
9537without requiring a separate database tier for the first useful app.
9538
9539## Deployment Goal
9540
9541The first deployment path should stay closer to a simple Unix/PHP-style upload
9542than a large multi-service app stack:
9543
9544- one VM is enough for the first useful business app
9545- no container runtime is required for the base deployment
9546- no separate database server is required before the app proves itself
9547- server code, live object source, runtime data, and secrets live in separate
9548 Unix paths
9549- normal upgrades are `git pull`, package install, service restart, checks
9550- object edits do not require a full server redeploy
9551- every manual step should become scriptable after it stays boring
9552
9553This does not mean skipping safety. The simple path still uses a service user,
9554systemd, a reverse proxy, HTTPS, private config, filesystem checks, backups, and
9555explicit public route allowlists.
9556
9557## Verified Baseline
9558
9559The first staging install was verified on:
9560
9561- Ubuntu 24.04.4 LTS
9562- Python 3.12.3
9563- Git 2.43.0
9564- Caddy 2.11.4
9565- systemd with the DBBASIC service and Caddy running as separate units
9566
9567Record the baseline on each new VM. Run the Caddy commands after Caddy is
9568installed, if the VM does not already have it.
9569
9570```bash
9571lsb_release -a
9572python3 --version
9573git --version
9574caddy version
9575systemctl is-active dbbasic-object-server caddy
9576cd /opt/dbbasic-object-server
9577sudo -u dbbasic git rev-parse --short HEAD
9578```
9579
9580Do not commit the VM's real IP address, hostname, or provider-specific details
9581to this repository.
9582
9583## System Updates
9584
9585Before using a new VM for staging, apply normal OS updates and reboot if Ubuntu
9586requests it:
9587
9588```bash
9589sudo apt update
9590apt list --upgradable
9591sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y
9592sudo DEBIAN_FRONTEND=noninteractive apt-get autoremove -y
9593test -f /var/run/reboot-required && cat /var/run/reboot-required || true
9594```
9595
9596If packages are kept back because they need new dependencies, install them
9597explicitly when they are normal platform packages:
9598
9599```bash
9600sudo DEBIAN_FRONTEND=noninteractive apt-get install -y fwupd
9601```
9602
9603After a reboot, verify the services and endpoint again:
9604
9605```bash
9606sudo systemctl is-active dbbasic-object-server caddy
9607curl https://dbbasic.example.com/
9608```
9609
9610## Provider Monitoring
9611
9612For DigitalOcean Droplets, the metrics agent is useful on staging VMs because it
9613adds CPU, memory, disk, and network graphs plus alerting while the server is
9614under active development. DigitalOcean describes this as a free opt-in service.
9615It sends system telemetry for monitoring, not customer content.
9616
9617Install it after normal OS updates:
9618
9619```bash
9620curl -fsSL https://repos.insights.digitalocean.com/install.sh -o /tmp/do-agent-install.sh
9621sudo bash /tmp/do-agent-install.sh
9622```
9623
9624Verify it:
9625
9626```bash
9627systemctl is-active do-agent
9628systemctl is-enabled do-agent
9629dpkg-query -W do-agent
9630systemctl --no-pager --full status do-agent
9631```
9632
9633Metrics usually appear in the Droplet's Insights tab after a few minutes. This
9634is provider-specific VM monitoring; it does not replace DBBASIC's own object
9635logs, state, versions, or future application/runtime metrics.
9636
9637## Layout
9638
9639Use separate paths for server code, object source, and runtime data:
9640
9641```text
9642/opt/dbbasic-object-server
9643/var/lib/dbbasic-object-server/objects
9644/var/lib/dbbasic-object-server/data
9645```
9646
9647- `/opt/dbbasic-object-server` is the git checkout.
9648- `/var/lib/dbbasic-object-server/objects` contains live object source files.
9649- `/var/lib/dbbasic-object-server/data` contains state, logs, and versions.
9650
9651`objects` and `data` are mode 0700, owned by `dbbasic`: user objects run as a
9652second user, `dbbasic-sandbox`, which must not be able to traverse, `stat` or
9653`chmod` anything in them (see ""Kernel Requirements for User Code"").
9654
9655Keeping objects and data outside the checkout lets the server be upgraded
9656without mixing application data into git history.
9657
9658## Install
9659
9660On a fresh Debian or Ubuntu VM:
9661
9662```bash
9663sudo apt update
9664sudo apt install -y python3 python3-venv python3-pip git
9665sudo useradd --system --home /var/lib/dbbasic-object-server --shell /usr/sbin/nologin dbbasic
9666sudo mkdir -p /opt/dbbasic-object-server
9667sudo mkdir -p /var/lib/dbbasic-object-server/objects
9668sudo mkdir -p /var/lib/dbbasic-object-server/data
9669sudo chown -R dbbasic:dbbasic /opt/dbbasic-object-server /var/lib/dbbasic-object-server
9670sudo chmod 755 /opt/dbbasic-object-server
9671sudo chmod 750 /var/lib/dbbasic-object-server
9672sudo chmod 750 /var/lib/dbbasic-object-server/objects
9673sudo chmod 750 /var/lib/dbbasic-object-server/data
9674```
9675
9676Clone and install the server:
9677
9678```bash
9679sudo -u dbbasic git clone <repository-url> /opt/dbbasic-object-server
9680cd /opt/dbbasic-object-server
9681sudo -u dbbasic python3 -m venv .venv
9682sudo -u dbbasic .venv/bin/python -m pip install -e '.[server,scheduler]'
9683```
9684
9685## Environment
9686
9687Create `/etc/dbbasic-object-server.env`:
9688
9689```text
9690DBBASIC_OBJECTS_DIR=/var/lib/dbbasic-object-server/objects
9691DBBASIC_DATA_DIR=/var/lib/dbbasic-object-server/data
9692DBBASIC_BACKUPS_DIR=/var/lib/dbbasic-object-server/data/backups
9693DBBASIC_PACKAGES_DIR=/opt/dbbasic-object-server/packages
9694DBBASIC_ENABLE_SOURCE_WRITES=false
9695# Non-admin users writing their own u_<id>_ objects. Keep false until user
9696# objects run sandboxed -- see ""User objects and external identity"" below.
9697DBBASIC_ENABLE_USER_SOURCE_WRITES=false
9698# An external token verifier (e.g. a DRF app's /api/auth/verify/). Unset = off.
9699# Must be a trusted internal service: every caller's token is sent to it.
9700# https:// is required unless the host is loopback (127.0.0.0/8, ::1, localhost).
9701# DBBASIC_IDENTITY_VERIFY_URL=http://127.0.0.1:8000/api/auth/verify/
9702# This server's name; the verifier must echo it as ""audience"" (required).
9703# DBBASIC_IDENTITY_AUDIENCE=box-a.example.com
9704# Shared secret sent as X-DBBASIC-Verify-Secret (required for a non-loopback URL).
9705# DBBASIC_IDENTITY_VERIFY_SECRET=<random, 16+ visible characters>
9706# Roles the verifier may confer (default: none; admin names never).
9707# DBBASIC_IDENTITY_VERIFY_ALLOWED_ROLES=viewer,editor
9708# Seconds a verified token is trusted before re-asking (default 30, at most 60). The app
9709# can also POST /admin/identity/sources/forget (admin token) on revocation.
9710# DBBASIC_IDENTITY_CACHE_TTL_SECONDS=30
9711DBBASIC_ENABLE_FILE_WRITES=false
9712DBBASIC_ENABLE_PACKAGE_INSTALLS=false
9713DBBASIC_ENABLE_PACKAGE_RESTORE=false
9714# AI chat, voice, and reader -- each is its own flag; enabling AI chat does
9715# NOT enable TTS/STT/reader. Each also needs a per-user provider key stored
9716# via PUT /identity/users/{id}/service-keys before it does anything -- see
9717# docs/shell-and-ai.md and docs/secrets-and-credentials.md.
9718DBBASIC_ENABLE_AI_CHAT=false
9719DBBASIC_AI_TIMEOUT_SECONDS=60
9720DBBASIC_AI_DEFAULT_MODEL=anthropic:claude-haiku-5-5
9721# Effort for conversation tool subsets and for builder mode
9722# (low|medium|high|xhigh|max); sent only to Claude 4.6+ models.
9723DBBASIC_AI_EFFORT=low
9724DBBASIC_AI_BUILDER_EFFORT=high
9725DBBASIC_ENABLE_TTS=false
9726DBBASIC_TTS_CLOUD_TIMEOUT_SECONDS=30
9727# STT costs real money on every utterance (not just occasional replies
9728# like TTS) -- leave this off even where TTS is on unless you mean it.
9729DBBASIC_ENABLE_STT=false
9730DBBASIC_STT_TIMEOUT_SECONDS=30
9731DBBASIC_ENABLE_READER=false
9732DBBASIC_ADMIN_TOKEN=replace-with-a-generated-token
9733DBBASIC_MAX_REQUEST_BYTES=1048576
9734DBBASIC_MAX_OBJECT_FILE_BYTES=1048576
9735DBBASIC_MAX_CONCURRENT_REQUESTS=64
9736DBBASIC_MAX_CONCURRENT_EXECUTIONS=8
9737# One customer's user objects may run this many at once (0 = no per-user cap).
9738# Over it, that customer alone gets 429; others are unaffected.
9739DBBASIC_MAX_CONCURRENT_EXECUTIONS_PER_USER=3
9740# Per-customer storage quotas for u_<id>_ objects (0 = unlimited each):
9741# objects owned, bytes of one object's state, bytes of all _files storage.
9742DBBASIC_USER_MAX_OBJECTS=100
9743DBBASIC_USER_MAX_STATE_BYTES=5242880
9744DBBASIC_USER_MAX_FILES_BYTES=104857600
9745DBBASIC_OBJECT_TIMEOUT_SECONDS=5
9746DBBASIC_WORKER_POOL_SIZE=2
9747DBBASIC_TRUSTED_IN_PROCESS_OBJECTS=site_home
9748DBBASIC_RATE_LIMIT_REQUESTS=1000
9749DBBASIC_RATE_LIMIT_WINDOW_SECONDS=60
9750DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS=true
9751DBBASIC_ENABLE_PERMISSION_AUDIT=false
9752DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=false
9753DBBASIC_PERMISSION_TRUST_HEADERS=false
9754# true = a stored allow rule whose narrowing key was dropped (a misspelt or
9755# null row_filter, collection, ...) grants nothing instead of applying more
9756# widely than written. Deny rules are untouched. Off by default; the default
9757# may turn on in a later release (`docs/permissions-model.md`).
9758DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS=false
9759DBBASIC_ENABLE_SESSION_LOGIN=false
9760DBBASIC_SESSION_LOGIN_TOKEN=
9761DBBASIC_ENABLE_PASSWORD_LOGIN=false
9762DBBASIC_COOKIE_SECURE=true
9763DBBASIC_LOGIN_LOCKOUT_ATTEMPTS=5
9764DBBASIC_LOGIN_LOCKOUT_WINDOW_SECONDS=900
9765DBBASIC_ENABLE_RECORD_EVENTS=true
9766DBBASIC_EVENT_KEEP_COUNT=1000
9767DBBASIC_EVENT_KEEP_SECONDS=604800
9768DBBASIC_LOG_MAX_BYTES=10485760
9769DBBASIC_LOG_COMPRESS_ROTATED=true
9770DBBASIC_LOG_KEEP_ROTATED=32
9771# Other feature gates worth knowing exist -- off by default, turn on what
9772# you actually use rather than everything at once.
9773DBBASIC_ENABLE_USER_FILES=false
9774DBBASIC_ENABLE_REALTIME=false
9775DBBASIC_ENABLE_SITE_ROUTES=false
9776DBBASIC_ENABLE_FEED=false
9777DBBASIC_ENABLE_FILTERING=false
9778DBBASIC_ENABLE_CONCURRENCY=false
9779DBBASIC_ENABLE_SESSION_ADMIN_GATES=false
9780# off | shadow | on. Makes a permission-filtered list cost what the user can
9781# see instead of the whole collection (docs/permissions-model.md#row-filter-index).
9782# Run `shadow` first: it serves the old result and logs any disagreement.
9783DBBASIC_ROW_FILTER_INDEX=off
9784# Copy new mail from members' own IMAP mailboxes into their inbox
9785# (app-mail-sync; see docs/http-api-contract.md#mail-sync-imap-inbound).
9786# The second line lets it reach mail servers on private addresses.
9787DBBASIC_ENABLE_MAIL_SYNC=false
9788DBBASIC_MAIL_SYNC_ALLOW_PRIVATE_HOSTS=false
9789```
9790
9791Generate a local token on the VM:
9792
9793```bash
9794python3 -c ""import secrets; print(secrets.token_urlsafe(32))""
9795```
9796
9797Use that generated value for `DBBASIC_ADMIN_TOKEN`. Do not reuse test tokens,
9798README placeholders, or tokens from another server. It is required for local or
9799admin object listing and introspection requests such as source, state, logs,
9800metadata, and versions.
9801
9802## Bootstrap Browser Login
9803
9804To enable browser login on a fresh VM, create the first admin user from the
9805shell and turn on password login:
9806
9807```bash
9808cd /opt/dbbasic-object-server
9809sudo -u dbbasic DBBASIC_DATA_DIR=/var/lib/dbbasic-object-server/data \
9810 .venv/bin/python object_identity_cli.py create-superuser \
9811 --user-id operator --email you@example.com
9812```
9813
9814The password is prompted twice without echo and stored only as a scrypt hash
9815under `data/identity/credentials.tsv` (owner-only permissions, inside the
9816runtime data directory that never enters source control). Then set
9817`DBBASIC_ENABLE_PASSWORD_LOGIN=true` in the environment file, restart the
9818service, and allow `/login` and `/logout` through the reverse proxy. Keep
9819`DBBASIC_COOKIE_SECURE=true` behind HTTPS; set it to `false` only for
9820plain-HTTP local development. Additional users can be managed with the same
9821CLI (`create-user`, `set-password`, `list-users`) or through the admin HTTP
9822surface from Scroll.
9823
9824For the first VM boot, leave source writes disabled. After health checks,
9825backups, and proxy access are working, a staging server can enable source
9826writes:
9827
9828```text
9829DBBASIC_ENABLE_SOURCE_WRITES=true
9830```
9831
9832### User objects and external identity
9833
9834To let another app's users call this server with their own
9835tokens, set `DBBASIC_IDENTITY_VERIFY_URL` to that app's verify endpoint on
9836an internal address (`https://`, or `http://` to a loopback host only),
9837`DBBASIC_IDENTITY_AUDIENCE` to this server's name, and -- for a host that
9838is not loopback -- `DBBASIC_IDENTITY_VERIFY_SECRET`. Those users can then run their own `u_<id>_` objects
9839and list theirs plus the system objects marked `LISTED = True`; they are
9840never admin. Their code may call only system objects marked
9841`USER_CALLABLE = True`, and each user is held to the concurrency and storage
9842limits above (runtime-contract.md ""Fairness and quotas""). See
9843[`permissions-model.md`](/docs/permissions-model#identity-sources).
9844
9845Letting them *write* code is a separate switch,
9846`DBBASIC_ENABLE_USER_SOURCE_WRITES=true`. The server refuses user writes
9847(403) unless user objects can run sandboxed on this host (the sandbox
9848launcher running, Landlock ABI >= 4, not root; `python object_sandbox.py
9849--status`), because without that wall a
9850user write would be arbitrary Python running with the server's privileges.
9851`DBBASIC_ENABLE_SOURCE_WRITES` does not imply it and it does not imply
9852`DBBASIC_ENABLE_SOURCE_WRITES`.
9853
9854Leave file writes disabled on public staging until quotas, permissions, and
9855content policy are ready for the use case. A controlled operator VM can enable
9856them separately:
9857
9858```text
9859DBBASIC_ENABLE_FILE_WRITES=true
9860```
9861
9862Permission audit and enforcement should also stay closed on first boot. Turn on
9863audit mode first to watch route decisions without blocking users:
9864
9865```text
9866DBBASIC_ENABLE_PERMISSION_AUDIT=true
9867```
9868
9869Request blocking only after the persisted policy and auth gateway are confirmed:
9870
9871```text
9872DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true
9873```
9874
9875Once set, enforcement is always effective: every request is decided by the
9876policy, and `permissions.mode` in `/permissions/status` reads `enforced`. The
9877readiness checks in `/permissions/status` are advisory. A problem while
9878enforced never opens the box; it shows in what the affected callers get:
9879a corrupt or unreadable policy answers `503 permission_policy_unavailable` to
9880everyone but the admin token (which can repair it with
9881`PUT /permissions/policy`), an unreadable identity store answers
9882`503 identity_store_unavailable` to signed-in callers, and with no sign-in
9883path only the admin token and public grants get in. The server logs a
9884`WARNING` for each problem at startup, `GET /admin/status` leads with it
9885under `alerts`, and a problem that appears later is logged as an `ERROR`
9886and recorded in `GET /admin/ops?kind=permission_readiness`. A policy with no
9887grants is enforced as deny-all for everyone but admins, which is how a fresh
9888box starts until it has a policy (see
9889[permissions-model.md](/docs/permissions-model#route-enforcement) for the
9890fresh-box order).
9891
9892The one thing enforcement refuses to start without is
9893`DBBASIC_ADMIN_TOKEN`, the way in for every other problem. For one release
9894`DBBASIC_ALLOW_START_WITH_BLOCKED_ENFORCEMENT=true` starts without it,
9895still enforced (it used to start the server unenforced, and no longer does).
9896`DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT` no longer does anything;
9897remove it. To run without enforcement on purpose, leave
9898`DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=false` and use
9899`DBBASIC_ENABLE_PERMISSION_AUDIT=true` to watch decisions.
9900
9901A hosted, multi-user box should also set
9902`DBBASIC_REQUIRE_PERMISSION_ENFORCEMENT=true`: the server then refuses to
9903start, with a one-line `Refusing to start: ...` error, unless
9904`DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true` (audit alone refuses too), so a
9905lost or mistyped enforcement flag cannot bring the box up open. Unset, it
9906changes nothing.
9907
9908`DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS=true` stops the engine applying a
9909stored allow rule that `/admin/status` reports as allowing more than written
9910(a misspelt or null `row_filter`, `collection` and the like): the rule grants
9911nothing until it is fixed. Before turning it on, read the alert and
9912`GET /permissions/status`: every rule named there as an allow that ""applies
9913more widely than written"" will stop granting, which can lock its users out of
9914that collection until you fix the key. Deny rules are not affected. Unset or
9915`false`, it changes nothing (`docs/permissions-model.md`).
9916
9917`DBBASIC_PERMISSION_TRUST_HEADERS=true` is only appropriate when a trusted proxy
9918or auth gateway strips client-supplied identity headers and writes fresh
9919`X-DBBASIC-*` headers itself.
9920
9921Do not commit real tokens, VM hostnames, private URLs, or deployment-specific
9922paths to this repository.
9923
9924After creating the file, keep it readable by root and the service group only:
9925
9926```bash
9927sudo chown root:dbbasic /etc/dbbasic-object-server.env
9928sudo chmod 640 /etc/dbbasic-object-server.env
9929```
9930
9931## Filesystem Check
9932
9933The public package includes a small single-VM layout checker. Run it after
9934installing the server and after changing ownership or deployment paths:
9935
9936```bash
9937cd /opt/dbbasic-object-server
9938set -a
9939. /etc/dbbasic-object-server.env
9940set +a
9941.venv/bin/python -m deployment_checks
9942```
9943
9944The checker validates the normal Unix boundary:
9945
9946- server code under `/opt/dbbasic-object-server`
9947- live object source under `/var/lib/dbbasic-object-server/objects`
9948- runtime data under `/var/lib/dbbasic-object-server/data`
9949- deployment secrets under `/etc/dbbasic-object-server.env`
9950- systemd unit under `/etc/systemd/system/dbbasic-object-server.service`
9951
9952Errors should be fixed before exposing routes publicly. Warnings usually mean a
9953runtime path is visible to other local users. On a single-purpose staging VM
9954that may not break anything, but the safer default is `750` for object and data
9955directories.
9956
9957## Traffic Limits
9958
9959Keep the public server narrow while it is staging.
9960
9961`DBBASIC_MAX_REQUEST_BYTES` limits inbound HTTP request bodies before JSON
9962parsing or object execution. The default is 1 MiB:
9963
9964```text
9965DBBASIC_MAX_REQUEST_BYTES=1048576
9966DBBASIC_MAX_CONCURRENT_REQUESTS=64
9967DBBASIC_MAX_CONCURRENT_EXECUTIONS=8
9968```
9969
9970Configure the same or smaller request body limit in the reverse proxy so Caddy
9971or nginx can reject oversized traffic before Python handles it. The app-level
9972limit stays in place because proxy configuration can drift.
9973
9974The concurrency limits are per process. Under overload, the server returns
9975`503` rather than queueing unlimited work on a small VM. Future production
9976hardening still needs CPU/memory isolation.
9977`DBBASIC_OBJECT_TIMEOUT_SECONDS` runs object methods in a worker process and
9978returns `504` if the wall-clock timeout is exceeded. On its own that means a
9979new Python interpreter for every object call, including every page object and
9980site route. `DBBASIC_WORKER_POOL_SIZE` (default `0`, off) keeps that many warm
9981worker processes instead. Isolation, the `504` timeout and live source edits
9982are unchanged; the interpreter start-up cost is not paid per request. Start
9983with `2` on a small VM; each worker holds roughly 32 MB of RSS after serving a
9984page. Size it near the number of objects you expect to run at once, and keep it
9985at or below `DBBASIC_MAX_CONCURRENT_EXECUTIONS`. Measured numbers are in
9986[`traffic-limits.md`](/docs/traffic-limits#warm-worker-pool).
9987`DBBASIC_TRUSTED_IN_PROCESS_OBJECTS` is a comma-separated allowlist for
9988reviewed server-owned objects that should keep the fast in-process path, such as
9989the public homepage. Do not add user-created objects to this list.
9990The rate limit values above return `429` with `Retry-After` when one IP or
9991valid admin token exceeds the configured window.
9992`DBBASIC_RATE_LIMIT_TRUST_PROXY_HEADERS` is appropriate only because uvicorn is
9993bound to `127.0.0.1` behind Caddy.
9994
9995See [`traffic-limits.md`](/docs/traffic-limits) for the operating model.
9996
9997## Log Maintenance
9998
9999Object logs are part of the runtime feedback loop, so staging servers should not
10000let them grow forever.
10001
10002The active log for an object stays plain TSV:
10003
10004```text
10005/var/lib/dbbasic-object-server/data/logs/{object_id}/log.tsv
10006```
10007
10008When it reaches `DBBASIC_LOG_MAX_BYTES`, the server rotates it. New rotated logs
10009are gzip-compressed by default:
10010
10011```text
10012/var/lib/dbbasic-object-server/data/logs/{object_id}/log-YYYYMMDD-HHMMSS-ffffff.tsv.gz
10013```
10014
10015Inspect compressed logs without expanding a second copy:
10016
10017```bash
10018gzip -cd /var/lib/dbbasic-object-server/data/logs/site_home/log-*.tsv.gz
10019```
10020
10021Garbage collection is controlled by `DBBASIC_LOG_KEEP_ROTATED`. The default
10022keeps the newest 32 rotated files per object and deletes older rotated logs
10023after a successful rotation. Set it to `0` to keep all rotated logs.
10024
10025This is at-rest compression. For in-motion compression, start with reverse-proxy
10026HTTP compression for large log responses. Later station replication should
10027compress batches, not individual tiny events.
10028
10029Event rows are a delivery queue, not the durable audit log. The server and
10030daemon prune old `data/state/events/state.tsv` event rows with:
10031
10032```bash
10033DBBASIC_EVENT_KEEP_COUNT=1000
10034DBBASIC_EVENT_KEEP_SECONDS=604800
10035```
10036
10037Set either value to `0` to disable that retention rule. Subscriptions stay in
10038place, and any event referenced by a subscription `last_event_id` is protected so
10039the daemon keeps its delivery cursor. Failed delivery attempts are protected too,
10040so callback failures stay visible and retryable until delivery succeeds or the
10041subscription is repaired.
10042
10043## Packages
10044
10045Packages are read from `DBBASIC_PACKAGES_DIR`. The public server currently
10046supports package listing, dry-run planning, and package installs only when
10047`DBBASIC_ENABLE_PACKAGE_INSTALLS=true`. Dry-run and install requests append
10048compact audit rows under
10049`/var/lib/dbbasic-object-server/data/package_changes/{package_id}/changes.jsonl`.
10050Package installs create a runtime restore point before writing source, schema,
10051or seed files. Restore points default to
10052`/var/lib/dbbasic-object-server/data/backups/`; set `DBBASIC_BACKUPS_DIR` if
10053they should live on another mounted volume.
10054
10055Package restore is separate and requires `DBBASIC_ENABLE_PACKAGE_RESTORE=true`.
10056It restores a recorded install restore point with overwrite and snapshot
10057pruning, so package-created runtime files are removed if they were not in the
10058archive.
10059
10060Keep `DBBASIC_ENABLE_PACKAGE_INSTALLS=false` and
10061`DBBASIC_ENABLE_PACKAGE_RESTORE=false` on public staging unless `/packages` is
10062reachable only from a private admin surface. The first install path writes
10063objects and schemas, creates seed TSV files only when no data exists, and
10064rejects permissions/migrations until merge/run semantics are explicit.
10065
10066## Reactions and Scheduled Passes
10067
10068Installing a package does not by itself make its reactions run. Three
10069separate things have to be true, and a stock install has only some of them:
10070
10071- **Event handlers** (`HANDLES` objects: an invoice flipping to paid, a
10072 journal composing, a sale moving stock) run only when
10073 `DBBASIC_ENABLE_EVENT_HANDLERS=true` (writes made over HTTP) and/or
10074 `DBBASIC_ENABLE_CHANGE_DISPATCH=true` (the daemon replays the change log,
10075 which also reaches writes actions, runners and webhooks make at storage
10076 level -- a Stripe payment, a checkout, a shipment). Both default off.
10077 Turning them on is a deliberate act: read the open handler findings
10078 (tax basis, order totals) before you do. **Change dispatch starts from
10079 the moment its first pass runs**: writes made before then (payments that
10080 landed while the flag was off) are NOT dispatched, and the first pass
10081 says so -- `GET /daemon/status` carries `change_dispatch_baseline` and a
10082 `change_dispatch_skipped_history` warning with the count. To replay them,
10083 delete `.change_dispatch_cursor` in the data dir and start the daemon once
10084 with `DBBASIC_CHANGE_DISPATCH_FROM=beginning` (or an ISO timestamp). Read
10085 what your handlers do first: state-based reactions (invoice status, books,
10086 stock) are idempotent, but a replay queues an order email per order.
10087- **Scheduled passes** (invoice aging, recurring journals, the biller, the
10088 usage rollup, tracking polls, and the methods objects schedule for
10089 themselves with `_schedule`) run only in the daemon, `object_daemon.py`.
10090 `install.sh` installs and starts it as `dbbasic-object-daemon.service`
10091 (see ""systemd"" below); a hand-built VM needs that unit added.
10092- **Cron schedules** -- every schedule the shipped packages declare --
10093 need `croniter`, which is an optional extra (`scheduler`). `install.sh`
10094 installs it (`.[server,scheduler]`), and so does the one-click install,
10095 which runs `install.sh`. A hand-built VM installs it into the server's
10096 virtualenv with `pip install -e '.[server,scheduler]'`; a box installed
10097 before `install.sh` did so adds it the same way.
10098
10099None of this is silent any more. The server's startup log prints one
10100`[dbbasic] Reactions NOT RUNNING (...)` line per gap, naming the handler
10101objects or schedules affected and the setting that fixes it; the daemon's
10102boot banner prints a `Reactions:` block; and
10103`GET /daemon/status` reports `daemon.reactions` with `status`, the flags,
10104whether a daemon heartbeat (`data/.daemon_heartbeat`, touched every 30s
10105by a running daemon) is fresh, and a `problems` list
10106(`handlers_inert`, `storage_writes_unreacted`, `cron_needs_croniter`,
10107`daemon_not_running`). A cron task that cannot be scheduled also carries
10108the reason in its own `error` field (`GET /daemon/scheduler/tasks`) and is
10109logged as an ERROR once per daemon start.
10110
10111## Minimal Object
10112
10113Create one object so the VM can prove execution, state, and logs:
10114
10115```bash
10116sudo -u dbbasic mkdir -p /var/lib/dbbasic-object-server/objects/site
10117sudo -u dbbasic tee /var/lib/dbbasic-object-server/objects/site/home.py >/dev/null <<'PY'
10118def GET(request):
10119 count = _state_manager.get(""count"", 0) + 1
10120 _state_manager.set(""count"", count)
10121 return {
10122 ""status"": ""ok"",
10123 ""message"": ""DBBASIC Object Server is running"",
10124 ""count"": count,
10125 }
10126PY
10127```
10128
10129This object resolves as `site_home`.
10130
10131For a public staging page, the same object can return HTML instead of JSON:
10132
10133```python
10134def GET(request):
10135 count = int(_state_manager.get(""count"", 0)) + 1
10136 _state_manager.set(""count"", count)
10137 _logger.info(""site_home served"", count=count, response_type=""html"")
10138
10139 return {
10140 ""content_type"": ""text/html; charset=utf-8"",
10141 ""body"": f""<!doctype html><h1>DBBASIC Object Server</h1><p>Served {count} times.</p>"",
10142 }
10143```
10144
10145That keeps the staging page honest: it is a live object with state and logs, not
10146a static file.
10147
10148## Run Manually
10149
10150Before creating a service, run the server by hand:
10151
10152```bash
10153cd /opt/dbbasic-object-server
10154set -a
10155. /etc/dbbasic-object-server.env
10156set +a
10157.venv/bin/uvicorn object_server:app --host 127.0.0.1 --port 8001 --no-access-log
10158```
10159
10160In another shell:
10161
10162```bash
10163curl http://127.0.0.1:8001/health
10164curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/health?capacity=true'
10165curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" http://127.0.0.1:8001/objects
10166curl http://127.0.0.1:8001/objects/site_home
10167curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/objects/site_home?state=true'
10168curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/objects/site_home?logs=true'
10169```
10170
10171## systemd
10172
10173Create `/etc/systemd/system/dbbasic-object-server.service`:
10174
10175```ini
10176[Unit]
10177Description=DBBASIC Object Server
10178After=network-online.target
10179Wants=network-online.target
10180
10181[Service]
10182User=dbbasic
10183Group=dbbasic
10184WorkingDirectory=/opt/dbbasic-object-server
10185EnvironmentFile=/etc/dbbasic-object-server.env
10186ExecStart=/opt/dbbasic-object-server/.venv/bin/uvicorn object_server:app --host 127.0.0.1 --port 8001 --no-access-log
10187Restart=on-failure
10188RestartSec=2
10189NoNewPrivileges=true
10190PrivateTmp=true
10191ProtectSystem=full
10192ReadWritePaths=/var/lib/dbbasic-object-server
10193
10194[Install]
10195WantedBy=multi-user.target
10196```
10197
10198Start it:
10199
10200```bash
10201sudo systemctl daemon-reload
10202sudo systemctl enable --now dbbasic-object-server
10203sudo systemctl status dbbasic-object-server
10204curl http://127.0.0.1:8001/health
10205curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" 'http://127.0.0.1:8001/health?capacity=true'
10206```
10207
10208Watch logs:
10209
10210```bash
10211sudo journalctl -u dbbasic-object-server -f
10212```
10213
10214### The daemon unit
10215
10216The background daemon (`object_daemon.py`: scheduled tasks, including the
10217methods objects schedule for themselves with `_schedule`, the queue,
10218change dispatch, retention and cleanup passes) is a second unit with the
10219same user, code, env file and data directory, and no port. `install.sh`
10220writes it; on a hand-built VM create
10221`/etc/systemd/system/dbbasic-object-daemon.service`:
10222
10223```ini
10224[Unit]
10225Description=DBBASIC Object Server daemon (scheduler, queue, background passes)
10226After=network-online.target dbbasic-object-server.service
10227Wants=network-online.target
10228
10229[Service]
10230User=dbbasic
10231Group=dbbasic
10232WorkingDirectory=/opt/dbbasic-object-server
10233EnvironmentFile=/etc/dbbasic-object-server.env
10234ExecStart=/opt/dbbasic-object-server/.venv/bin/python object_daemon.py
10235Restart=on-failure
10236RestartSec=5
10237NoNewPrivileges=true
10238PrivateTmp=true
10239ProtectSystem=full
10240ReadWritePaths=/var/lib/dbbasic-object-server
10241
10242[Install]
10243WantedBy=multi-user.target
10244```
10245
10246```bash
10247sudo systemctl daemon-reload
10248sudo systemctl enable --now dbbasic-object-daemon
10249sudo journalctl -u dbbasic-object-daemon -f
10250```
10251
10252Run exactly one daemon per data directory: two would both run every due
10253task. Restart it alongside the server after an upgrade or an env change
10254(`sudo systemctl restart dbbasic-object-server dbbasic-object-daemon`).
10255
10256`--no-access-log` keeps successful request lines out of journald. DBBASIC keeps
10257the useful application trail in object logs and `/health?metrics=true`, which
10258are the surfaces Scroll should read. If access analytics are needed later,
10259build them as an explicit app/object instead of relying on raw process logs.
10260
10261Cap journald so process logs cannot consume the VM:
10262
10263```bash
10264sudo mkdir -p /etc/systemd/journald.conf.d
10265sudo tee /etc/systemd/journald.conf.d/99-dbbasic.conf >/dev/null <<'EOF'
10266[Journal]
10267SystemMaxUse=128M
10268SystemKeepFree=1G
10269MaxRetentionSec=7day
10270Compress=yes
10271EOF
10272sudo systemctl restart systemd-journald
10273sudo journalctl --vacuum-size=128M
10274sudo journalctl --disk-usage
10275```
10276
10277## Upgrade
10278
10279**Two different things live at `/opt` and two different things get served
10280at `/var/lib` — know which one you changed before declaring a deploy done.**
10281
10282Core server modules (`object_server.py`, `object_ai.py`, and every other
10283`.py` at the repo root) are imported directly from
10284`/opt/dbbasic-object-server` — the steps below are complete for these:
10285
10286```bash
10287cd /opt/dbbasic-object-server
10288sudo -u dbbasic git pull --ff-only
10289sudo -u dbbasic .venv/bin/python -m pip install -e '.[server,scheduler]'
10290sudo systemctl restart dbbasic-object-server dbbasic-object-daemon
10291```
10292
10293**Anything under `packages/<name>/` (objects, schemas, seed data) is
10294different.** The running server reads these from a separately *installed*
10295copy at `/var/lib/dbbasic-object-server/objects/` and
10296`/var/lib/dbbasic-object-server/data/schemas/` — `git pull` alone never
10297syncs into it, no matter how many times you restart. A `git pull`-only
10298""deploy"" of a `packages/` change is a silent no-op: the commit lands, the
10299tests pass, the service restarts clean, and the live server keeps running
10300the old code with no error anywhere. After the `git pull` above, also run:
10301
10302```bash
10303curl -s -X POST https://dbbasic.example.com/packages/app-shell/install \
10304 -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" -H 'Content-Type: application/json' \
10305 -d '{""allow_replace"": true}'
10306```
10307
10308To reinstall many packages (e.g. every one after an upgrade), take one
10309backup and have each install reuse it instead of writing a full archive per
10310package (about 237 MB each on a 3.3 GB data directory):
10311
10312```bash
10313BACKUP=$(curl -s -X POST https://dbbasic.example.com/admin/backups \
10314 -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" | python3 -c 'import json,sys; print(json.load(sys.stdin)[""backup""][""id""])')
10315for pkg in $(ls packages); do
10316 curl -s -X POST ""https://dbbasic.example.com/packages/$pkg/install"" \
10317 -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" -H 'Content-Type: application/json' \
10318 -d ""{\""allow_replace\"": true, \""restore_point\"": \""$BACKUP\""}""
10319done
10320```
10321
10322The loop's order does not matter. A package whose queues or doors are written
10323into another package's collection (app-nav's `attention_sources`) installs
10324cleanly even when that package is still the old release's, because those rows
10325are held back until `app-nav` is installed and refreshes its schema; `app-nav`
10326sorts late in this loop, so read `install.warnings` of the earlier installs as
10327""waiting for app-nav"", not as failures, and expect `registered_for_others` in
10328the app-nav response. The release gate's `upgrade` stage (`CONTRIBUTING.md`)
10329runs exactly this loop from the previous tag.
10330
10331(swap `app-shell` for whichever package changed; `DBBASIC_ENABLE_PACKAGE_INSTALLS`
10332must be `true`). Check the response's `install.objects[].status` — `""updated""`
10333means a real change landed, `""unchanged""` means nothing to sync. Read
10334`install.permission_retractions` too: it lists every permission rule the
10335install removed because the package withdrew it, and every rule it left in
10336place for you to decide about (`GET /permissions/unshipped` shows those for
10337the whole box; see ""Package Rules And Upgrades"" in
10338[`permissions-model.md`](/docs/permissions-model)). A package's tightened
10339permission rules do not reach a running box until it is reinstalled. A schema-only
10340change can also go straight to `PUT /admin/schemas/{collection}` with the
10341updated schema JSON, same admin-token gate. Either way, **restart the
10342service afterward** — object modules are cached in the running process, so
10343even a correctly-installed file has no effect until the next restart clears
10344that cache:
10345
10346```bash
10347sudo systemctl restart dbbasic-object-server dbbasic-object-daemon
10348```
10349
10350To confirm a `packages/` deploy actually landed rather than trusting the
10351install response alone, diff the live file against the source directly:
10352
10353```bash
10354diff /var/lib/dbbasic-object-server/objects/site/<name>.py \
10355 /opt/dbbasic-object-server/packages/<pkg>/objects/site/<name>.py
10356```
10357
10358A non-empty diff means the install step (or the restart) didn't happen yet.
10359
10360Then verify the local service, filesystem layout, public proxy, and deployed
10361commit:
10362
10363```bash
10364cd /opt/dbbasic-object-server
10365set -a
10366. /etc/dbbasic-object-server.env
10367set +a
10368.venv/bin/python -m deployment_checks
10369curl http://127.0.0.1:8001/health
10370curl https://dbbasic.example.com/
10371sudo systemctl is-active dbbasic-object-server caddy
10372sudo -u dbbasic git rev-parse --short HEAD
10373```
10374
10375If the upgrade only changes live objects that were edited **directly**
10376under `/var/lib/dbbasic-object-server/objects` (not via a `packages/` git
10377change), the server should not need a git deploy at all. That is the
10378object loop: edit one object, run it, inspect state/logs, and keep the
10379version trail. This is a third, separate path from both cases above — it
10380never touches `/opt` or git at all.
10381
10382## HTTPS Proxy
10383
10384For a public or staging hostname, put Caddy or nginx in front of uvicorn and keep
10385uvicorn bound to `127.0.0.1`.
10386
10387Install Caddy if the VM does not already have a reverse proxy:
10388
10389```bash
10390sudo apt install -y caddy
10391```
10392
10393Example Caddyfile using documentation domains:
10394
10395```caddyfile
10396dbbasic.example.com {
10397 reverse_proxy 127.0.0.1:8001
10398}
10399```
10400
10401Replace `dbbasic.example.com` only on the VM. Do not commit real deployment
10402hostnames into this repository.
10403
10404If Caddy was already installed, inspect what it is serving before taking over
10405the hostname:
10406
10407```bash
10408sudo systemctl status caddy --no-pager
10409sudo sed -n '1,220p' /etc/caddy/Caddyfile
10410sudo find /usr/share/caddy -maxdepth 3 -type f -printf '%p\t%s bytes\n'
10411```
10412
10413Back up the old config before changing it:
10414
10415```bash
10416sudo cp -a /etc/caddy/Caddyfile /etc/caddy/Caddyfile.before-dbbasic
10417```
10418
10419For the earliest public staging endpoint, expose only the hello object, system
10420dashboard object, admin status and admin inspection routes, health check, and
10421current-session self-service route until auth, permissions, and source
10422visibility are ready. Keep the broad `/objects` listing blocked:
10423
10424```caddyfile
10425dbbasic.example.com {
10426 handle / {
10427 rewrite * /objects/site_home
10428 reverse_proxy 127.0.0.1:8001
10429 }
10430
10431 handle /health {
10432 reverse_proxy 127.0.0.1:8001
10433 }
10434
10435 handle /login {
10436 reverse_proxy 127.0.0.1:8001
10437 }
10438
10439 handle /logout {
10440 reverse_proxy 127.0.0.1:8001
10441 }
10442
10443 # only when signup / password reset are turned on
10444 handle /signup {
10445 reverse_proxy 127.0.0.1:8001
10446 }
10447
10448 handle /verify {
10449 reverse_proxy 127.0.0.1:8001
10450 }
10451
10452 handle /reset* {
10453 reverse_proxy 127.0.0.1:8001
10454 }
10455
10456 handle /admin/status {
10457 reverse_proxy 127.0.0.1:8001
10458 }
10459
10460 handle /admin/changes* {
10461 reverse_proxy 127.0.0.1:8001
10462 }
10463
10464 handle /admin/objects* {
10465 reverse_proxy 127.0.0.1:8001
10466 }
10467
10468 handle /admin/files* {
10469 reverse_proxy 127.0.0.1:8001
10470 }
10471
10472 handle /admin/collections* {
10473 reverse_proxy 127.0.0.1:8001
10474 }
10475
10476 handle /admin/schemas* {
10477 reverse_proxy 127.0.0.1:8001
10478 }
10479
10480 handle /admin/identity* {
10481 reverse_proxy 127.0.0.1:8001
10482 }
10483
10484 handle /permissions/status* {
10485 reverse_proxy 127.0.0.1:8001
10486 }
10487
10488 handle /permissions/policy* {
10489 reverse_proxy 127.0.0.1:8001
10490 }
10491
10492 handle /daemon/status {
10493 reverse_proxy 127.0.0.1:8001
10494 }
10495
10496 handle /daemon/scheduler/tasks* {
10497 reverse_proxy 127.0.0.1:8001
10498 }
10499
10500 handle /daemon/queue/messages* {
10501 reverse_proxy 127.0.0.1:8001
10502 }
10503
10504 handle /events* {
10505 reverse_proxy 127.0.0.1:8001
10506 }
10507
10508 handle /packages* {
10509 reverse_proxy 127.0.0.1:8001
10510 }
10511
10512 handle /api/mcp {
10513 reverse_proxy 127.0.0.1:8001
10514 }
10515
10516 handle_path /static/* {
10517 root * /var/lib/dbbasic-static
10518 file_server
10519 header Cache-Control ""public, max-age=3600""
10520 }
10521
10522 handle /permissions/audit* {
10523 reverse_proxy 127.0.0.1:8001
10524 }
10525
10526 handle /dashboard {
10527 rewrite * /objects/system_dashboard
10528 reverse_proxy 127.0.0.1:8001
10529 }
10530
10531 handle /admin/write-probe {
10532 rewrite * /objects/system_write_probe
10533 reverse_proxy 127.0.0.1:8001
10534 }
10535
10536 handle /collections/dbbasic_probe/records* {
10537 reverse_proxy 127.0.0.1:8001
10538 }
10539
10540 handle /collections/dbbasic_probe/changes {
10541 reverse_proxy 127.0.0.1:8001
10542 }
10543
10544 handle /schemas/dbbasic_probe {
10545 reverse_proxy 127.0.0.1:8001
10546 }
10547
10548 handle /identity/session {
10549 reverse_proxy 127.0.0.1:8001
10550 }
10551
10552 # This exposes GET/DELETE current-session checks. POST password login works
10553 # when DBBASIC_ENABLE_PASSWORD_LOGIN=true; the gateway session-mint POST
10554 # remains disabled unless DBBASIC_ENABLE_SESSION_LOGIN=true and
10555 # DBBASIC_SESSION_LOGIN_TOKEN are set.
10556
10557 handle /objects/site_home* {
10558 reverse_proxy 127.0.0.1:8001
10559 }
10560
10561 handle {
10562 respond ""Not found"" 404
10563 }
10564}
10565```
10566
10567Validate and reload:
10568
10569```bash
10570sudo caddy fmt --overwrite /etc/caddy/Caddyfile
10571sudo caddy validate --config /etc/caddy/Caddyfile
10572sudo systemctl reload caddy
10573```
10574
10575Then test:
10576
10577```bash
10578curl https://dbbasic.example.com/
10579curl https://dbbasic.example.com/health
10580curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/status
10581curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/collections
10582curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/schemas
10583curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/admin/identity/users
10584curl -H ""Authorization: Token $DBBASIC_ADMIN_TOKEN"" https://dbbasic.example.com/daemon/status
10585curl https://dbbasic.example.com/objects/site_home
10586curl https://dbbasic.example.com/admin/write-probe
10587curl https://dbbasic.example.com/objects
10588```
10589
10590The first six should return responses from the object server. The root and
10591`site_home` responses may be JSON or HTML depending on the object. The full
10592`/objects` route should stay blocked by Caddy in this early staging mode.
10593
10594The `admin-write-probe` package may also expose the narrow
10595`/collections/dbbasic_probe/records*`, `/collections/dbbasic_probe/changes`,
10596and `/schemas/dbbasic_probe` routes. Those routes are still protected by the
10597server-side admin-token gate. They exist to prove collection create/update/
10598delete behavior, record changelog reads, and schema reads through the public
10599reverse proxy without exposing every collection or schema route. Do not expose
10600broad `/collections*`, `/schemas*`, `/objects*`, or source write routes on a
10601public staging server. Use `/admin/collections*` and `/admin/schemas*` for
10602operator inspection instead. Use `/admin/identity*` for read-only account, user,
10603and session inspection instead of exposing broad identity management routes.
10604
10605## Public Code Execution Controls
10606
10607In the early staging deployment, do not expose the full object server API
10608directly to the internet.
10609
10610Use all of these controls together:
10611
10612- keep uvicorn bound to `127.0.0.1`
10613- expose only specific routes through Cadd
Only the first 512 KB is shown. Download the zip for the whole file.