Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
Package Authoring
This is the practical guide for building a DBBASIC package: one installable directory that ships an app piece — objects, schemas, and seed data — without a deploy pipeline. It is written for humans and AI tools that generate packages. The runtime contract details live in runtime-contract.md#packages; this page is the authoring workflow.
Find Your Task
| I want to... | Go to |
|---|---|
| upgrade a package without losing data, and test it | Upgrading a package |
| know what a field permission does on a write | permissions-model.md |
| start a new package that already works | Start from a scaffold (scripts/new_package.py) |
| check a change as different people, with permissions enforced | Try Your Change (scripts/try_package.py) |
| see which rows and labels a page would list for someone | Try Your Change, --rows |
| let a role read every row while only owners write | Recipes |
| let staff enter records owned by members, donors or patients | permissions-model.md ("on_behalf": true) |
| make a person's records show up in a subject access export | Personal data ("subject") |
| count "my queue" on the menu or home page | Recipes, Attention |
| freeze fields once a record is settled | Recipes |
| add a field and show it in a list | Recipes |
| make a value unique, required only in some state, or bounded | Add a field links each rule |
| compare a datetime with now in a check (aware or naive, UTC, unparseable values) | Comparing a datetime with now |
| refuse a write on the date, on another field, or on another collection | What can't be declared |
| require a field when a row of another collection says so (a category, a type) | A requirement another collection decides |
| see a whole app built that way (expenses, mileage, a register) | expense-substantiation.md |
| change a page or route I already shipped | Changing a seeded row in a new version |
decide what to bump in version | Which version to bump |
know why an integer comes back as "4" | What a record looks like on the wire |
| my test failed after I added a field, a dependency or a version | A failing pin on a pure addition is a test bug |
| install, dry-run, restore | What install does, Authoring workflow |
What A Package Is
A package is a directory under packages/ (or DBBASIC_PACKAGES_DIR) with a manifest and package-relative content:
packages/{package_id}/
dbbasic-package.json
objects/ # object source files
schemas/ # collection schema JSON files
seed/ # initial records, TSV files (new ids are added on every install)
permissions/ # rule fragments: merged into the deployment policy on install
migrations/ # declared, not run: install refuses a package that lists any
permissions/ is installed: each file is {"rules": [...]}, and install validates the rules, tags them with this package's id and appends the ones the policy does not already hold (What install does has the detail, including how a rule is retired). seed/ is merged by record id, not written once (same section).
A good package is one app primitive: contacts, notes, tasks, articles, invoices. Small enough to review, complete enough to install and use.
The Manifest
dbbasic-package.json is plain JSON:
{
"dron": "0.2",
"id": "contacts",
"name": "Contacts",
"version": "0.1.0",
"description": "Contact records with a browse/edit page",
"compatibility": {"dbbasic_object_server": ">=0.1.0"},
"dependencies": [],
"objects": [
{"id": "contacts_directory", "path": "objects/contacts/directory.py"}
],
"schemas": [
{"collection": "contacts", "path": "schemas/contacts.json"}
],
"seed": [
{"collection": "contacts", "path": "seed/contacts.tsv"}
],
"permissions": [],
"migrations": [],
"schedules": [
{"id": "contacts_dedupe_nightly",
"object_id": "contacts_directory",
"schedule": "10 6 * * *",
"description": "Flag likely duplicate contacts overnight."}
],
"nav": [
{"id": "contacts", "label": "Contacts", "path": "/contacts",
"blurb": "People, the organizations they belong to, and interactions",
"surface": "member", "group": "Work", "order": 60}
]
}
Rules the server enforces:
idmust be a safe package identifier; object ids and collection names are
validated with the same rules as the rest of the server.
- All paths are package-relative. Absolute paths, null bytes, and
..
traversal are rejected at parse time.
dron(optional) names the DRON version the package was written for, as
"MAJOR.MINOR" text. A server installs it if it reads that version or a later minor of the same major; a later minor, another major, or a value that is not "MAJOR.MINOR" text refuses the install (and the dry run) before anything is written, naming the version asked for and the version the server reads: Package app-tickets dbbasic-package.json: the package was written for DRON 0.3 and this server reads DRON 0.2, ...; upgrade the server .... Leave it out and the package installs as it always did. The scaffold writes the server's version. See dron.md.
- A key DRON does not define refuses the install. A misspelt section
(schedule for schedules), a nav entry's lable, a schema field's requird or a rule's row_filtr is refused when the package is loaded, before anything is written, and the message names the file, the entry or rule, the key and the closest spelling: Package permission rule is invalid: permissions/rules.json rule 3: unknown key 'row_filtr' (did you mean 'row_filter'?). (Until this was tightened such a key was dropped and the install succeeded; a rule whose row_filter was misspelt covered every row.) The same goes for values the loader used to coerce or re-case ("required": "no", a text version, "nav_optional": "no", "type": "Integer", "effect": "Allow", "surface": "Public"), for an unknown field type, and, in permission rules and transition guards, for an unknown action, principal, operator or $-variable ($userid) and a boolean filter value (write "true"). The engine-only synonyms (readonly, readOnly, computed: true, validation.regex, validation.required, validation.choices, validation.in, {"values": [...]}) are refused with the DRON spelling. So are values that used to install and then fail the first write or render that touched them, or do nothing: a validation.min or max that is not a number, a field permissions level other than edit, read or hidden (write and readonly are the engine's spellings, not DRON's), a relation with no collection, a formula or rollup on a field that is not "type": "computed", a rollup with no collection, fk_field or op, an op other than sum, count, min, max or avg, or an op other than count with no field, a hooks.before_write that is not an object id, and a views.list_mode other than table, board, tree, calendar, cards or feed: Package schema is invalid: schemas/orders.json: orders: views.list_mode 'grid' is not a list mode; write one of table, board, tree, calendar, cards or feed. Schemas already stored on a box, ones saved through the schema API, and the deployment's own policy file are read as before: only a package declaration is held to DRON. The DRON JSON Schema, below, catches the same mistakes earlier, in your editor or through tests/test_dron_schema.py, which validates every shipped manifest, schema and rules file against it (it needs no jsonschema package; it carries its own small validator). A package of your own is checked the same way once it sits under packages/: python -m pytest tests/test_dron_schema.py -k your-package-id. The dry run (GET /packages/{package_id}?dry_run=true) lists a refused declaration in its warnings, with the same reason, before you install.
What Install Actually Does Today
Installs are deliberately conservative:
objectsentries are written under the configured objects root. Existing
objects require allow_replace.
schemasentries are validated and written underdata/schemas/. Existing
schemas require allow_replace; with it, an unedited schema is replaced (updated), and one an operator has customised is merged field by field (merged) or parked as a conflict to resolve. See What a schema's version does.
seedTSV is merged byid: a collection with no records takes the
whole file; a collection that already holds records gets only the seed rows whose id it does not have (reported status: "merged", or "skipped" when nothing was new). A row that is already there is never overwritten with something an operator changed, so a reinstall never destroys live data and never blocks the install. A column the package itself changed in the new version, and nobody has edited since the install wrote it, is refreshed; an edited one is kept and reported (replaced / kept on the seed entry): see Changing a seeded row in a new version. A row the collection refuses (a unique key live data already holds, a value its schema rejects) is listed under rejected in the result and the rest still merge. This is what makes an in-place upgrade safe: reinstall with allow_replace to ship new object code, a migrated schema, and re-merged permissions while every existing record is preserved. Live records live outside the package, in data/collections/<name>/records.tsv keyed by collection, so an upgrade has no reason to touch them. (Evolving a schema across an upgrade — backfilling a newly added field on old rows — is the separate migrations story below, not yet implemented; adding a field is safe because old rows simply read as empty for it, and a default applies to rows written from then on, not to old ones.)
permissionsentries MERGE: each fragment file is
{"rules": [ ... ]} using the same rule shape as the policy document (effect, principal, actions, optional collection/object_id, row filters, field lists). On install the rules are validated, stamped with "package": "<package_id>" provenance, and appended to the deployment policy — skipping any rule that already exists, so reinstalls are idempotent. This is how a site package makes its own pages public: ship the grant with the code instead of hand-editing policy after install. Invalid fragments block the whole install.
- **Deleting or changing a rule is a retirement, and an upgrade performs
it.** Two rules are the same rule when everything but reason matches, so adding a row filter to a grant, or dropping an action from it, ships a NEW rule and withdraws the old one. Every install records the rules the package shipped (permissions in data/package_baselines/<id>.json); the next install removes from the policy any rule that is in that record, is no longer shipped, and is still tagged as this package's. Nothing to write: delete the rule from rules and it goes on upgrade.
A box installed before 2026-11-28 has no such record, so for it (and for any rule you want gone whatever the box's history) list the withdrawn rule in the fragment's optional retracted array, in the same shape, with a reason that says why it was withdrawn:
{
"retracted": [
{"effect": "allow", "principal": "registered", "actions": ["read"],
"collection": "template_runs",
"reason": "replaced by the owner-filtered read"}
],
"rules": [ ... ]
}
When you delete or tighten a shipped rule, add the old rule to retracted in the same commit and leave it there: it is how every older install finds out. A rule may not be in both lists (the install is refused). tests/test_package_permission_retraction.py reads this checkout's git history and fails, printing the entries to paste, when a rule that was once shipped is neither shipped nor retracted.
Either way a live rule is removed only if it is tagged as this package's AND identical to the withdrawn one. A rule the operator edited no longer matches and a rule the operator wrote has no tag; both stay, and the install reports them (permission_retractions in the dry run and the install response; removed rules are kept whole in the package change log). GET /permissions/unshipped lists every rule in the policy that no installed package ships. See "Package Rules And Upgrades" in permissions-model.md.
- A grant you leave out is not a refusal for the row's owner. With no
rule matching, the engine's owner fallback lets whoever owner_id, user_id or created_by names read, update and delete the row. If the people a collection's rows belong to must not change or remove them (a ledger, a log, a run history, anything whose rule says "no delete"), ship the rule that says so:
{"effect": "deny", "principal": "owner_fallback",
"actions": ["update", "delete"], "collection": "wallet_entries",
"reason": "the ledger is the balance: entries are never edited or deleted"}
It switches the fallback off and nothing else: your explicit grants still grant, admins and in-process writers are unaffected. Details and where the fallback reaches: "Ownership" in permissions-model.md. tests/test_owner_fallback_opt_out.py fails until a new collection whose owners get update or delete from the fallback alone is either opted out, granted explicitly, or listed there as a deliberate decision.
migrationsare accepted in the manifest and reported in dry-runs, but
install rejects them until explicit run semantics land.
schedulesbecometask_<id>rows in the scheduler trigger's state,
which is where object_daemon.process_scheduler reads the board from. If your app needs a recurring pass, declare it here. A schedule that exists only in a running server's state is invisible to review, absent from a fresh install, and gone the next time the box is rebuilt — that is precisely how a demo server ended up with four nightly passes that appeared nowhere in this repository. Fields: id (becomes the state key, [a-z][a-z0-9_]*), object_id, schedule, and optional type (cron — the default — or onetime), method (default POST), payload, description.
Three properties make declaring a schedule safe to do repeatedly:
- Run history survives.
last_run,run_countandnext_run
belong to the daemon and are never reset by an install. An upgrade
that forgot when a pass last worked would make "is this actually
running?" unanswerable.
- A pause is honoured. The package declares what should run; an
operator decides what *does* right now. A reinstall never restarts a
task somebody deliberately paused.
- A changed expression reschedules. Editing the cron clears
`next_run` so the daemon recomputes it; leaving it alone keeps
tonight's firing exactly where it was, so shipping a patch does not
skip a run.
Two things are refused outright, at install time rather than at 3am: an unparseable cron (the daemon reads that as "no next run" and moves on in silence — a pass that never runs and never complains), and a schedule aimed at an object neither this package nor the server provides. Removing a schedule from a manifest does not delete the task, matching the rest of install: deregistering never destroys.
naventries become rows in thenav_entriescollection, which every
navigation surface folds over. If your app serves a page, declare its door here. See the section below.
attentionentries become rows in theattention_sourcescollection,
which the daemon's rollup pass reads its list of providers from. If your app has a queue that waits on a person, declare it here. See the section below.
- The HTTP install route creates a restore point first and appends changelog
rows under data/package_changes/{package_id}/changes.jsonl.
Navigation (nav)
A menu maintained by hand rots the moment somebody ships without editing it, and the rot is invisible — nothing fails, the front door just advertises a server that no longer exists. This repository had three such lists of the same apps: the app switcher's JS array in site_nav (25 entries), the home page's tile grid in site_home (21), and a collection-to-URL map for search hits. They disagreed with each other and between them named none of the eight newest apps. Worse, site_home existed in no package at all — it lived only on a running server, so a rebuilt box came back with no front door and said nothing about it, which is precisely the failure the schedules section was built to end for cron.
So a door is declared by the app that owns it, and every navigation surface becomes a fold over one registry:
"nav": [
{"id": "shop", "label": "Shop", "path": "/shop",
"blurb": "Browse what is for sale and buy it",
"surface": "public", "group": "Commerce", "order": 400}
]
idbecomes thenav_entriesrecord id, so[a-z][a-z0-9_]*. It must
be unique across every installed package: two packages writing one row is two packages fighting over one door.
labelandpathare required.pathstarts with/and holds no
whitespace.
blurbis one honest line in the present tense saying what the app
does — it is rendered under the label on the home grid. No marketing.
surfaceispublic|member|operator|hidden, default
member. This governs the MENU and is not access control: permissions decide who may open a page, and leaving a door off the menu hides nothing that was not already protected. /shop and the public product/pay/portal pages are public; ordinary app pages are member; /scheduler, /flow, /urls, /dashboard and other admin or debug pages are operator.
groupis free text, defaultApps. The house groups are Work,
Publishing, Money, Commerce, Warehouse and System.
orderis an integer, default100. Packages band it by group (Work
in the 0s, Publishing the 200s, Money the 300s, Commerce the 400s, Warehouse the 500s, System the 600s) because a group sorts where its earliest entry sorts — that way the reading order of the groups falls out of the same number, instead of a seventh list holding it.
Three properties make declaring a door safe to do repeatedly:
- The operator's
hiddensurvives.operator_hiddenis a separate
boolean column and an install never writes it on an existing row. The package says what the app IS; the operator says what they want to SEE. An upgrade that silently put back a page somebody deliberately removed would be the same class of incident as one that restarts a paused nightly pass — so an operator flips operator_hidden (a role:manager update on nav_entries) instead of editing somebody else's manifest.
- Unchanged means unwritten. Every package-owned field — label, path,
blurb, group, surface, order — is compared before anything is written, so a plan that reports unchanged is one where nothing at all is about to happen. A dry run that under-reports is worse than no dry run.
- Removing an entry does not delete the row. Same as the rest of
install: deregistering never destroys.
Two things are refused, and one deliberately is not:
- A duplicate id inside one manifest, and an **invalid surface, path
or order**, fail at parse time.
- A collision with another package blocks the install: an id already
registered by a different package, or a path a different package already claims. Whichever installed last would otherwise silently win, and the loser's menu entry would point somewhere its own package never chose.
- Whether a path is actually served is NOT checked. Routing has three
sources (convention, site_routes records, views records) and two of them are data the same install may be about to seed, so resolving a route here would produce false blockers. The registry records the door the package intends; /urls is where you go to see what the server actually answers.
If the nav_entries collection does not exist yet (app-nav is not installed), nav entries (and attention sources) are reported as skipped with a reason and the install proceeds, with a line in the result's warnings saying they were NOT registered. A package must never fail because the navigation app is absent, and install order does not matter: the install records what the package declared (in its baseline), and installing app-nav registers the nav entries and attention sources of every package already installed, listed in its result as registered_for_others. Only missing rows are written, as their own package's; an existing row (an operator's operator_hidden or operator_muted, another package's id) is left as it is. A box installed before declarations were recorded falls back to the package's manifest, only when that is the installed version, and otherwise names the package in warnings (reinstall it). tests/test_install_order_nav.py checks both orders.
The same holds on an upgraded box whose app-nav is still the previous release's. Its installed attention_sources schema can be older than the one this tree ships (before declared counts it required object_id), and a row written under the old schema would be refused, failing the install of the package that declares the count. An install that finds the owner's installed schema behind the one in this tree does not write those attention rows: they are skipped with stale_schema_owner naming the package, the install succeeds, and warnings says the rows wait for it. Installing app-nav refreshes the schema and registers them (registered_for_others). A real validation error against a current schema still refuses the install. tests/test_install_order_after_upgrade.py installs app-nav from the previous tag, then a package from this tree.
Depend on app-nav
The rule: a package that declares nav or attention lists "app-nav" in dependencies. The installer does not resolve dependencies (it records them), but scripts/try_package.py installs a package's dependencies first, so the declaration makes app-nav land first and the entries land with the package itself; it also tells a reader what the package needs. scripts/new_package.py writes it. It is a "should", not a "must": nothing refuses a manifest without it, because install must never fail on the navigation app's absence, and an app-nav installed later registers the entries anyway (above). Most of the packages shipped before this rule was written do not declare it (a gap the next version bump of each is the time to close, not a reason to copy it).
The opt-out
tests/test_package_nav.py asserts that every package shipping a site_* object or a site_routes seed declares at least one nav entry. That test is the thing that stops the drift coming back. Some packages legitimately serve a URL that is not a door — a mounted widget (site_thread, site_share), a fragment inside another page (site_materialize_run_button), a POST endpoint (site_timer_actions), or a per-record document reached from the record itself (site_packing_slip, site_receiving_sheet, site_return_form). Those declare:
"nav_optional": true
which makes "this app has no front page" a reviewable claim in the manifest rather than an omission nobody notices.
Attention (attention)
A menu answers "where can I go". The only question a home screen is actually asked is does anything need me?, and this server is unusually well placed to answer it, because it is built almost entirely out of gates and derived states. Every one of them produces a queue of things a machine deliberately refused to decide: scans sitting at extracted waiting to be confirmed into expenses, time entries submitted waiting for an approver who is by design not the person who logged them, invoices past their due date, bank lines nothing matched, POs a supplier shorted, orders committed and not yet in a box, returns that arrived and were never judged.
The system already computes all of it, on a schedule, and throws it away at the end of each pass. system_scan_processor has been returning a field literally named needing_a_human since the day it was written and no surface has ever read it. The arithmetic was never missing; a place to declare that the arithmetic means something was — and that declaration can only honestly live in the package that owns the domain, because nobody else knows that extracted is a waiting room and confirmed is not.
So it is declared, third use of the pattern that already fixed cron (schedules) and navigation (nav):
"attention": [
{"id": "orders_to_pick", "object_id": "system_order_attention",
"reads": ["orders", "order_lines", "shipments", "shipment_lines"],
"label": "Orders to pick", "path": "/orders",
"nav_id": "orders", "group": "Commerce", "severity": "normal"}
]
Or, when the queue is "rows of one collection in a waiting state" (it usually is), declare the count instead of writing a provider — see Declared counts:
"attention": [
{"id": "scans_to_confirm", "collection": "scans",
"where": {"status": "extracted"},
"detail": {"op": "count",
"where": {"created_at": {"op": "older_than_days", "value": 7}},
"text": "{value} over a week old"},
"label": "Receipts to confirm", "path": "/scans",
"nav_id": "scans", "group": "Money", "severity": "normal"}
]
idbecomes theattention_sourcesrecord id, so[a-z][a-z0-9_]*,
and it must be unique across every installed package.
object_idnames the provider (below), orcollectionnames the
collection a declared count reads — exactly one of the two. Checked: a counter aimed at an object (or a collection) neither this package nor the server provides blocks the install, exactly as a schedule does. A counter pointing at nothing reads zero forever, and a queue that reads zero forever is indistinguishable from a queue that is empty — the silent failure this whole section exists to end.
reads(providers only) lists the collections the provider folds its
number from. The number is computed with no viewer, so it is shown only to a viewer who may read every row of each listed collection the box has — see Who sees a provider's number. Leave it out and only admins see the count.
labelis what a person calls the queue, in their words: "Receipts to
confirm", not "scans.status=extracted".
pathis where the count clicks through to. Required, starts with/,
no whitespace. A number that cannot be acted on in one click does not belong on a home page. Whether anything actually serves the path is not checked, for the same reason nav does not check it.
nav_idis optional: thenav_entriesrow this count decorates, so the
app list itself reads "Invoices — 5 overdue" with no second surface to maintain. Omit it when the package ships no door at all (app-intake). Two queues may name one door, and its badge is their sum: a person with one deal they own and one assigned to them, as two sources on nav_id: "deals", sees 2 on the Deals entry (the entry's severity is the loudest of the two and its detail joins theirs). Before 2026-11 the louder queue won and the other was silently dropped. Each queue still has its own row, with its own count, in attention. Because they are added, a row that matches both queues is counted twice on the badge: make the queues disjoint, or put the union in one provider.
groupis free text, defaultApps, and uses the same house groups as
nav.
severityisnormal|warning|urgent, defaultnormal, and is
the first sort key on the home band. normal is work waiting; warning is work that is already late (an overdue invoice); urgent is something broken (a scheduler pass that failed). Three steps, because a scale with more is a scale nobody calibrates.
Declared counts (collection + where)
Ten of the first sixteen providers were the same fifteen lines: read one collection, keep the rows in the waiting state, return len() and a sentence. A declaration says that instead, and object_attention.count is the one function that evaluates every declaration.
whereis the permission row-filter language, the same one a
rule's row_filter uses and object_permissions.record_matches_filter decides — not a second one. Each value is a literal (eq), a $-variable, one {"op", "value"} condition (eq, ne, in, gte, lte, gt, lt), or a list of conditions ANDed. Membership is {"op": "in", "value": ["unmatched", ""]}; a bare list is refused, because in a row filter it is not membership. "Not one of these" is a list of ne conditions.
- One operator is added, for attention only: `{"op":
"older_than_days", "value": 7}, which is **inclusive**: a row matches when its age is 7 or more days (age >= 7). A YYYY-MM-DD value is aged in calendar days against the server's local date; any other value is an ISO datetime (Z accepted, naive read as UTC) aged in elapsed whole days. An empty or unparseable value is never older than anything. "Due before today" is {"op": "older_than_days", "value": 1}` on a date.
- Its threshold may be a setting: `{"op": "older_than_days", "value":
{"setting": "carrier.stuck_days", "default": 10}} reads the first app_settings row with exactly that key and a non-blank value, once per count, through the key index. A value that is not a whole number of days ≥ 0 (soon, 7.5, -3`), or a box without app-settings, reads as the default. That is the only thing a declaration reads from settings: a number of days, by key — never an expression.
- At least one literal equality is required (
"status": "submitted",
or in). The rows are fetched through the records cache's field index on it, so counting costs the queue, not the collection. A where made only of ne / ranges is refused at install.
- "My own rows" is
$user_id— `{"status": "draft", "owner_id":
"$user_id"}` — resolved for the viewer. There is no separate scope switch.
detail is optional: one part, or a list of parts joined with ", ".
| Part | Value |
|---|---|
{"op": "count", "where"?: {...}, "text": "{value} over a week old"} | the counted rows, or those also matching where |
{"op": "sum", "field": "amount_cents", "format"?: ..., "text": ...} | an integer field summed; an unparseable cell adds 0 |
{"op": "max_age_days", "field": "requested_on", "text": "oldest {value} days"} | the oldest dated row's age; undated and future rows add nothing |
A part whose value is 0 is left out unless it says "show_zero": true; a max_age_days with no dated rows is always left out. {value} is optional: a text without it is a fixed sentence shown exactly when the part would have been ({"op": "count", "text": "failed 3 or more syncs in a row"}). format (sums only): integer (default), cents (1,234.56), dollars ($1234.56), hours (seconds as hours, one decimal). Integer arithmetic throughout.
Booleans need no case-insensitive operator. The write path stores a boolean field as exactly true or false (or blank), so "enabled, where blank means enabled" is {"op": "in", "value": ["true", ""]} and "failed" is "ok": "false". "Not one of these" over an enum that must also serve as the index is the complement written out — "status": {"op": "in", "value": ["sent", "partial", "overdue", ""]} — with a test that the list plus the excluded values is the enum plus blank, so a value added to the enum later fails a test instead of silently dropping out of the count (tests/test_app_invoices_package.py).
Counted for the viewer, through the permission engine. A declared count is the number of matching rows the person looking may read (object_access.Access.visible, the same per-row question the record API asks), and the detail is computed over the same rows. An admin sees the whole queue; a manager whose rule grants the collection sees the rows that rule grants; a member with an owner-filtered read sees their own; someone with no grant sees nothing. It fails closed wherever object_access does: no identity, an unreadable policy. Project and share grants count, as they do for the record API.
Counted from the fields the viewer may read, when permissions are enforced (DBBASIC_ENABLE_PERMISSION_ENFORCEMENT). Reading a row is not reading all of it: a rule's fields / denied_fields or a schema field's permissions can hide a field from someone who reads the row. Each row is therefore judged as the record API would serve it to the viewer (object_access.Access.readable), and:
- a
wherecondition on a field the viewer cannot read in a row is
false for that row, whatever the operator (ne included). The count becomes "rows where this field, which you can see, matches": a support agent who reads every ticket but not salary_band sees 0 for a queue declared "where": {"status": "open", "salary_band": "A"}, not the number of band-A tickets. If a queue is meant for people who cannot read the field it filters on, filter on a field they can read;
- a
sumormax_age_daysadds nothing from a row whosefieldthe
viewer cannot read, and a detail part's own where follows the rule above. When a field is hidden on some rows only (a field hidden from the row's owner), the sentence covers the rows where it is readable;
- a detail part that depends on a hidden field in every counted row is
left out, even with "show_zero": true: "0.00 awaiting approval" would be a statement about a field the viewer cannot read. The other parts of the sentence are kept.
With enforcement off or audit-only nothing is redacted anywhere, and counts and sentences are the row-level ones described above, unchanged. If the mode cannot be determined, nothing is counted. A viewer who reads every field a declaration names sees the same numbers either way. Being an admin is not the same thing: the schema can hide a field from an admin as from anyone. Among the shipped packages (audited 2026-12-03) exactly two queues change, thread_comments_to_moderate and profile_comments_to_moderate: their status is hidden from everyone but the comment's owner and the moderator role, so with enforcement on an admin who is not also a moderator is no longer shown those counts (the record API does not show them status either). Moderators, and admins who are also moderators, see what they did. The threshold a {"setting": ...} reads from app_settings is the box's configuration, the same for every viewer, and is not redacted.
A code provider's number, by contrast, is computed with no viewer, so it reaches only viewers who may read every row it was folded from (below) — which is why a queue that can be declared should be: a member then sees their own share instead of nothing.
Declared counts are therefore not rolled up: the daemon skips them, and removes any number a replaced provider left in attention_counts, a global count being exactly what a per-viewer one must not leak. The index read is what keeps this inside the rule below: the cost of a home render is each queue's candidate rows, not a fold over the collection. (A collection over DBBASIC_RECORDS_CACHE_MAX_ROWS has no index and is read whole, exactly as every API list of it already is.)
Write a provider instead when the number needs another collection (a quantity still owed across order and receipt lines), arithmetic between fields (how far below its reorder point the worst shelf is), one field standing in for another (a run's started_at, else its created_at), or a comparison the row-filter language does not have (a naive local datetime against the wall clock, in minutes). Those are loops, functions and expressions, and configuration never gets them. The five providers that remain, and why:
| Provider | Why it is code |
|---|---|
orders_to_pick | ordered minus shipped, across orders, order lines, shipments and shipment lines |
pos_short_received | the detail folds receipts and receipt lines against order lines |
products_to_reorder | the detail is reorder_point - on_hand |
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 |
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 |
Who sees a provider's number
A provider's count was computed by the daemon over every row of the collections it reads, with no viewer, and until 2026-11 it was shown to every signed-in user — so a member with no grant on purchase orders saw how many were short. Now object_attention.provider_shown_to decides, fail closed:
- an admin sees it;
- anyone else sees it only when the entry's
readsnames at least one
collection the box has, and for each of them the viewer may read every row, whole (object_access.Access.reads_every_row): no deny rule that applies to them (filtered or not), and either the access mode allows the read or some allow rule grants it with no row filter and no field restriction. An own-rows grant is not enough — the number is everybody's rows;
- an entry with no
reads, areadsthat does not parse, or a stored
count whose source row is gone: admins only;
- a listed collection the box does not have holds no rows and is skipped.
- with permissions enforced, a listed collection whose schema could
hide any field from the viewer in some row hides the number from them, admins included (object_field_permissions.may_hide_a_field). The rule check above looks at rules only, and a provider does not say which fields it folds, so any field the record API would redact for this viewer might be one it counted or described. "Could hide" is decided without a row and fails closed: a field hidden from a principal the viewer matches, hidden from owner (anyone can own a row), hidden by default unless a role or other row-independent principal the viewer matches grants read or edit, or a permissions that does not parse. With enforcement off no field is redacted and this check is skipped; if the mode cannot be determined the number is shown to nobody. No shipped provider reads a collection with field permissions today.
attention_counts itself is readable by nobody but an admin: the menu reads it in process (action_nav_entries), and app-nav retracts the registered read rule it used to ship, so an upgraded box drops it too.
The COUNT contract
A provider is an ordinary object exposing:
def COUNT(request):
return {"count": 3, "detail": "1 over a week old"}
COUNT and not GET or POST, deliberately: a distinct verb means the same object stays free to answer a human on the other methods without either use accidentally serving the other. count must be a real non-negative integer — the rollup refuses to coerce a string or a float, because every coercion here is a way for a broken provider to look like an empty queue. detail is optional and is the sentence a bare number cannot say ("62 hours awaiting approval", "18 units still owed").
A provider reads its own collections and degrades to {"count": 0} when they are absent — a deployment that never installed your app should not produce an error every five minutes. A provider that genuinely fails should raise; see below for what happens then.
Counts are a rollup, not a live fold
object_daemon.process_attention executes every code provider on an interval (DBBASIC_ATTENTION_INTERVAL_SECONDS, default 300) and writes the answers to the attention_counts collection. The home page and the app list read that one small table.
This is not an optimisation, it is a rule. Folding a dozen collections on every home render is how a home page becomes the slowest page, and worse: this box went to 675MB resident and started swapping because something folded a big collection on a timer. A home screen that folds a dozen collections per render is that same mistake with a nicer name, and it makes the front page's cost grow with the number of installed packages — the one place cost must not grow. Staleness is bounded by the interval and stated on the page ("as of 6 minutes ago") rather than pretended away.
Two consequences worth knowing when you write a provider:
- A broken provider must look broken, never look calm. One that
raises, or answers with a non-integer count, has its error written and its previous count kept, with computed_at left where it was. Zeroing it would report an empty queue when what happened is that nobody looked.
- Do not do expensive work per row. The pass runs every five minutes
on the same box that serves requests. A full scan of your own collections is the intended cost; calling out to a network is not.
Zeros disappear
A count of zero is stored (the absence of a row means the provider has never run, which is a different fact) and rendered nowhere. When every queue is empty the home page's "Needs you" band is absent entirely — not "0 pending", not an empty panel with a heading: gone.
This is the rule that separates an inbox from a dashboard. A board that says "0 pending approvals" every day trains people to stop reading it, and once they have stopped they do not start again on the day it says three. A page that is EMPTY when nothing needs them, and short when something does, gets read every time. "Nothing needs you" is a complete and welcome answer, and blank space gives it better than any sentence would.
Idempotency and the operator
The same three properties nav has:
- The operator's
operator_mutedsurvives. A deployment that does
not work a queue mutes it (a role:manager update on attention_sources) instead of editing somebody else's manifest, and an install never writes that column. A muted source is not executed at all and its stored count is removed, so it costs nothing and shows nothing.
- Unchanged means unwritten. Every package-owned field —
object_id, collection, where, detail, label, path, nav_id, group, severity — is compared before anything is written.
- Removing an entry does not delete the row. Deregistering never
destroys.
A collision with another package on an id blocks the install: two packages writing one row is two definitions of what needs a human, and whichever installed last would silently win. Unlike nav there is no path-collision rule — two queues legitimately point at one list, and blocking that would be a false blocker.
If the attention_sources collection does not exist (app-nav is not installed) the entries are reported as skipped with a reason and the install proceeds, exactly as nav entries are.
Personal data: the subject export
action_export_subject_data (app-privacy, admin-only) answers a subject access request: everything the server holds about one email address, in one document. It does not have its own list of collections. Each schema declares what in it is personal, and the export folds every installed collection by those declarations (three schema files, shown together):
{"name": "patients", "fields": [
{"name": "id"},
{"name": "email", "subject": "email"}]}
{"name": "appointments", "fields": [
{"name": "id"},
{"name": "patient_id", "subject": "relation", "relation": {"collection": "patients"}}]}
{"name": "treatment_notes", "fields": [
{"name": "id"},
{"name": "appointment_id", "subject": "relation", "relation": {"collection": "appointments"}}]}
"subject": "email"— this field holds the person's email address. A row
whose value is their address (case and surrounding spaces ignored) is theirs.
"subject": "relation"— this relation points at a record already proven
to be theirs, so the row is theirs too. Relations are followed to any depth (notes → appointments → patients), and only in that direction: from the person's own rows to rows that point at them. A relation to a shared record (a product, a fund) is not declared and is never a way in.
"subject_exempt": "<why>"at the schema root — no field identifies a
person (rows keyed by an anonymous visitor token, the operator's own mailboxes). The sentence is returned under not_searchable.
The loader refuses any other subject value, and a relation declaration without a relation, because a typo there would leave a person's records out of their own request. A collection with an email-like field (a name containing email, or to / sent_to) that declares nothing is still named in the export's not_searchable, with "undeclared": true and the fields, and is not searched. tests/test_privacy.py fails when a shipped schema has such a field and no declaration. The export also lists what it searched, and under unavailable any collection a declaration points at that the box doesn't have, or that could not be read.
A box upgraded from before these keys existed keeps its installed schemas until the upgrade reinstalls the packages. Until then the export names those collections as undeclared rather than guessing.
The declarations say what is personal. They say nothing about what may be erased or how long it is kept. The export offers no erasure: orders, invoices and payments are business records with statutory retention, and deleting a row an invoice references breaks the ledger rather than anonymising anyone. Which fields are contact details (redactable) and which are evidence (kept), and for how long, is an open decision for the owner, to be made per collection before any erasure code is written.
Editor Help: The DRON Schemas
Everything a package declares (schemas, manifest, permission rules) is described by JSON Schema files in dron/, the formal side of DRON. Point an editor at them and it completes keys, shows each key's description on hover, and underlines the mistakes the installer would refuse (a misspelt row_filter, maxlength for validation.max_length, "surface": "private") before you get as far as installing.
| File | Schema |
|---|---|
packages/*/schemas/*.json | dron/dron-collection.schema.json |
packages/*/dbbasic-package.json | dron/dron-package.schema.json |
packages/*/permissions/*.json | dron/dron-permissions.schema.json |
Two more schemas describe files that are not part of a package: the deployment's own policy, data/permissions/policy.json (what PUT /permissions/policy stores), by dron/dron-policy.schema.json, and the signed envelope boxes exchange, by dron/dron-document.schema.json. Map them the same way in your own deployment's editor settings; a box reads its own policy more loosely than the schema (see dron.md), so run an operator-written policy through the schema before saving it.
VS Code, no change to any package file. In .vscode/settings.json:
{
"json.schemas": [
{"fileMatch": ["packages/*/schemas/*.json"],
"url": "./dron/dron-collection.schema.json"},
{"fileMatch": ["packages/*/dbbasic-package.json"],
"url": "./dron/dron-package.schema.json"},
{"fileMatch": ["packages/*/permissions/*.json"],
"url": "./dron/dron-permissions.schema.json"}
]
}
Or per file, a $schema key at the top of the file, relative to it:
{"$schema": "../../../dron/dron-collection.schema.json", "name": "invoices"}
The loaders ignore a $schema key (a collection's is dropped when the schema is normalized, the manifest's and a rules file's are never read), and the DRON schemas allow it, so adding one never breaks an install (tests/test_dron_schema.py proves it through the real loaders). The shipped packages do not carry one: it would change every file's content hash and restore-point baseline for no change in behaviour, so they rely on the editor mapping above.
tests/test_dron_schema.py validates every shipped file against these schemas, so a file that an editor flags is a file CI flags. A fragment that the schema cannot judge on its own (a required_when naming a field the collection does not have, two nav entries with one id) is still refused by the loader at install; the test lists each such case.
Start From A Scaffold
python scripts/new_package.py app-tickets
python scripts/try_package.py app-tickets --user ann --user bob --brief \
--call 'ann POST /collections/tickets/records {"title": "first", "owner_id": "ann"}' \
--call 'bob GET /collections/tickets/records' --rows 'ann /tickets'
scripts/new_package.py <id> (standard library, writes only the new directory, refuses to overwrite one) creates packages/<id>/ with a working package: a manifest, one schema (collection name = the id without app-, dashes to underscores; --collection overrides), the owner rule from the recipes below, a seeded list page at /<collection> and a menu entry. It depends on app-nav and app-views because it ships both. It installs as it stands and passes tests/test_dron_schema.py's checks, so every later edit starts from a package that works: change one thing, run try_package.py, repeat. Next steps are the recipes (add a field, a role, a queue, a freeze), then the workflow below. Pass --dir to write somewhere other than packages/; give the same directory to try_package.py --packages-dir.
Authoring Workflow
- Create the package directory and manifest (or start from the
scaffold).
- Write the objects (see
object-authoring.mdfor method shape, state, logs,
request["_identity"], and HTML form patterns).
- Write each schema JSON (
{"fields": [{"name": "id"}, ...]}— see the
schemas section of http-api-contract.md for validation and field permission options).
- Seed TSV: first row is the header, tab-separated, and must include
id. - Try it before you install anywhere real:
scripts/try_package.py installs the package into a scratch directory and calls it as users with roles, enforcement on. Then dry-run:
GET /packages/{package_id}?dry_run=true
Authorization: Token <token>
The plan reports what would be created, replaced, merged, applied, or skipped, with warnings. Nothing is written.
- Install (requires
DBBASIC_ENABLE_PACKAGE_INSTALLS=trueplus the admin
gate):
POST /packages/{package_id}/install
Authorization: Token <token>
- Verify: run the objects, read the records, check
GET /packages/{package_id}/changes for the install changelog, and use POST /packages/{package_id}/restore if the install needs to be rolled back (requires DBBASIC_ENABLE_PACKAGE_RESTORE=true).
What A Schema's version Does
"version": 7 in a collection schema is a label, a whole number you raise by hand. Exactly what it does:
- It is stored and echoed:
GET /schemas/<collection>(admin) and the schema
listings report it, so a person can tell which shipped shape a box holds. It is absent from GET /api/schema/<collection>, the public structure-only view the generated forms read. A schema with no version reads as 1; one that is not a whole number of at least 1 is refused when the schema loads.
- Nothing compares it. Install decides what to do by comparing content
hashes of the shipped file, the live file and the last installed copy, so an edit you forgot to bump still installs (the number is part of the content, so a bump alone installs too, as an update). It runs no migration, rewrites no record, and does not touch a cache (the schema cache follows the file itself).
- On an upgrade of a customised schema (
merged, above), fields are merged
and everything else, the number included, is taken from the shipped file.
- It is not the schema history.
PUT /schemas/<collection>records a numbered
version of its own under data/schema_versions/ (that is what ?versions=true lists and what rollback restores); a package install does not write to it, and the two numbers are unrelated. A package install is undone by its restore point.
So: raise it when you change a schema's shape, as a note to the next reader; the engine does not need it. A test must not pin the number to prove a change. Assert the fields, the rules and the views the test is about, or schema["version"] >= N when the history is the point. Two package tests (tests/test_app_contacts_package.py, tests/test_app_tasks_package.py) pinned the exact number, so every schema edit meant editing a test for no reason; every tests/test_app_*_package.py now says >=. If a test of yours fails only on the number after you bumped it, the test is what is wrong.
A failing pin on a pure addition is a test bug. Adding a field to a form, a column to list_fields, a value to an enum, a dependency, a second permission file, a schema or a seed to a package, or bumping a version, must not turn a test red. The tests/test_app_*_package.py files used to say forms.default.fields == [...], dependencies == [{"id": "app-projects"}] and package["version"] == "0.6.0", so each of those additions broke a test that only meant to say "these are still here". They now assert what matters: tests/package_pins.py has assert_includes_in_order(actual, expected) (every expected member present, in the order named, extras allowed) and version_at_least, and sets are compared with >=. If your addition fails an exact-equality pin on a list, a set of collections or a version, relax the pin the same way; do not add your value to the expected list. Keep exact equality for what must not change: a permission rule, a transitions target set, a hidden field, a money amount. Those are behaviour and security, and an addition that touches them should fail until a person decides it is intended.
Which version to bump
The version in dbbasic-package.json is a different thing from a schema's: the package's release, recorded in its install baseline and in the install changelog. Bump it on any content change. Neither number is compared by the installer (content hashes decide what changes), so these are conventions the next reader relies on:
| You changed | Package version | Schema version |
|---|---|---|
a field added to deals.json (the recipe above) | 0.1.0 to 0.2.0 | 1 to 2 |
only an object's code, a seeded row or a rule's reason | 0.2.0 to 0.2.1 | unchanged |
| 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 |
| 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 |
Patch for a fix nobody has to react to, minor for something added or changed that people can see, and the description for anything an operator must act on. Then reinstall with allow_replace (an install of a package that already has objects or schemas on disk is refused without it).
Upgrading A Package: Data, Backfill, And An Upgrade Test
An upgrade is a reinstall of a higher version over the box's live data (allow_replace). What it does to each layer:
| Layer | On upgrade |
|---|---|
| records | untouched. Data lives outside the package, keyed by collection |
| the schema | replaced, or merged with the operator's local additions (what version does) |
| 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 |
a default | fills new writes only, never an existing row |
| seed rows | merged by id; a live row an operator changed is kept |
The recommended pattern, since nothing migrates for you:
- Make changes additive. Add a field; do not rename, retype or remove one
(a rename is a new field plus a backfill, with the old one left in place).
- Write every reader to cope with empty. A page, a check or a handler that
reads the new field treats blank as "the default" (row.get("priority") or "normal"); a where filter on the new field simply does not match old rows (?priority=normal omits them), so a filter that must include old rows waits for the backfill.
- Backfill as a separate, repeatable step, not inside the install: an
admin loop of PUT /collections/<c>/records/<id> with the new value for each row that lacks one (it is idempotent: a second run finds nothing to do), or a one-off script using object_records.update_collection_record.
- Only then tighten: make the field
required, addrequired_when,
unique or a lock. A rule added on a field that old rows lack refuses those rows' next write until they conform (what happens to rows already there).
Test the upgrade before you ship it. Install the old version, write data as a real person, change the package's files to the new version, install it over the same data with Sandbox.reinstall and read the old data back. Save as a pytest file in your checkout and run it from the repository root; the data directory is a throwaway, nothing is left running. (tests/test_package_recipes.py runs this exact block.)
<!-- recipe: upgrade-test -->
import json
import shutil
from scripts import new_package
from scripts.try_package import Sandbox
def test_the_upgrade_keeps_old_rows_and_gives_new_rows_the_default(tmp_path):
root = tmp_path / "packages"
for name in ("app-nav", "app-views"):
shutil.copytree(f"packages/{name}", root / name)
new_package.create_package("app-tickets", packages_dir=root) # version 1
records = "/collections/tickets/records"
with Sandbox(["app-tickets"], packages_dir=root) as box:
box.add_user("ann")
status, body = box.call("ann", "POST", records, {"title": "old", "owner_id": "ann"})
assert status == 201
old_id = body["record"]["id"]
schema_path = root / "app-tickets" / "schemas" / "tickets.json" # ship version 2
schema = json.loads(schema_path.read_text())
schema["fields"].append({"name": "priority", "type": "enum", "default": "normal",
"enum": ["low", "normal", "high"]})
schema["version"] = 2
schema_path.write_text(json.dumps(schema))
box.reinstall("app-tickets")
old = box.call("ann", "GET", f"{records}/{old_id}")[1]["record"]
assert old["title"] == "old" # the row survived
assert not old.get("priority") # and was not backfilled
status, body = box.call("ann", "POST", records, {"title": "new", "owner_id": "ann"})
assert body["record"]["priority"] == "normal" # new writes get the default
assert box.call("ann", "GET", records)[1]["total"] == 2
Customisations an operator made (extra fields, edited objects, rules) survive an upgrade by the three-way rules in upgrade-and-customization.md; test those with the same pattern, making the change between the two installs.
Try Your Change
A rule or a schema is only half checked by reading it; the other half is what the API answers a person with that role, with permission enforcement on. scripts/try_package.py does that in one command: it installs packages into a throwaway data directory, creates users with the roles you name and an API key for each, and sends the requests you list, as those users, through the real application. Standard library only, no network, no port opened, nothing left running; the scratch directory is removed when it finishes (--data-dir DIR keeps the data instead).
python scripts/try_package.py deals \
--user ann --user bob --user carol:auditor \
--call 'ann POST /collections/deals/records {"title": "Ann one", "owner_id": "ann"}' \
--call 'ann PUT /collections/deals/records/$last_id {"title": "Ann 1"}' \
--call 'bob GET /collections/deals/records' \
--call 'carol GET /collections/deals/records' \
--call 'anon GET /collections/deals/records'
- A package name that lists
dependenciesfound beside it installs those
first (app-nav, app-views, ...). Other packages directories: --packages-dir. To see what your change did, run the same calls against the unchanged package: git worktree add ../before HEAD gives you the old tree, --packages-dir ../before/packages runs the old version while the plain command runs your edited one, and a diff of the two outputs (add --brief) is the behaviour change. The packages beside the one you name (its dependencies) come from the same directory.
--user NAME[:ROLE,ROLE]makes a user. A role is just a name; a rule's
"principal": "role:auditor" matches users whose roles include auditor. Roles live on the user record (data/identity/users.tsv): set them when the user is created, as here, with POST /identity/users ("roles": [...]), with object_identity_cli.py create-user --roles a,b, or in Python with object_identity.create_user({"user_id": "carol", "roles": ["auditor"]}). The deployment policy's user_roles map ({"carol": ["auditor"]}, written with PUT /permissions/policy) assigns roles too, and the two add together. admin and superuser are the admin roles, and the admin token bypasses every rule.
- A call is
USER METHOD PATH [JSON]; USER is a--username,admin(the
admin token) or anon (no credentials). Each answer prints as its status and JSON. $last_id in a path is the id of the record the previous call returned.
--briefprints one line per call instead of the JSON:
ann POST /collections/deals/records -> 400 Record field 'title' is required, the status, then the error (and its code, when it has one). Use it for a run of many calls; leave it off to read one full answer.
--rows 'USER ROUTE'shows what a seeded page's list blocks would put on
screen for that person: for each list block, the rows the person may read and the title and subtitle each row would carry (title_field, subtitle_field, subtitle_label, else the first non-empty of title, name, label, subject, body, text, content, message, description, email, then the id). Pages are drawn in the browser by JavaScript, which this does not run, so the script computes the labels with a Python copy of the list renderer's rules (a test fails if the two default orders drift apart). It checks the data and the labels, not the layout: a table collection prints its list_fields columns instead (a table ignores title_field and subtitle_field), board, tree and calendar modes are not previewed, and the search box is not reproduced. For anything visual, open the page in a browser. Example: --rows 'ann /notes' after --call 'ann POST /collections/notes/records {"content": "hi", "owner_id": "ann"}'.
- Pages need
DBBASIC_ENABLE_SITE_ROUTES=true. A seeded view is served
through a site_routes row, and routes are off by default, so without the variable ann GET /notes is 404 Not found. Run DBBASIC_ENABLE_SITE_ROUTES=true python scripts/try_package.py ... (and start a real server with it set) to get the page. What comes back is the page shell, not the rows, which the browser fetches afterwards; --rows does not need the variable, because it reads the views records directly.
owner_idon a create is yours unless your role says otherwise. Leave
it out (or send your own id) and the server fills in the caller before the rules are asked, so an own-rows rule ({"owner_id": "$user_id"}) allows it. Someone else's id is refused with 403, "field": "owner_id", and is never rewritten: only an admin role or a rule with "on_behalf": true (staff entering records for others) may create a row another user owns (docs/permissions-model.md, "Who owns a record you create"). The server fills in only owner_id; any other field a rule filters on must be sent, and a create without it is answered 403 {"error": "no matching role rule"}, which reads as "no permission" and is really "your record does not match your own grant".
- Enforcement is on;
--no-enforceturns it off, and then only the admin token
gets in. Event handlers, schedules and the attention rollup are daemon work and do not run here (they are off on a stock install too).
From Python, for a test of your own (this is what tests/test_try_package.py does):
from scripts.try_package import Sandbox
with Sandbox(["deals"]) as box:
box.add_user("ann")
box.add_user("carol", roles=["auditor"])
status, body = box.call("ann", "POST", "/collections/deals/records",
{"title": "Ann one", "owner_id": "ann"})
status, body = box.call("carol", "GET", "/collections/deals/records")
Putting your package under packages/ also lets the DRON test check it (python -m pytest tests/test_dron_schema.py -k deals), which finds a misspelt key before an install does (the installer refuses one too).
What A Record Looks Like On The Wire
Records are stored in TSV files, so every value a record API returns is a string. This is the storage representation, not a bug in one endpoint, and it is what every record surface returns today:
POST {"title": "x", "amount_cents": 500, "is_public": true}
-> {"record": {"title": "x", "amount_cents": "500", "is_public": "true", ...}}
- Integers and numbers come back as
"500","5.5"; booleans as
exactly "true" or "false". A field never written is absent from a single record and an empty string "" in a list: treat both as empty. Dates and datetimes are ISO strings.
- What you may send is looser than what you get back: a JSON number
or a numeric string for an integer field (500 or "500"; "5.5" is refused 400 ... must be an integer), and for a boolean a JSON boolean or "true", "yes" or 1, which are all stored as "true".
- Filters and the counts that use them compare the stored text:
?amount_cents=500 and {"status": "open"} match exactly. Ordered filters (?amount_cents.gte=100) parse the cell by the field's type. Never compare "10" and "9" as strings in a client; convert first.
- Clients convert using the schema.
GET /api/schema/<collection>lists
every field with its type (integer, number, boolean, date, datetime, enum, text, ...). A generic client reads it once and converts: parseInt for integer (money is integer cents; do not use floats), value === "true" for boolean, new Date for dates. The shipped list and form pages read the same endpoint for their cell formatting.
- Responses carry a few real numbers beside the records (
total,count,
limit, offset); those are JSON numbers.
tests/test_package_recipes.py checks each claim above against the deals package and app-notes.
Recipes
Four things people ask for first, each as a small change to one package, deals, with what to expect. Create the three files, then run any recipe's commands with scripts/try_package.py above. (tests/test_package_recipes.py builds the package from these exact blocks and checks every result stated here, so they stay true.) The first three blocks are whole files. Every later block is a fragment, and the sentence above it says which file it goes in and where: "append to rules" means add the object to that array, and "add these keys" means merge them into the file's top-level object beside the keys that are already there (a key you add that exists, such as dependencies or objects, replaces it). The blocks are valid JSON on their own and are not meant to be saved as a file. (Or start from the scaffold, which writes the same shape under your own names.)
packages/deals/dbbasic-package.json:
<!-- recipe: deals-manifest -->
{
"id": "deals",
"name": "Deals",
"version": "0.1.0",
"description": "Deals, each owned by one person",
"compatibility": {"dbbasic_object_server": ">=0.1.0"},
"dependencies": [],
"objects": [],
"schemas": [{"collection": "deals", "path": "schemas/deals.json"}],
"permissions": [{"path": "permissions/rules.json"}],
"seed": [],
"migrations": []
}
packages/deals/schemas/deals.json:
<!-- recipe: deals-schema -->
{
"name": "deals",
"title": "Deals",
"version": 1,
"fields": [
{"name": "id"},
{"name": "title", "type": "text", "required": true},
{"name": "description", "type": "textarea"},
{"name": "status", "type": "enum", "enum": ["open", "won", "lost"],
"default": "open", "transitions": {"open": ["won", "lost"]}},
{"name": "amount_cents", "type": "integer"},
{"name": "assigned_to", "type": "text"},
{"name": "owner_id", "type": "text"}
],
"forms": {"default": {"fields": ["title", "description", "status", "amount_cents", "assigned_to"]}},
"views": {"list_mode": "table", "list_fields": ["title", "status", "amount_cents"]},
"search": {"fields": ["title", "description"]}
}
packages/deals/permissions/rules.json:
<!-- recipe: deals-rules -->
{
"rules": [
{"effect": "allow", "principal": "registered",
"actions": ["create", "read", "update", "delete"],
"collection": "deals", "row_filter": {"owner_id": "$user_id"},
"reason": "people manage their own deals"}
]
}
As it stands, ann sees and changes her own deals, and nobody else's.
A role reads every row while only owners write
Append this object to the rules array in permissions/rules.json: the role's grant has no row_filter, and a grant with no filter is every row.
<!-- recipe: deals-auditor-rule -->
{"effect": "allow", "principal": "role:auditor", "actions": ["read"],
"collection": "deals",
"reason": "auditors read every deal and change none"}
Rules add up: a request is allowed when any allow rule matches, and each rule brings its own row filter. So an auditor reads every row through this rule and, being signed in, still owns whatever she creates through the first. With ann (two deals), bob (one) and carol (role auditor):
| Request | Answer |
|---|---|
ann GET /collections/deals/records | 200, total: 2, her rows |
bob GET /collections/deals/records | 200, total: 1, his row |
carol GET /collections/deals/records | 200, total: 3, everyone's |
carol GET ...records?limit=2&offset=2 | 200, count: 1, total: 3, has_more: false |
carol GET ...records?owner_id=ann | 200, total: 2: filters apply after the grant |
carol GET /api/search?q=Ann&collections=deals | 200, Ann's deals |
carol PUT or DELETE on Ann's deal | 403 no matching role rule |
bob PUT on Ann's deal | 403 no matching role rule |
ann POST with owner_id: "ann", or without it | 201, owned by ann; with "bob": 403 |
Listing, paging and filtering are all done after the permission filter, so total is the number of rows the caller may read.
A count over rows I own or am assigned
where is a row filter: its entries are ANDed, and there is no OR and no NOT (adding either is a design decision that has not been taken). Write two entries, one per condition, in the manifest. A queue declared with collection and where is counted for the viewer, over the rows the viewer may read, so the second queue also needs a read grant on the assigned rows, or the assignee sees 0, and a zero is never shown.
<!-- recipe: deals-attention -->
{
"dependencies": ["app-nav"],
"attention": [
{"id": "deals_i_own", "collection": "deals",
"where": {"status": "open", "owner_id": "$user_id"},
"label": "Open deals I own", "path": "/deals", "group": "Work"},
{"id": "deals_assigned_to_me", "collection": "deals",
"where": {"status": "open", "assigned_to": "$user_id",
"owner_id": {"op": "ne", "value": "$user_id"}},
"label": "Open deals assigned to me", "path": "/deals", "group": "Work"}
]
}
(Merge both keys into the top level of dbbasic-package.json, replacing its empty "dependencies": []. app-nav must be installed: it owns the registry the entries are written to, and without it they are skipped with a note. See the app-nav rule.)
The second queue excludes rows the viewer owns ("owner_id": {"op": "ne", "value": "$user_id"}), so a deal that is both owned by and assigned to the same person is counted once, in "I own". Without that condition it would count in both queues and the badge would double-count it. (ne matches a deal with no owner at all, and the queue still needs one literal condition, here status.) And append this object to the rules array in permissions/rules.json:
<!-- recipe: deals-assignee-rule -->
{"effect": "allow", "principal": "registered", "actions": ["read"],
"collection": "deals", "row_filter": {"assigned_to": "$user_id"},
"reason": "assignees read the deals assigned to them"}
Read the result the way the menu does: GET /objects/action_nav_entries, as each person, and look at attention. With Ann owning two open deals that are assigned to Bob, and Bob owning one:
| Viewer | attention |
|---|---|
ann | deals_i_own count 2 |
bob | deals_assigned_to_me count 2, deals_i_own count 1 |
carol (auditor, owns none) | nothing: both queues are 0 |
The two queues do not overlap, so the union "owned or assigned" is their sum with nothing counted twice (a deal Bob both owns and is assigned counts once, under "I own"). Reach for a provider object (COUNT), below, only when the rule is more than conditions can say.
To put the number on the app list too, give the package a door: merge this nav key into the top level of dbbasic-package.json, and add "nav_id": "deals" to each of the two attention entries above:
<!-- recipe: deals-nav -->
{"nav": [{"id": "deals", "label": "Deals", "path": "/deals", "group": "Work"}]}
GET /objects/action_nav_entries then returns the Deals entry with count 2 for ann and 3 for bob (2 assigned + 1 owned): the badge is the sum of every queue that names the door, while attention keeps the two rows apart.
Freeze some fields once a record is settled
locked_when freezes a record while its stored state matches when. Two ways to say which fields stay free, and a rule uses one of them:
"except": [...]freezes everything except the listed fields. Fields you
add to the schema later are frozen too, which is the safe direction for money and the surprising one for a note field nobody thought about.
"fields": [...]freezes only the listed fields; every other field,
including ones added later, stays editable. Use it when most of the record is allowed to keep changing. The names must be declared fields (not id), and a rule with both except and fields is refused at schema load.
<!-- recipe: deals-locked-when -->
{
"locked_when": [
{"when": {"status": ["won", "lost"]},
"fields": ["title", "description", "amount_cents"],
"message": "A settled deal's title, description and amount are frozen."}
]
}
(Merge that key into the top level of schemas/deals.json, beside fields and forms.) With a won deal:
| Request | Answer |
|---|---|
PUT {"assigned_to": "carol"} | 200: not a frozen field |
PUT {"title": "late"} | 409 {"code": "record_locked", "fields": ["title"], "error": "A settled deal's ..."} |
PUT {"title": "<its current title>"} | 200: sending a frozen field back unchanged is not a change |
DELETE | 409 record_locked, fields: [] (allow_delete defaults to false) |
the admin token does the same PUT | 409: nobody is exempt |
PUT {"status": "open"} | 400 ... cannot move from 'won' to 'open' (allowed: none) |
The last row is not the lock: it is the transitions map. done, won, closed mean nothing to the platform. A status is terminal only because it has no entry in transitions (values missing from the map are terminal); a status you can leave is a status you listed moves for. The fields form does not name status, so the transitions alone decide where a settled deal may go. In the except form you would list status to let the lock be left, and leave it out to make the state final. Details: "Locked when settled" in validation-and-logic.md.
Add a field and show it in a list page
Five places know about a field; the list page needs the first and one of the next two:
fields: `{"name": "priority", "type": "enum", "enum": ["low", "normal",
"high"], "default": "normal", "label": "Priority"}. The record API accepts, validates and returns it from here. Rules a field can carry, each in [validation-and-logic.md](validation-and-logic.md): required, enum, validation.min_length / max_length / pattern, validation.min / max and exclusive_min / exclusive_max ([strict bounds](validation-and-logic.md#strict-bounds-and-conditional-required-fields)), validation.required_when (non-blank only while the record is in a given state, same section), and a root-level unique` key (uniqueness).
forms.default.fields: add"priority". When a schema lists form fields,
a field not listed is not on the form.
views.list_fields: add"priority". This is what the table list
shows as columns and what the board shows on each card. The list page itself is a seeded view record over the schema's views.list_mode (see Seeded views and site routes); the plain row list (list_mode absent, cards or feed) and the tree and calendar modes do not show list_fields at all, only a title and a date. To put a field on a row list, name it as the list block's subtitle_field. A row with no value for that field draws no subtitle line (never a bare "Pinned:"), and a field the schema types boolean reads Yes/No instead of true/false (the list generator fetches the schema for this; with list_modes_enabled turned off it does not, and values show as stored).
views.detail_fields, if the schema declares one, for the detail page;
search.fields to make it searchable text; views.filter_fields for a filter select (enums and booleans).
- Bump
version, and reinstall withallow_replace
(POST /packages/deals/install with {"allow_replace": true}, or install_package(..., allow_replace=True) in Python): the schema comes back updated.
What to expect afterwards: GET /api/schema/deals lists priority under fields and in views.list_fields; a deal created from now on without a priority reads normal; a deal written before the change has no value (a default fills new writes, not old rows), so ?priority=normal does not list it. Backfill old rows with an update if the page should show a value for them. A value outside the enum is refused 400 Record field 'priority' must be one of: low, normal, high.
Required fields must be in every create. A field with "required": true makes a create without it a 400, and the generated form is not the only caller: your try_package.py --call is too. On a real package:
python scripts/try_package.py app-contacts --user ann --brief \
--call 'ann POST /collections/contacts/records {"last_name": "Lee", "owner_id": "ann"}' \
--call 'ann POST /collections/contacts/records {"first_name": "Ada", "owner_id": "ann"}'
# ann POST /collections/contacts/records -> 400 Record field 'first_name' is required
# ann POST /collections/contacts/records -> 201
A field you make required later therefore breaks every caller that does not send it yet; add it as optional, backfill, then require it.
What happens to rows that are already there when you add a rule. None is rewritten, and none is removed:
uniquecompares exactly as stored, case included:"Acme"and
"acme" are two keys unless the constraint says "ignore_case": true (which folds the key fields, not scope). Values are trimmed first, so "Acme" and "Acme " are one key: trimming is leading and trailing whitespace only (Python str.strip), not whitespace inside the value. A blank key field means the row has no key and is exempt. Tested in tests/test_package_recipes.py; full rules in validation-and-logic.md.
unique: existing duplicates stay and stay editable; no further holder of
the key is admitted. object_records.find_unique_violations(collection, base_dir=...) lists them; run it before you ship the declaration and merge or delete what it reports.
required_when,min/max: a row that already breaks the rule stays on
file but is refused on its next write, whatever that write changes, until it conforms (validation-and-logic.md).
locked_when: it looks at the stored state, so a row already in a matching
state is frozen from the moment the rule lands.
What Can't Be Declared
Schemas, permission rules, where filters and seeded views say a great deal without code. They do not say these, and a package that needs one is not doing something wrong: it needs the tool in the right-hand column.
| You want | Why a declaration cannot say it | Use |
|---|---|---|
| "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) |
| the same, as a count ("invoices over a week old") | an attention declaration with {"op": "older_than_days", "value": 7} (counts only; Declared counts) | |
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); a check only decides at write time |
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 |
comparing two fields (end_on > start_on, taken <= capacity) | a bound is a constant | a locked check on the record's own fields |
| "forbidden when" (a lost deal must have no reason code) | required_when asks for non-blank, never blank | a locked check |
| a rule that needs rows of other collections (a sum against a ceiling) | a locked check with reads (Locked checks) | |
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 rule about who may do it, that no row filter can state | a pre-write hook, which gets the caller; a check never does |
A check that reads the record and the clock
A locked check is a function the schema names and the platform calls inside the write lock, for every writer (HTTP, MCP, handlers, the daemon, imports), and a refusal writes nothing. This one refuses a deal whose close_on is in the past. Three files change.
1. dbbasic-package.json: merge this key into the top level, replacing the empty "objects": []:
<!-- recipe: deals-close-date-manifest -->
{"objects": [{"id": "hook_deals", "path": "objects/hook/deals.py"}]}
2. schemas/deals.json: append this field object to the fields array:
<!-- recipe: deals-close-date-field -->
{"name": "close_on", "type": "date", "label": "Close on"}
and merge this key into the schema's top level (beside fields):
<!-- recipe: deals-close-date-checks -->
{
"locked_checks": [
{"name": "close_date", "object": "hook_deals", "function": "LOCKED_CHECK",
"on": {"create": true, "update": ["close_on"], "delete": false}}
]
}
3. packages/deals/objects/hook/deals.py (a new file):
<!-- recipe: deals-close-check -->
from datetime import date
def LOCKED_CHECK(request):
close_on = (request.get("record") or {}).get("close_on", "")
if close_on and close_on < date.today().isoformat():
return {"error": "A deal cannot close in the past.", "status": 409}
return None
Comparing a datetime with now
A date is a bare YYYY-MM-DD with no zone, compared above with the server's local date. A datetime field needs three decisions, and the platform's convention is UTC:
- What is stored is whatever the writer sent, if it parses. The platform
validates with datetime.fromisoformat after turning a trailing Z into +00:00, and stores the string as sent. So a stored value may be aware (2026-07-27T09:39:00Z, ...+02:00) or naive (2026-07-27T09:39:00, no offset). The generated form sends UTC with a Z and no fractional seconds (the browser's datetime-local answer, read as the viewer's wall clock, is converted to UTC before it is sent); a server-filled created_at is UTC with microseconds and a Z. An API client may send any of them.
- Comparing aware with naive raises
TypeError. Normalise first: read a
naive value as UTC (that is the platform's own rule: attention's older_than_days does the same), convert an aware one to UTC, and compare with datetime.now(timezone.utc).
- A value you cannot parse is a check that cannot decide, so fail closed.
Do not return None (allow) from an except. Let the exception out: the platform turns any exception raised by a check into 503 check_unavailable and writes nothing. Return {"error": "...", "status": 503} yourself if you want your own message.
Add a second field and a second check. Append to fields in schemas/deals.json:
<!-- recipe: deals-follow-up-field -->
{"name": "follow_up_at", "type": "datetime", "label": "Follow up at"}
append to the locked_checks array you just added:
<!-- recipe: deals-follow-up-check-entry -->
{"name": "follow_up", "object": "hook_deals", "function": "FOLLOW_UP_CHECK",
"on": {"create": true, "update": ["follow_up_at"], "delete": false}}
and add this to objects/hook/deals.py, below LOCKED_CHECK:
<!-- recipe: deals-follow-up-check -->
from datetime import datetime, timezone
def as_utc(text):
"""A stored datetime as an aware UTC datetime. Raises ValueError if it is not one."""
when = datetime.fromisoformat(text.strip().replace("Z", "+00:00"))
if when.tzinfo is None:
return when.replace(tzinfo=timezone.utc) # naive means UTC here
return when.astimezone(timezone.utc)
def FOLLOW_UP_CHECK(request):
text = (request.get("record") or {}).get("follow_up_at", "")
if not text:
return None # the field is optional
if as_utc(text) <= datetime.now(timezone.utc): # an unparseable value raises: 503
return {"error": "A follow-up must be in the future.", "status": 409}
return None
With that, Z, +02:00 and offset-less values all compare correctly, a past one is 409 check_refused, and a value as_utc cannot read is 503 check_unavailable, never a quiet allow.
What to know, each verified in object_records and by tests/test_package_recipes.py:
- A check may read the current time. It is ordinary Python, loaded
without a sandbox; the only things it may not do are write or run another object. Dates are YYYY-MM-DD strings, which sort in date order, and the record it receives holds strings (see the wire).
recordis the row as it will be stored (on an update, the stored row
with the changes applied); existing is the row on file, read under the lock (None on a create). Return None to allow, or {"error": "...", "status": 409} (any 4xx) to refuse. The refusal reaches the client as 409 {"code": "check_refused", "check": "close_date", "error": "A deal cannot close in the past."}.
- It decides at write time only, and only for writes
onselects. Here
update: ["close_on"] means a deal whose date has since passed can still have its title changed, and is judged again the moment its date is touched. A rule that must hold as time passes is not a write rule.
- The object does not have to live in the same package as the schema: it
is looked up by id among the installed objects. Shipping it beside the schema is the convention, and a check in another package needs that package in dependencies. Install does not check that the object exists; a check whose object is missing refuses every write it selects with 503 check_unavailable, which is why the recipe is tried before it is shipped.
- A check with
reads(other collections) also takes a lock that every write
to those collections takes; a check of the record's own fields needs none and costs one flock round trip. Details, failure modes and cost: Locked checks.
A requirement another collection decides
"A purchase order number is required when the deal's type says so" is a required_when whose condition lives in another collection, and required_when reads only the record. The way through, used by app-finance's expense categories (expense-substantiation.md), is to copy the condition onto the record and let three tools each do the part only it can:
- a pre-write hook stamps what the other collection says
(po_required) on every API write, so nobody has to type it;
required_whenon the stamped field makes it binding, declared, for
every writer;
- a locked check refuses a stamp that disagrees with the other
collection, inside the write lock and for every writer, so a writer below the hook (an import, an action) cannot skip the rule by leaving the stamp out.
The stamp is also the point-in-time record of the rule that applied (logic-decisions.md #1). Six changes to the base deals package.
1. packages/deals/schemas/deal_types.json (a new file):
<!-- recipe: deals-type-schema -->
{
"name": "deal_types",
"title": "Deal Types",
"version": 1,
"fields": [
{"name": "id"},
{"name": "name", "type": "text", "required": true},
{"name": "requires_po", "type": "boolean", "default": "false"}
]
}
2. dbbasic-package.json: merge these keys into the top level (they replace objects and schemas; deal_types is listed first so its schema exists before a deal points at it):
<!-- recipe: deals-type-manifest -->
{
"objects": [{"id": "hook_deal_po", "path": "objects/hook/deal_po.py"}],
"schemas": [{"collection": "deal_types", "path": "schemas/deal_types.json"},
{"collection": "deals", "path": "schemas/deals.json"}]
}
3. permissions/rules.json: append this object to the rules array:
<!-- recipe: deals-type-rule -->
{"effect": "allow", "principal": "registered", "actions": ["read"],
"collection": "deal_types",
"reason": "everybody filing a deal needs to see the types and what each requires"}
4. schemas/deals.json: append these three field objects to the fields array:
<!-- recipe: deals-type-fields -->
[
{"name": "deal_type_id",
"relation": {"collection": "deal_types", "display_field": "name", "requires": "read"}},
{"name": "po_required", "type": "boolean"},
{"name": "po_number", "type": "text",
"validation": {"required_when": {"po_required": "true", "status": ["won"]}}}
]
5. schemas/deals.json: merge these keys into the schema's top level:
<!-- recipe: deals-type-keys -->
{
"hooks": {"before_write": "hook_deal_po"},
"locked_checks": [
{"name": "po_stamp", "object": "hook_deal_po", "function": "LOCKED_CHECK",
"reads": ["deal_types"],
"on": {"create": true, "update": ["deal_type_id", "po_required"], "delete": false}}
]
}
6. packages/deals/objects/hook/deal_po.py (a new file):
<!-- recipe: deals-type-hook -->
import os
import object_records
def requires_po(deal_type_id, base):
""""true" or "false", as the deal type says. Raises if the type cannot be read."""
if not deal_type_id:
return "false"
row = object_records.get_collection_record("deal_types", deal_type_id, base_dir=base)
return "true" if row.get("requires_po") == "true" else "false"
def BEFORE_WRITE(request):
if request["action"] not in ("create", "update"):
return None
record = dict(request["record"])
base = os.environ.get("DBBASIC_DATA_DIR", "data")
record["po_required"] = requires_po(record.get("deal_type_id", ""), base)
return {"record": record}
def LOCKED_CHECK(request):
record = request["record"]
wanted = requires_po(record.get("deal_type_id", ""), request["base_dir"])
if (record.get("po_required") or "false") != wanted:
return {"error": f"po_required must be {wanted}, as the deal type says.", "status": 409}
return None
With a type "Enterprise" (requires_po: true) made by an admin:
| Request | Answer |
|---|---|
ann POST a deal of that type | 201, po_required: "true" (stamped; she did not send it) |
ann PUT {"status": "won"} | 400 Record field 'po_number' is required when po_required is true and status is won |
ann PUT {"status": "won", "po_number": "PO-1"} | 200 |
ann POST a deal with no type, then PUT won | 200: po_required is false |
a writer below the hook creates one with po_required: "false" | CheckRefusedError (over HTTP: 409 check_refused), nothing written |
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 |
This hook restamps on every write, which is the simple choice. app-finance's expense hook restamps only when the stamp is judged (a new category or amount, a move into submitted or approved), so an approved expense keeps the rule it was approved under for good; object_expense_rules.stamps_are_judged is that decision written down.
The check reads deal_types, so every write to a deal type waits on the same lock: a type changed in the middle of a deal's write cannot slip between the check and the append. A hook that cannot read the type raises, which refuses the write (fail closed); so does the check (503).
An action that is the grant
Some actions exist to write what their caller may not write over the record API. app-counter's are the example: a cashier records a payment, a credit note, a refund or a waste stock move whose relation declares requires: update on an invoice, payment or product the cashier may only read. That is deliberate (giving cashiers update on invoices would let them reprice and void bills), so these role-granted actions are exempt from Access.relation_refusal: asking it would refuse the very write the action is for. The action is the grant, and therefore it must check, itself, what the relation check and the record API would otherwise have checked:
- The caller's role. The server asks the
executerule only with
enforcement on. Ask it inside the action too, from the rules that already name the roles (object_corrections.staff_refusal(access, object_id, doing=...) counts only role grants, admins and denies), so it holds with enforcement off and a plain user is refused. Where only some of the action's roles may do the expensive part, ask object_corrections.role_grants(access, action, collection=..., record=...): the same role-only question for any action, with the owner fallback off, so owning the row never reads as holding the role. app-disputes' resolve action pays out only for a role that may update every dispute (manager, owner), while a cashier may close their own as no_action.
- The record's state. Only the states the action is for: a counter
payment only for an issued invoice (not a draft, a void, a quote or a credit note) with money open, whichever way the record was named.
- Scope. Read a record whose reach the caller's own read decides (the
order, the invoice) through object_access as the caller. Where the action itself is the grant for a record the role does not read (the product a cashier writes off), read it under the action's authority only after the role check, still honour a deny rule that names the caller (object_corrections.denied_by_rule), and do not widen the role's read grants to make the lookup work. Either way a refused record gets the answer a missing one gets, without echoing the id, so the action is no oracle for ids. When the action pays out of a record the caller may only read, check that the records it combines belong together: app-disputes pays out of an order only through that order's own bill and payments, of the order's own account (orders.invoice_id is not a validated pointer), instead of asking for an update right on the order that no staff role should hold.
- Limits. Anything the caller may do alone only up to a setting (a
refund amount, a waste quantity) needs an approval above it that names the item it approves and is spent once; an approval that names no item is refused when it is written and not honoured if one is already on file. A limit that is unset or unreadable fails closed unless the shop's ordinary work needs a small default, and the description says which.
Refuse before the first write, and say in the action's docstring which of these it relies on.
Seeded Views And Site Routes
Most app pages are not code. A page is a record in the views collection whose blocks column says what to draw, and a row in site_routes that points a URL at the renderer. A package ships both as seed files.
seed/views.tsv (first row is the header, tab-separated):
| Column | Meaning |
|---|---|
id | the record id; unique across every package, so prefix it (view_deals) |
title | required; the page heading |
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 |
layout | single (default), two_column or grid |
blocks | a JSON list of blocks, on one line (below) |
owner_id | leave blank for a package's page |
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 |
pinned | true puts it in the nav app switcher |
created_at | any timestamp |
seed/site_routes.tsv:
| Column | Meaning |
|---|---|
id | the row id |
pattern | /deals, /deals/{deal_id} or /deals/{deal_id:uuid} (:uuid only matches a UUID) |
object_id | site_view_render for a view |
priority | an integer; the lowest wins, and a tie goes to the pattern with more literal segments |
host | optional; the row applies to that host only |
id pattern object_id priority
route_deals /deals site_view_render 20
route_deals_detail /deals/{deal_id} site_view_render 10
id title route layout blocks owner_id is_public pinned created_at
view_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
view_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
To wire them in: add both seed files to the manifest ({"collection": "views", "path": "seed/views.tsv"} and the same for site_routes), list app-views in dependencies (it ships the views schema and the site_view_render object, and it is not installed for you), and run the server with DBBASIC_ENABLE_SITE_ROUTES=true (routes are off by default; see site-routing.md). Each view's route and its site_routes row must say the same pattern: the renderer finds the view by matching the request against the views' route columns. Two reminders: a changed row of a shipped view reaches boxes that already have it by the rule in the next section (keep the id), and the TSV cannot hold a tab or a newline inside blocks, so keep each block list on one line.
Changing a seeded row in a new version
Keep the row's id, put the new value in the seed file, bump the package version and reinstall as for any upgrade (allow_replace). Do not add a second row for the same route: two views answering one route collide, and the renderer takes the first it finds. The install decides column by column, so a box's own edits are never lost:
- At every install it records, for each seeded row and column, a hash of what
the package shipped and of what the row held right after it was written (data/package_baselines/<package>.json, key seed_rows; hashes, never the values). id, created_at and updated_at are not tracked.
- A column the new version changed, whose live value is still what the last
install wrote, is replaced. The seed entry of the install result lists those ids under replaced, and its status is merged.
- A column the new version changed, whose live value is something else (an
operator edited it through the API or a form), is kept. It is listed under kept (id, columns, reason: "edited") and as a warning in the result, and the install goes on. The same column the package did not change is never touched, edited or not, and says nothing.
- A box installed before rows were tracked has no baseline, and an edit looks
exactly like an old default. A row there that already equals the new value is adopted silently; one that differs is kept with reason: "no baseline". Once it matches (edit it by hand, e.g. PUT /collections/views/records/view_notes with the new blocks, or delete it and reinstall so the shipped row comes back) later versions flow.
- A row the collection refuses to update is kept with the refusal's code, and
never fails the install.
Example: view_notes ships [{"kind": "list", "collection": "notes"}]. Version 0.2.0 adds "subtitle_field": "owner_id" to its blocks. A box that never touched the row gets the new blocks on reinstall; a box whose operator retitled the page keeps that title and still gets the new blocks; a box whose operator rewrote blocks keeps theirs and the install says so. A page and its route are two seed rows (views and site_routes): if you change a route, change both, and each is decided on its own. A row removed from the seed file stays on boxes that have it, and a row an operator deleted is added back by the next install, as before. tests/test_seed_row_upgrade.py runs every case above. Check what your own change does with --rows (see Try Your Change) on a box built from the old version.
Blocks. kind is one of list, form, detail, related, thread, count, aggregate, markdown, reader, object. An unknown kind or key is not an error at runtime, it is a placeholder card or silently ignored, so check them with the DRON schema instead: dron/dron-view.schema.json describes every kind and option with a sentence each, and tests/test_dron_schema.py validates every shipped views.tsv against it, and every site_routes.tsv, so a misspelt option fails there (python -m pytest tests/test_dron_schema.py -k deals). The list block's options:
| Option | Does |
|---|---|
collection | required |
title | a heading above the list |
search | true: a search box (text search over the schema's search.fields) |
sort | true: a Newest/Oldest select; "oldest" starts oldest first; always by created_at |
sort_by, sort_dir | sort by this field instead, asc or desc (default desc) |
add, add_label | true: a button that opens the generated create form |
owner_scoped | true: ask only for the viewer's own rows. A request, not access control |
where | a standing narrowing, {field: "value"}, equality only, applied after the permission filter; keeps the table, filter bar and realtime |
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) |
href_template, href_field | where a row title links, when not /<collection>/<id> |
row_actions: false, link: false | no edit/delete buttons, no detail link: for logs and reports |
row_limit | rows drawn before "Show all" (default 50) |
filters, limit | avoid: they swap in a bare list of titles with none of the above. Use where and row_limit |
Which list modes show list_fields. The mode is views.list_mode in the collection's schema, not in the block.
list_mode | Shows |
|---|---|
table | one column per views.list_fields entry (every field when none is listed), relation columns by label, headers sort |
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 |
tree | a title per node, nested by views.tree.parent_field (default parent_id); no list_fields |
calendar | a title per day, by views.calendar.date_field; no list_fields |
absent, cards, feed | rows of avatar, title, created date and tags, plus the block's subtitle_field; no list_fields |
A mode whose field cannot be found (no enum for a board, no self-relation for a tree) falls back to the row list with a notice. views.filter_fields (enum and boolean fields) adds a filter bar above every mode.
Semantics At A Glance
Small facts that were guessed at, in one place. The fuller account is linked.
older_than_days: Nis inclusive: a row matches when its age isNor
more days (age >= N). A date-only value (2026-11-20) ages in calendar days against the server's local date, so a date N days back matches today; a datetime ages in elapsed whole days. A blank, unparseable or future value never matches. ("Due before today" is older_than_days: 1 on a date.) Declared counts.
uniquecompares trimmed values and ignores blank ones."evt-1"and
"evt-1 " collide; a record whose key field is blank has no key. A violation is 409 {"code": "unique_violation", "error": <your message, else a generated sentence>, "fields": [...], "scope": [...]}; the id of the record holding the key is not returned. ignore_case is opt-in. (validation-and-logic.md)
locked_whenrefuses with409 record_locked, andfieldslists the
frozen fields the write tried to change ([] for a delete). allow_delete defaults to false: a settled record cannot be deleted. Judged by the stored record, for every writer, the admin token included.
- No status means "done". Only the
transitionsmap says where a value may
go; a value with no entry is terminal. done, closed, won are your words.
- Roles are assigned on the user (
roleswhen the user is created) and in
the policy's user_roles; rules match them as role:<name>. Try Your Change.
- Schema validation of your package is
tests/test_dron_schema.py, with no
jsonschema package needed. Searching is GET /api/search?q=...&collections=<c>; GET /collections/<c>/records takes limit, offset and field filters (field=value, field.op=value; ops eq ne in gte lte gt lt), and ?search=ann is refused 400 as an unknown field. q and sort are reserved there and ignored.
A Minimal Working Example
packages/hello-world/ in this repository is the smallest complete package. packages/admin-write-probe/ is the smallest complete app-shaped package: one HTML page object, one schema, one seed file, exercising records end to end. packages/app-projects/ and packages/app-notes/ are the reference user apps: an owner-scoped schema with search metadata, permission rules granting signed-in users their own rows (row_filter on $user_id), and a signed-in page that reads and writes records with the visitor's session cookie. Start a new app package from app-notes.
app-notes also shows the public/private pattern: a boolean is_public field plus a second permission rule (principal: public, row_filter: {"is_public": "true"}) makes shared records readable by anyone across every surface — pages, records API, MCP, and search — with no visibility code in the app itself. Its permalink page (site_note_view) expects a site_routes record mapping /notes/{note_id:uuid} to it; route records are site data, so each deployment adds them next to its other routes.
Object files inside packages are normal DBBASIC objects. A package page that renders per-user content reads request["_identity"]; a package form posts to its own object id and writes records through the object runtime. Signed-in browser users carry their session cookie automatically.
Rules For Generated Packages
- Never put secrets, tokens, real hostnames, or private paths in package
content — packages are meant to be shareable source.
- Keep one package per app primitive; use
dependenciesto declare (not yet
resolve) cross-package needs.
- Bump the manifest's
versionon any content change so install changelogs and
restore points stay meaningful. (A schema's own version is a label, not a switch: what it does.)
- Prefer seed data that demonstrates the schema without pretending to be real
data.
- Dry-run output is the review artifact: a package that cannot explain itself
in a dry-run plan is not ready to install.