Walkthrough: the todo app
This page shows the whole process once, on the smallest app anyone could ask for — "I want to create a todo app" — using complete files from the repository rather than excerpts. An excerpt of generated code is unconvincing, because the reader assumes the messy parts were cropped. Every block below is the file as it sits in demos/todo/ at the version of these docs, pulled in at build time; nothing is retyped for the page. The one thing dropped is the title line of each markdown file — the section heading above the block stands in for it, so the page keeps a single top-level heading — and everything from the first line after it onward is shown.
Todo was chosen for the reason a todo app is usually a bad demo: the reader spends zero attention on the domain, so the process is the only thing on the page. Every other demo vertical makes you learn field service or bike repair first.
The chain is five files and one derivation step:
| step | file | who writes it |
|---|---|---|
| 1. The brief | spec/prompt.md | the customer, in one line |
| 2. The interview | spec/answers.md | the customer, answering the builder |
| 3. The concept | spec/concept.md | the builder; approved before any code |
| 4. The model | spec/model.ts | the builder — what exists, declared once |
| 5. What is derived | migrations, manifest, permissions, API, client | nobody — re-emitted, and gated |
| 6. The business logic | src/module.ts | the builder — the only code that is about todo |
Read it top to bottom. The point is at the end: the last file is the whole of the application code, and none of the tenancy, permissions or audit it runs under appears in it.
1. The brief
The prompt is one line, deliberately. A real brief is underspecified, and everything that follows was either asked for in the interview or assumed by the builder and written down in the concept's Assumptions section — never silently.
I want to create a todo app.
That is the whole prompt, deliberately. A real brief is underspecified — everything below it in spec/ was either asked for in the interview (see answers.md) or assumed by the builder and recorded in the concept's Assumptions section.
Keep this file short. Intent enters here; derived decisions belong in concept.md. If a correction cannot be expressed as something a customer would actually have said, that is a finding about the pipeline, not a reason to grow this file.
2. The interview
The design skill asks the questions the brief left open, in two rounds of a few each, recommending an answer to every one. Here every recommendation was accepted as offered, which is what a builder should expect for an app this plain.
The interview asked two rounds, five questions. Delivered as one block so a replay does not have to match question wording — the interview skill reads this, finds its frontier covered, and proposes.
- Who uses it: I share lists with people. I own my lists and can invite specific people to some of them; the rest stay private.
- Screens: a web UI.
- Anything automatic: no. Nothing on a timer — no due dates, no reminders, no recurring tasks.
- What a share allows: they can add items and tick them off, but not delete the list or share it onward.
- Accounts: I invite them by email. Nobody signs themselves up.
Every one of the five was the builder's recommended answer, accepted as offered.
3. The concept
The interview produces a concept — the design document the customer approves before a line of code is written. It is written for the customer, in their vocabulary, and it is the contract every later step is checked against: the cast in §6 becomes the seed, the scenario in §9 becomes the test, and the assumptions in §10 are the decisions taken on the customer's behalf, listed so they can be reversed while reversing is cheap.
Notice §3. Accounts, invitations, isolation between accounts, a permission check on every operation and an audit trail are listed under free from the platform. What is left under yours to build is lists, items and sharing — and that is the whole build.
1. What we're building & who uses it
A todo app. Anyone with an account owns lists; a list is private until its owner shares it with someone by email. There are two kinds of people, and they use the same app: the person who owns a list, and the person it was shared with.
2. The thing that moves through the system
Two nouns — a list, and the items on it. An item is open or done, and it can go back; that is the entire lifecycle. There are no stages to skip because there are no stages.
This is a record, not a workflow. It composes no engine, and that is a fact about the app rather than an omission.
3. What already exists vs. what's yours
Free from the platform: accounts and login, invitations, isolation between accounts, a permission check on every operation, an audit trail of every change, the database and its migrations, hosting.
Yours to build: lists, items, sharing.
That is the whole build. No engine is composed — nothing here has invariants beyond "you cannot touch a list nobody shared with you", and that is the platform's own.
4. Who can do what
The owner does everything to their own list: create it, rename it, delete it, add items, complete them, delete them, share it, revoke a share — and archive it or put it in the trash, and take it back out of either.
Someone the list is shared with can see it, add items, and tick items off — including un-ticking. They cannot delete items, delete the list, archive it, bin it, or share it onward.
Everyone else sees nothing. A list you have not been shared with is invisible: not its contents, not its name, not the fact that it exists. Asking for it directly by id is refused, not answered with an empty result.
Another account entirely reaches nothing at all.
Nobody can see money, because there is none.
5. Money & sign-off
Neither. Nothing is invoiced, quoted or paid for, and nothing needs approving before a step can happen.
6. The cast, roles, tenancy
Two tenants, always — the second exists to be attacked, which is how isolation is proven rather than claimed.
| who | where | what they are |
|---|---|---|
| Ada | tenant one | owns lists |
| Björn | tenant one | Ada shares a list with him |
| Cleo | tenant two | unrelated account; must reach nothing |
One role: member — anyone with an account can own lists. Sharing is per-list, not a role, which is the interesting part of this app's permission model: what Björn may do is decided by the share on that list, not by anything about Björn.
7. The data we'll store
- People — one row per person with an account here: who they are, when they joined. Lists hang off it, which is how "your lists" is a fact the system can follow rather than a filter the code has to remember.
- Lists — name, who owns it, when it was created.
- Items — which list they are on, what they say, done or not, who added them, when.
- Shares — which list, which person, and the email it was sent to.
- Invitations — which list, the address, who asked and when. One lasts until the address joins or the owner withdraws it.
The email is load-bearing. The sharing screen promises "shared with björn@example.com", and accounts are opaque ids, so the address needs a table of its own to come from. A promised human-readable string with no source table is a missing table.
8. The screens
- Your lists — the ones you own and the ones shared with you, marked which is which.
- A list — its items, tick to complete, add an item.
- Sharing — enter an email, see who the list is shared with and who is still invited, revoke a share, withdraw an invitation.
9. The scenario the test will replay
The happy path. Ada creates "Groceries" and adds milk. She shares it with Björn. Björn sees the list, adds bread, and ticks milk off. Ada sees both changes.
The denials that prove it.
- Björn cannot delete the list, and is refused when he tries.
- Ada's other list, "Work", is not shared. It does not appear in Björn's lists, and asking for it directly by id is refused.
- Cleo reaches nothing at all — not Ada's lists, not Björn's, not by id.
- A control alongside each: Björn can add and tick, so the closed doors are not passing because every door is shut.
Putting lists away (#119). Dana joins after everyone else and makes "Holiday" and "Taxes 2025".
- She archives "Taxes 2025". It leaves her lists, appears when she asks for her archive, and is still readable — archiving files a list away, it does not hide what is on it.
- She puts "Holiday" in the trash. It leaves her lists and shows in her trash; opening it is "not found", like a deleted list. Restoring it brings it back with its items.
- She bins the archived "Taxes 2025" and restores it: it comes back to the archive, not to her lists.
- Nobody else's trash shows her lists, and Björn — who can add to a list Ada shared with him — cannot archive or bin it.
- Emptying the bin is the delete that cannot be undone.
10. Assumptions
Decisions taken on the builder's behalf. Each is cheap to reverse now and expensive later.
- The product is called Todo.
- People you share with can add and complete, but cannot delete items or the list, and cannot share it onward.
- Ticking is reversible — completing something is not final.
- One role: anyone with an account can own lists. Sharing is per-list.
- Everyone uses the same app; there is no separate portal for people you share with.
- A list is shared with a person, not with a public link.
- Sharing with an address that has not joined sends an email, and the list arrives when that address joins. Signing in is joining, with the address the issuer verified.
- Revoking a share is possible, and takes effect immediately.
- Item text is ordinary personal data — nothing needing erasure beyond deleting it.
- English only.
- Archive and trash are two different things with two different permissions. An archived list is kept and readable; a binned list is gone until restored. Search finds items only on the lists you see in your lists.
11. Out of scope
Due dates, reminders and recurrence (the builder said no). Sub-tasks, attachments, comments, re-sharing, public links, search, and a mobile app.
Roles and permissions (generated)
| Role | What they can do |
|---|---|
admin | list:create — Create lists of your ownpeople:manage — Decide which members may use this workspace’s plugins |
member | list:create — Create lists of your own |
Shared one record at a time, without a role:
| Record | What the person it is shared with can do |
|---|---|
list | list:contribute — See a list, add items to it, and tick them off |
owner | list:archive — Archive a list, or bring it back from the archivelist:contribute — See a list, add items to it, and tick them offlist:manage — Rename, delete and share a list, and delete items on itlist:trash — Move a list to the trash, see what is in it, and restore it |
Entity model (generated)
Processes (generated)
No lifecycle is declared: nothing here moves through stages.
Decisions log
- 2026-10-18: The three sections above are generated by
substrat concept syncfrommodel.jsonandPERMISSIONS.md, andpnpm lint:conceptfails when they are stale. Add a line here, by hand, on every change to the model or to a permission. - 2026-10-18: PERMISSIONS.md re-emitted with its new Operations section, which names the key each operation declares it checks and what that check narrows to. No operation, key or role changed.
- 2026-11-05: Lists became searchable by name (
todo/search-lists,list.namein the search index), because the lists are paged now and finding one should not mean walking the pages. It checkslist:contributeper hit, assearch-itemsdoes; no key or role changed.list-itemsbecame kernel-composed (derive: 'list') and gained adonefilter and a sort bytext; its default order is still the id, so a cursor handed out before stays valid. - 2026-11-07: An owner can invite an address that has not joined (
todo/invite,todo/list-invites,todo/cancel-invite, theinviteentity). The email is queued in the operation, and a consumer oftodo.owner-joinedmakes the share, because a grant delegates and the person joining holds nothing on the list. All three operations checklist:manage; no key or role changed. - 2026-11-07:
todo/invitealso checkslist:contribute. The share an invitation becomes is made by a consumer, which re-checks nobody, so holdinglist:managealone let someone hand on a key they did not hold. No key or role changed, and an owner holds both. - 2026-11-07:
todo/joinno longer takesemail(K-61). The operation readsctx.verifiedEmail, which every door passes, and refuses a person with no verified address, so a typed address claims nothing. The host guard is gone. UnderOIDC_ALLOW_UNVERIFIED_EMAILa person can still sign in, but not join. - 2026-11-13: Todo can be the app a plugin takes its people from (
identity.person@1,docs/rfc/dependent-people.md). A member may be given plugin access (todo/grant-plugin-access,todo/revoke-plugin-access, theaccessentity), and a plugin asks who a login is withtodo/resolve-person, through the peer door. Two keys and one role are new:people:manage, held by the newadminrole (a member who also decides plugin access; Ada, in the dev cast), andpeople:resolve, declaredholder: 'system'and held only by thenotespeer. Nothing a member could do before changed. - 2026-11-13: An admin reads the members with whether each may use plugins (
todo/list-members,people:manage), for a Plugins screen in the account menu. No key or role changed. - 2026-11-13: A plugin may ask whether a person may see a list or an item (
todo/vouch-access, the new keypeople:vouch, declaredholder: 'system'and held only by thenotespeer), so a plugin that keeps notes on items shows them only to the people the item is shared with. It answers from the list's owner and its shares. The list screen shows the plugin's notes under each item. No role changed. - 2026-11-15: Todo can call Notes as the signed-in person (#3161): Todo keeps the person's refresh token for its session and trades it for a short-lived token Notes verifies itself. The other-verticals section of
PERMISSIONS.mdnow says a peer's admission also gates the calls it makes for a person. No key or role of Todo's changed.
4. The model
The approved concept becomes one TypeScript module declaring what exists: the entities and their fields, the operations over them, and the permission each operation checks. It is TypeScript rather than a schema language because the compiler checks the joins between those three things — an operation naming an entity that does not exist, an entityIdFrom naming no output field, a payload carrying an erasable field — and those joins are where the defects live. The model explains each declaration; this is what a complete one looks like.
Two lines carry the permission model. parents: ['owner'] on list is the edge the permission walk follows, so "your lists" is a fact the kernel can prove rather than a filter the code has to remember. And permission: { key: 'list:manage', entity: 'list', idFrom: 'listId' } on rename-list declares that the check is on that list, which the conformance kit then drives against the handler.
/**
* Todo's model — what exists, declared once (#697/#707).
*
* The concept is approved (`spec/concept.md`); this is its entity and operation
* surface, and everything downstream is derived from it: the migrations, the
* manifest, the route table, the permission registry, the API document.
*
* This vertical composes **no engine**. Nothing here has an invariant beyond
* "you cannot touch a list nobody shared with you", and that one is the
* platform's. An absent `engines` argument is a fact about the app, not an
* omission.
*/
import {
defineEntities,
defineOperations,
emitModel,
entityStateOutput,
personResolveInput,
personResolveOutput,
z,
} from '@substrat-run/contracts';
import { MAX_SEARCH_LIMIT } from '@substrat-run/kernel';
/**
* How much wider than the answer the handlers ask the index for.
*
* Every search here filters hits AFTER ranking — by list, or by which lists the
* caller reaches — and a ranked top-N filtered afterwards returns fewer than N.
* Asking for more is the only defence.
*/
export const SEARCH_OVERFETCH = 4;
/**
* This vertical's own cap, and deliberately NOT the kernel's.
*
* `ctx.search` clamps every ask to `MAX_SEARCH_LIMIT`, so a caller allowed to
* request the ceiling leaves the over-fetch no headroom at all: the ask and the
* answer become the same number and the filter above eats into the result. Deriving
* the bound keeps the two from drifting apart — raise the ceiling and this follows.
*/
export const TODO_SEARCH_MAX = Math.floor(MAX_SEARCH_LIMIT / SEARCH_OVERFETCH);
export const todoEntities = defineEntities({
/**
* A person who has an account in this scope — the thing their lists hang off.
*
* It exists because ownership has to be reachable by the permission walk. A
* list's owner cannot be a grant made by the operation that creates it:
* `ctx.grant` delegates what the caller already holds, and nobody holds
* anything on a list that did not exist a moment ago. So the grant is made
* once, per person, on THIS entity when they join, and every list they create
* links to it. The walk reaches list → owner and the answer follows.
*
* `id` is the principal id. One row per person, not per login.
*/
owner: {
table: 'todo_owners',
fields: z.object({
id: z.string(),
email: z.string(),
display_name: z.string(),
created_at: z.string(),
}),
key: ['email'],
erasable: ['email', 'display_name'],
},
/**
* A list. Private to its owner until a share exists for someone else.
*
* Archivable and trashable (#119), each under its own key: filing a finished list away and
* putting one in the bin are different acts, and an owner may be given one without the
* other. The kernel adds the two columns and leaves archived and binned lists out of
* `my-lists` unless they are asked for.
*
* A list left in the bin for 30 days is deleted for good, by `delete-list` — the same
* delete a person empties the bin with, so its items and shares go with it exactly as they
* would by hand.
*/
list: {
table: 'todo_lists',
fields: z.object({
id: z.string(),
owner_id: z.string(),
name: z.string(),
created_at: z.string(),
}),
parents: ['owner'],
archive: { permission: 'list:archive' },
trash: { permission: 'list:trash', purgeAfterDays: 30 },
},
/**
* An item on a list. `done` is a number because SQLite has no boolean and the
* row comes back as 0/1 — declaring `z.boolean()` here would emit the same
* INTEGER column while promising the reader a type the database cannot return.
*/
item: {
table: 'todo_items',
fields: z.object({
id: z.string(),
list_id: z.string(),
text: z.string(),
done: z.number(),
added_by: z.string(),
created_at: z.string(),
}),
parents: ['list'],
},
/**
* One person's access to one list.
*
* The email is here because the sharing screen promises "shared with
* björn@example.com" and principals are opaque ids — a promised string with no
* source table is a missing table. It is the only directly personal field in
* the app, so it is `erasable`, which also makes it uncarryable by any event.
*
* `key` is the composite it reads as: one share per person per list.
*/
share: {
table: 'todo_shares',
fields: z.object({
id: z.string(),
list_id: z.string(),
principal: z.string(),
email: z.string(),
created_at: z.string(),
}),
parents: ['list'],
key: ['list_id', 'principal'],
erasable: ['email'],
},
/**
* An address invited to a list, until that person joins. Its own entity rather than a share
* with no principal, because a share IS a person's access and this is nobody's yet.
*/
invite: {
table: 'todo_invites',
fields: z.object({
id: z.string(),
list_id: z.string(),
email: z.string(),
invited_by: z.string(),
created_at: z.string(),
}),
parents: ['list'],
key: ['list_id', 'email'],
erasable: ['email'],
},
/**
* A member who may use this workspace's plugins: the other apps of the tenant that take their
* people from here. A row is the access, and removing it takes the access away.
*
* Its own entity rather than a column on `owner`, because it is a decision somebody else made
* about a person, with its own author and date. `id` is the member's `owner` id.
*/
access: {
table: 'todo_plugin_access',
fields: z.object({
id: z.string(),
granted_by: z.string(),
created_at: z.string(),
}),
},
});
/**
* Three keys, and the split is the app's whole permission model.
*
* - `list:create` is held scope-wide by every member. It is the only one that
* can be, because creating a list is the one act with no entity to narrow to.
* - `list:manage` and `list:contribute` are granted per person on their OWN
* `owner` entity when they join, and reach their lists through the declared
* parent edge. Nobody holds either one scope-wide, which is what makes one
* member's lists unreachable to another.
* - Sharing narrows `list:contribute` onto ONE list for one person, so what
* Björn may do is a fact about *that list* rather than about Björn.
*
* Three more are about people rather than lists. `people:manage` is the workspace admin's:
* who may use the plugins. `people:resolve` and `people:vouch` are held by no person at all: a
* plugin holds them, as a peer, to ask who somebody signing in to it is, and whether they may
* see a list or an item it keeps something about.
*/
export const TODO_PERMISSIONS = [
'list:create',
'list:manage',
'list:contribute',
'list:archive',
'list:trash',
'people:manage',
'people:resolve',
'people:vouch',
] as const;
export const todoOperations = defineOperations(todoEntities, TODO_PERMISSIONS)({
/**
* Claim your account in this scope — the row every list hangs off.
*
* It exists because ownership is an entity, and an entity needs a moment it
* comes into being. Self-service and idempotent: joining twice is joining.
*/
'todo/join': {
summary: 'Claim your account in this workspace',
permission: 'list:create',
input: z.object({ displayName: z.string().min(1) }),
output: todoEntities.owner.fields,
http: { method: 'POST', path: '/join' },
emits: {
entity: 'owner',
entityIdFrom: 'id',
type: 'todo.owner-joined',
schemaVersion: 1,
piiClass: 'pseudonymous',
subjectId: 'id',
// `email` and `display_name` are erasable, so neither can ride here.
payload: ['id'],
},
},
'todo/create-list': {
summary: 'Create a list',
permission: 'list:create',
input: z.object({ name: z.string().min(1) }),
output: todoEntities.list.fields,
http: { method: 'POST', path: '/lists' },
emits: {
entity: 'list',
entityIdFrom: 'id',
type: 'todo.list-created',
schemaVersion: 1,
piiClass: 'none',
payload: ['id', 'name', 'owner_id'],
},
},
/**
* The proof walk. Owned lists and shared-with lists arrive in one answer, and
* a list nobody shared is not in it — filtered by a per-entity check, never by
* a WHERE clause on ownership.
*/
'todo/my-lists': {
summary: 'List the lists you own or have been shared',
narrows: {
reason: 'Returns only lists the caller owns or has been shared',
checks: ['list:contribute'],
},
// #119: the active lists unless the archive is asked for. The bin is its own read,
// `trashed-lists`, because who may look in it is a different question.
input: z.object({ view: z.enum(['active', 'archived']).optional() }),
output: todoEntities.list.fields,
// #811. The underlying walk IS kernel-composed — `created_at` with the id
// tie-break is exactly the `ORDER BY created_at, id` this shipped with — but
// visibility is decided by a per-row proof walk on top of it, so the handler
// walks with `pageVisible`, whose continuation hides the examined position (#2074).
// A short page can still carry a continuation at the scan budget.
paged: { over: { entity: 'list', sortable: ['created_at', 'name'] } },
http: { method: 'GET', path: '/lists' },
},
'todo/rename-list': {
summary: 'Rename a list',
permission: { key: 'list:manage', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string(), name: z.string().min(1) }),
output: todoEntities.list.fields,
http: { method: 'PATCH', path: '/lists/{listId}' },
patchException: 'This rename command requires a name; its handler writes only name.',
emits: {
entity: 'list',
entityIdFrom: 'id',
type: 'todo.list-renamed',
schemaVersion: 1,
piiClass: 'none',
payload: ['id', 'name'],
},
},
/**
* File a list away (#119). It leaves `my-lists` and stays readable — through the archive
* view, and by anyone it is shared with. The kernel checks `list:archive` on the list itself,
* so this cannot be done under `list:manage`.
*
* The four moves and the bin are DERIVED (#1773): each is the check and one kernel verb, so the
* platform writes them from the `archive` / `trash` declaration on `list`, and todo writes none.
*/
'todo/archive-list': {
summary: 'Archive a list',
derive: 'archive',
permission: { key: 'list:archive', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string() }),
output: entityStateOutput,
http: { method: 'POST', path: '/lists/{listId}/archive' },
},
'todo/unarchive-list': {
summary: 'Bring an archived list back',
derive: 'unarchive',
permission: { key: 'list:archive', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string() }),
output: entityStateOutput,
http: { method: 'POST', path: '/lists/{listId}/unarchive' },
},
/**
* Put a list in the bin (#119) — the delete a person can take back. Its items and shares
* are untouched, so a restore brings the whole list back as it was; `delete-list` is still
* the delete that cannot be undone.
*/
'todo/trash-list': {
summary: 'Move a list to the trash',
derive: 'trash',
permission: { key: 'list:trash', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string() }),
output: entityStateOutput,
http: { method: 'POST', path: '/lists/{listId}/trash' },
},
/** Take a list out of the bin, back to where it was — archived, if it was archived. */
'todo/restore-list': {
summary: 'Restore a list from the trash',
derive: 'restore',
permission: { key: 'list:trash', entity: 'list', idFrom: 'listId' },
// The one operation besides the delete that reaches a binned list; every other is refused
// `not_found` by the host before it runs.
trashed: 'admits',
input: z.object({ listId: z.string() }),
output: entityStateOutput,
http: { method: 'POST', path: '/lists/{listId}/restore' },
},
/**
* What is in YOUR bin. The kernel checks `list:trash` on every list it reads here, so a
* list somebody else binned never shows, however it reached the walk.
*/
'todo/trashed-lists': {
summary: 'The lists in your trash',
derive: 'trashed',
narrows: {
reason: 'Returns only binned lists the caller may restore',
checks: ['list:trash'],
},
output: todoEntities.list.fields,
paged: { over: { entity: 'list', sortable: ['created_at', 'name'] } },
http: { method: 'GET', path: '/lists/trash' },
},
'todo/delete-list': {
summary: 'Delete a list and everything on it',
permission: { key: 'list:manage', entity: 'list', idFrom: 'listId' },
// The permanent delete: it empties the bin, and it is what the 30-day horizon runs.
trashed: 'purges',
// Strict: a purge's parsed input is the id and nothing else (#119).
input: z.strictObject({ listId: z.string() }),
output: z.object({ id: z.string(), deleted: z.boolean() }),
http: { method: 'DELETE', path: '/lists/{listId}' },
emits: {
entity: 'list',
entityIdFrom: 'id',
type: 'todo.list-deleted',
schemaVersion: 1,
piiClass: 'none',
payload: ['id'],
},
},
'todo/list-items': {
summary: 'The items on a list',
// Kernel-composed: the WHERE, the keyset walk, the count and the indexes behind them are
// derived from `paged.over`, so there is no handler to keep in step with this declaration.
derive: 'list',
permission: { key: 'list:contribute', entity: 'list', idFrom: 'listId' },
// `limit` and `cursor` are NOT declared here: since #811 the platform parses
// the page trio with the one shared schema and merges it into the input, so
// the default and the `LIST_PAGE_MAX` ceiling are true of every paged read
// rather than of the ones whose author remembered to restate them.
//
// `done` is the one filter a person asks of a long list — what is left to do — and an
// equality on a declared column, so the kernel indexes it rather than the handler
// scanning. A number because SQLite has no boolean (see the entity).
input: z.object({ listId: z.string(), done: z.number().int().min(0).max(1).optional() }),
// The ENTRY, not the envelope: `paged` is what wraps it, here and in the document.
output: todoEntities.item.fields,
// A list's items are the one table here that grows without bound — one per line of
// shopping, forever. Keyset over the ULID id by default, which is creation-ordered
// for free and keeps every cursor handed out before this was kernel-composed valid
// (a walk whose sort is the id carries the id alone). `text` sorts alphabetically.
// `total` because the app renders a count beside the list; it costs a second
// query per request, which is why it is asked for rather than assumed.
paged: { over: { entity: 'item', sortable: ['id', 'text'], filterable: ['list_id', 'done'] }, total: true },
http: { method: 'GET', path: '/lists/{listId}/items' },
},
/**
* Search on ONE list (#827) — the read that `paged` above took away.
*
* Filtering `list-items` in the browser searched whatever page had loaded, which
* at forty items looked like search and at four thousand looked like a bug. This
* asks the index instead.
*
* A separate operation rather than a `q` on `list-items`: that read is sorted and
* paged, this one is ranked and capped, and one endpoint cannot carry both
* contracts. `GET /lists/{listId}/items/search` does not collide with the paged
* read — `mountOperations` registers a static segment ahead of its parameter
* sibling (#785).
*
* Permission is the ordinary entity-narrowed one: the caller either reaches this
* list or they do not, and one check settles it.
*/
'todo/search-list-items': {
summary: 'Find items on a list by text',
permission: { key: 'list:contribute', entity: 'list', idFrom: 'listId' },
input: z.object({
listId: z.string(),
// Two characters is the prefix index's floor. Declared here so a short term is
// a 400 naming the field, not a throw from inside the kernel.
q: z.string().min(2),
limit: z.number().int().positive().max(TODO_SEARCH_MAX).optional(),
}),
// Not a bare array: a capped read has to say it was capped, or the screen shows
// the first twenty of two hundred matches as though that were all of them.
output: z.object({
results: z.array(todoEntities.item.fields),
limit: z.number().int(),
capped: z.boolean(),
}),
http: { method: 'GET', path: '/lists/{listId}/items/search' },
},
/**
* Search across every list the caller can reach — "where did I put milk?".
*
* The same `narrows` shape as `my-lists`, and for the same reason: nobody holds
* `list:contribute` scope-wide, so the answer is assembled by asking, per list,
* whether this caller reaches it. The index is scope-wide and checks nothing —
* `ctx.search` never does — so the filter after it is what keeps one member's
* items out of another's results.
*
* The trap here is real and documented (concepts/reads.md): a ranked top-N
* filtered afterwards returns FEWER than N. The handler over-fetches on purpose.
*/
'todo/search-items': {
summary: 'Find items across the lists you can see',
narrows: {
reason: 'Returns only items on lists the caller owns or has been shared',
checks: ['list:contribute'],
},
input: z.object({
q: z.string().min(2),
limit: z.number().int().positive().max(TODO_SEARCH_MAX).optional(),
}),
output: z.object({
results: z.array(todoEntities.item.fields),
limit: z.number().int(),
capped: z.boolean(),
}),
http: { method: 'GET', path: '/items/search' },
},
/**
* Find one of your lists by name — the search beside `my-lists`, for when there are
* more lists than one page shows.
*
* The same `narrows` walk as `my-lists`, over search hits instead of every row: the
* index is scope-wide and checks nothing, so the per-list check after it is what keeps
* someone else's list out of the answer. Active lists only — the kernel leaves archived
* and binned rows out of `ctx.search`, as it does out of `ctx.page`.
*/
'todo/search-lists': {
summary: 'Find your lists by name',
narrows: {
reason: 'Returns only lists the caller owns or has been shared',
checks: ['list:contribute'],
},
input: z.object({
q: z.string().min(2),
limit: z.number().int().positive().max(TODO_SEARCH_MAX).optional(),
}),
output: z.object({
results: z.array(todoEntities.list.fields),
limit: z.number().int(),
capped: z.boolean(),
}),
http: { method: 'GET', path: '/lists/search' },
},
'todo/add-item': {
summary: 'Add an item to a list',
permission: { key: 'list:contribute', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string(), text: z.string().min(1) }),
output: todoEntities.item.fields,
http: { method: 'POST', path: '/lists/{listId}/items' },
emits: {
entity: 'item',
entityIdFrom: 'id',
type: 'todo.item-added',
schemaVersion: 1,
piiClass: 'none',
payload: ['id', 'list_id', 'text', 'added_by'],
},
},
/** Ticking is reversible, so this sets the state rather than completing. */
'todo/set-item-done': {
summary: 'Tick an item off, or put it back',
// The id is not in the input: the check is on the LIST this item sits on.
permission: { key: 'list:contribute', entity: 'list', resolved: 'the list the item is on' },
input: z.object({ itemId: z.string(), done: z.boolean() }),
output: todoEntities.item.fields,
http: { method: 'POST', path: '/items/{itemId}/done' },
emits: {
entity: 'item',
entityIdFrom: 'id',
type: 'todo.item-done-changed',
schemaVersion: 1,
piiClass: 'none',
payload: ['id', 'list_id', 'done'],
},
},
'todo/delete-item': {
summary: 'Delete an item',
permission: { key: 'list:manage', entity: 'list', resolved: 'the list the item is on' },
input: z.object({ itemId: z.string() }),
output: z.object({ id: z.string(), deleted: z.boolean() }),
http: { method: 'DELETE', path: '/items/{itemId}' },
emits: {
entity: 'item',
entityIdFrom: 'id',
type: 'todo.item-deleted',
schemaVersion: 1,
piiClass: 'none',
payload: ['id'],
},
},
/**
* Sharing. The event is about a share, whose subject is a person, so it is
* classified and keyed — and the address itself cannot ride along, because
* `share.email` is erasable. `principal` is what an erasure would key on.
*/
'todo/share-list': {
summary: 'Share a list with someone by email',
permission: { key: 'list:manage', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string(), email: z.string().email() }),
output: todoEntities.share.fields,
http: { method: 'POST', path: '/lists/{listId}/shares' },
emits: {
entity: 'share',
entityIdFrom: 'id',
type: 'todo.list-shared',
schemaVersion: 1,
piiClass: 'pseudonymous',
subjectId: 'principal',
payload: ['id', 'list_id', 'principal'],
},
},
/**
* Invite an address to a list. Someone who has joined gets the share at once; anyone else gets
* an email, and the share when they join. `status` says which, because the sharing screen
* shows the two differently.
*/
'todo/invite': {
summary: 'Invite someone to a list by email',
permission: { key: 'list:manage', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string(), email: z.string().email() }),
output: z.object({ status: z.enum(['shared', 'invited']), id: z.string(), email: z.string() }),
http: { method: 'POST', path: '/lists/{listId}/invites' },
emits: {
entity: 'invite',
entityIdFrom: 'id',
type: 'todo.invite-sent',
schemaVersion: 1,
piiClass: 'none',
payload: ['id'],
},
},
/** Who is invited and has not joined yet. Owner-only, as `list-shares` is. */
'todo/list-invites': {
summary: 'Who is invited to this list and has not joined',
derive: 'list',
permission: { key: 'list:manage', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string() }),
output: todoEntities.invite.fields,
paged: { over: { entity: 'invite', sortable: ['created_at'], filterable: ['list_id'] } },
http: { method: 'GET', path: '/lists/{listId}/invites' },
},
'todo/cancel-invite': {
summary: 'Withdraw an invitation',
permission: { key: 'list:manage', entity: 'list', resolved: 'the list the invite is on' },
input: z.object({ inviteId: z.string() }),
output: z.object({ id: z.string(), cancelled: z.boolean() }),
http: { method: 'DELETE', path: '/invites/{inviteId}' },
emits: {
entity: 'invite',
entityIdFrom: 'id',
type: 'todo.invite-cancelled',
schemaVersion: 1,
piiClass: 'none',
payload: ['id'],
},
},
/**
* Who a list is shared with. Owner-only: the members of a share are the
* owner's business, not each other's.
*/
'todo/list-shares': {
summary: 'Who this list is shared with',
derive: 'list',
permission: { key: 'list:manage', entity: 'list', idFrom: 'listId' },
input: z.object({ listId: z.string() }),
output: todoEntities.share.fields,
// A share list is short in every plausible app and unbounded all the same —
// one row per person a list is shared with, and nothing caps that. `list_id`
// is the filter the route already narrows by, declared so the kernel composes
// it and indexes `(list_id, created_at, id)` behind it.
paged: { over: { entity: 'share', sortable: ['created_at'], filterable: ['list_id'] } },
http: { method: 'GET', path: '/lists/{listId}/shares' },
},
'todo/revoke-share': {
summary: 'Revoke someone’s access to a list',
permission: { key: 'list:manage', entity: 'list', resolved: 'the list the share is on' },
input: z.object({ shareId: z.string() }),
output: z.object({ id: z.string(), revoked: z.boolean() }),
http: { method: 'DELETE', path: '/shares/{shareId}' },
emits: {
entity: 'share',
entityIdFrom: 'id',
type: 'todo.share-revoked',
schemaVersion: 1,
piiClass: 'none',
payload: ['id'],
},
},
/**
* The workspace's members, each with whether they may use its plugins: the admin's screen for
* deciding plugin access. Members only, never list invitations, which are no person yet.
*/
'todo/list-members': {
summary: 'The workspace’s members, and which of them may use its plugins',
permission: 'people:manage',
output: todoEntities.owner.fields.extend({ plugin_access: z.boolean() }),
paged: { over: { entity: 'owner', sortable: ['created_at', 'display_name'] } },
http: { method: 'GET', path: '/members' },
},
/**
* Let a member use the plugins. Idempotent: a member who has access keeps the row they have.
* The event is about a person, so it is classified and keyed on them.
*/
'todo/grant-plugin-access': {
summary: 'Let a member use this workspace’s plugins',
permission: 'people:manage',
input: z.object({ memberId: z.string() }),
output: todoEntities.access.fields,
http: { method: 'POST', path: '/members/{memberId}/plugin-access' },
emits: {
entity: 'access',
entityIdFrom: 'id',
type: 'todo.plugin-access-granted',
schemaVersion: 1,
piiClass: 'pseudonymous',
subjectId: 'id',
payload: ['id'],
},
},
/**
* Take it away again. A plugin learns of it the next time it asks about the person, which is
* within the time it keeps an answer for.
*/
'todo/revoke-plugin-access': {
summary: 'Stop a member using this workspace’s plugins',
permission: 'people:manage',
input: z.object({ memberId: z.string() }),
output: z.object({ id: z.string(), revoked: z.boolean() }),
http: { method: 'DELETE', path: '/members/{memberId}/plugin-access' },
emits: {
entity: 'access',
entityIdFrom: 'id',
type: 'todo.plugin-access-revoked',
schemaVersion: 1,
piiClass: 'pseudonymous',
subjectId: 'id',
payload: ['id'],
},
},
/**
* The person contract (`identity.person@1`): who is this login, asked by a plugin when
* somebody signs in to it. The shapes are the contract's own, so a plugin written against
* the contract works against this app unchanged.
*
* No `http`: it is called through the peer door and nowhere else, and `people:resolve` is
* held by the peers the manifest names, never by a person.
*/
'todo/resolve-person': {
summary: 'Who a login is here, for a plugin of this workspace',
permission: 'people:resolve',
input: personResolveInput,
output: personResolveOutput,
},
/**
* Whether a person may see a list, or the list an item is on: asked by a plugin that keeps
* something about Todo's lists (Notes, about items) before it shows or adds it. Answered from
* the list's owner and its shares, which are written in the same transaction as the grants
* they mirror; an operation cannot ask the kernel about another principal's access, which is
* what this stands in for. A binned list is seen by nobody, as everywhere else.
*
* No `http`, like `resolve-person`: the peer door is the only way in.
*/
'todo/vouch-access': {
summary: 'Whether a person may see a list or an item, for a plugin of this workspace',
permission: 'people:vouch',
input: z.object({
principal: z.string().min(1),
listId: z.string().min(1).optional(),
itemId: z.string().min(1).optional(),
}),
output: z.object({ visible: z.boolean(), listId: z.string().nullable() }),
},
});
export const todoModel = emitModel(todoEntities, { operations: todoOperations });5. What is derived
From spec/model.ts, without another line being written:
- The migrations —
src/migrations.generated.ts, theCREATE TABLEfor each entity and the indexes behind each declared sort and filter, re-emitted bypnpm lint:migrations. - The manifest — assembled from the model's two halves at mount time: the permission registry, the entity relations the permission walk follows, the events each operation emits, the paged lists.
PERMISSIONS.md— the human checkpoint: every key, what it means, and which role holds it, rendered bypnpm lint:permissionsand checked in, so a widened role cannot merge without appearing in the diff.model.json— the model as data, for tools that do not run TypeScript; gated bypnpm lint:model --check.- The HTTP surface — each operation's
http: { method, path }becomes a route, its input schema becomes the request validation the host applies before the handler runs, andopenapi.jsonwith a Scalar page is served from the same catalogue (pnpm lint:api). - The browser client —
app/src/api.generated.ts: typed methods for every operation, the entity interfaces, the pagedLinkwalk (pnpm lint:client). CONFORMANCE.md— the receipt saying which declared entity checks the kit drives against the running handler, and which it cannot, by name (pnpm lint:conformance).
Each of those carries the three marks a generated file must: the .generated suffix or a GENERATED first line, a header naming the producer and the source, and a --check re-emit in CI. The third is the only one that enforces anything.
6. The business logic
What is left is the one file that is about todo: what it means to share a list, and who may do what to one. Every handler opens with the check its declaration promised, and the satisfies clause at the bottom is what makes a handler that disagrees with its declaration — or one declared and not implemented — a compile error naming the method.
Sharing is the part worth reading twice. share-list is one ctx.grant and revoke-share is one ctx.revoke: the kernel narrows list:contribute onto this list for this person, re-checks that the caller holds it there, and records it transactionally with the operation. Nothing else in the app has to remember that Björn may touch this list — the grant is the fact, and every check reads it.
share-list finds the person by the address they joined with, so that address has to be theirs. The operation cannot see the session, so the dev server's src/app.ts checks it on the scope stub every door invokes through — the HTTP route and the MCP tool alike: the email given must be the session's own, and the issuer must have said email_verified: true about it (identifyEmail from @substrat-run/oidc-rp). Do the same wherever an address decides who receives access.
/**
* Todo's operations — the business logic, and nothing else.
*
* Everything structural is derived from `spec/model.ts`: the migrations were
* emitted from the entities, the manifest is assembled from both halves of the
* model, and the route table is derived at mount time. What is left in this file
* is what only a person could decide — what it MEANS to share a list, and who
* may do what to one.
*
* `operationsFor(todoOperations)` is the join: a handler whose input or return
* disagrees with the declared operation, one declared and not implemented, or
* one implemented and not declared, is a compile error naming the exact method.
*/
import {
mapPage,
pageVisible,
dataSubjectId,
substratError,
z,
type EntityRow,
type PrincipalId,
} from '@substrat-run/contracts';
import {
assertAllowed,
DEFAULT_SEARCH_LIMIT,
MAX_SEARCH_LIMIT,
requestEmail,
ulid,
type ConsumerHandler,
type ModuleRegistration,
type OperationContext,
operationsFor,
} from '@substrat-run/kernel';
import { SEARCH_OVERFETCH, todoEntities, todoOperations } from '../spec/model.js';
import { TODO_PERM, todoManifest } from './manifest.js';
import { todoMigrations } from './migrations.generated.js';
type OwnerRow = EntityRow<typeof todoEntities, 'owner'>;
type ListRow = EntityRow<typeof todoEntities, 'list'>;
type ItemRow = EntityRow<typeof todoEntities, 'item'>;
type ShareRow = EntityRow<typeof todoEntities, 'share'>;
type InviteRow = EntityRow<typeof todoEntities, 'invite'>;
type AccessRow = EntityRow<typeof todoEntities, 'access'>;
const listRef = (id: string) => ({ entityType: 'list', entityId: id });
/**
* Ask the index for more than the caller wants (#827).
*
* `SEARCH_OVERFETCH` is a guess, and an honest one: it is not a guarantee, which is
* why both handlers still report `capped` rather than pretending the answer is
* complete. The `min` is a backstop rather than the design — `TODO_SEARCH_MAX` is
* derived so that the widened ask stays inside the kernel's ceiling, and the clamp
* only ever fires if that derivation is broken.
*/
const overfetch = (limit: number) => Math.min(limit * SEARCH_OVERFETCH, MAX_SEARCH_LIMIT);
/** Hits carry the rank; rows carry the shape. Re-join them in the index's order. */
function rankOrder<R extends { id: string }>(hits: readonly { id: string }[], rows: readonly R[]): R[] {
const byId = new Map(rows.map((row) => [row.id, row]));
return hits.map((hit) => byId.get(hit.id)).filter((row): row is R => row !== undefined);
}
/**
* The list, or a refusal — never a silent empty answer.
*
* A binned list never gets this far in an operation addressed by `listId`: the HOST refuses it
* `not_found` before the handler runs, unless the operation declares `trashed` (#119). So this
* reads the row and nothing else.
*/
function listOrThrow(ctx: OperationContext, id: string): ListRow {
const row = ctx.sql.query<ListRow>('SELECT * FROM todo_lists WHERE id = ?', [id])[0];
if (!row) throw substratError('not_found', `list not found: ${id}`);
return row;
}
/**
* The list an operation reached through something else — an item, a share. The host cannot see
* which list that is (the check is `resolved`), so this asks the state itself: a binned list is
* gone from everyone's point of view until it is restored, its items and shares with it. K-45
* names these operations as the ones still holding their own check.
*/
function liveListOrThrow(ctx: OperationContext, id: string): ListRow {
const row = listOrThrow(ctx, id);
if (ctx.entityState(listRef(id)) === 'trashed') throw substratError('not_found', `list not found: ${id}`);
return row;
}
/** The list an item sits on — every item permission is really the list's. */
function itemAndList(ctx: OperationContext, itemId: string): { item: ItemRow; list: ListRow } {
const item = ctx.sql.query<ItemRow>('SELECT * FROM todo_items WHERE id = ?', [itemId])[0];
if (!item) throw substratError('not_found', `item not found: ${itemId}`);
return { item, list: liveListOrThrow(ctx, item.list_id) };
}
const escapeHtml = (text: string): string =>
text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
const ownerByEmail = (ctx: OperationContext, email: string): OwnerRow | undefined =>
ctx.sql.query<OwnerRow>('SELECT * FROM todo_owners WHERE email = ? COLLATE NOCASE', [email])[0];
/** One person's access to one list: the row, the grant and the event, or the share they have. */
async function shareWith(ctx: OperationContext, listId: string, invitee: OwnerRow): Promise<ShareRow> {
const existing = ctx.sql.query<ShareRow>('SELECT * FROM todo_shares WHERE list_id = ? AND principal = ?', [
listId,
invitee.id,
])[0];
if (existing) return existing;
const id = ulid();
ctx.sql.exec('INSERT INTO todo_shares (id, list_id, principal, email, created_at) VALUES (?, ?, ?, ?, ?)', [
id,
listId,
invitee.id,
invitee.email,
ctx.now(),
]);
await ctx.grant(invitee.id as PrincipalId, TODO_PERM.listContribute, listRef(listId));
const row = ctx.sql.query<ShareRow>('SELECT * FROM todo_shares WHERE id = ?', [id])[0]!;
ctx.emit({
type: 'todo.list-shared',
schemaVersion: 1,
entity: { entityType: 'share', entityId: row.id },
piiClass: 'pseudonymous',
subjectId: dataSubjectId.parse(row.principal),
// The address cannot ride along: `share.email` is erasable, and an
// immutable event is the one place an erasure cannot reach.
payload: { id: row.id, list_id: row.list_id, principal: row.principal },
});
return row;
}
/**
* Someone joined, so what they were invited to becomes theirs. A consumer, because a grant
* delegates: the person joining holds nothing on the list, and its owner decided this when they
* invited. An invitation to a binned list waits, as the list does.
*/
const shareInvitedLists: ConsumerHandler = async (ctx, event) => {
const { id } = z.object({ id: z.string() }).parse(event.payload);
const owner = ctx.sql.query<OwnerRow>('SELECT * FROM todo_owners WHERE id = ?', [id])[0];
if (!owner) return;
const invites = ctx.sql.query<InviteRow>(
`SELECT i.* FROM todo_invites i JOIN todo_lists l ON l.id = i.list_id
WHERE i.email = ? COLLATE NOCASE AND l._substrat_trashed_at IS NULL`,
[owner.email],
);
for (const invite of invites) {
await shareWith(ctx, invite.list_id, owner);
ctx.sql.exec('DELETE FROM todo_invites WHERE id = ?', [invite.id]);
}
};
const bound = operationsFor(todoOperations)({
'todo/join': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listCreate));
const existing = ctx.sql.query<OwnerRow>('SELECT * FROM todo_owners WHERE id = ?', [
ctx.principal,
])[0];
if (existing) return existing;
// Sharing finds a person by this address, so it is the issuer's word for it (K-61) and
// never something the caller typed.
if (ctx.verifiedEmail === null) {
throw substratError('permission_denied', 'joining needs a verified email address');
}
ctx.sql.exec(
'INSERT INTO todo_owners (id, email, display_name, created_at) VALUES (?, ?, ?, ?)',
[ctx.principal, ctx.verifiedEmail, input.displayName, ctx.now()],
);
const row = ctx.sql.query<OwnerRow>('SELECT * FROM todo_owners WHERE id = ?', [
ctx.principal,
])[0]!;
ctx.emit({
type: 'todo.owner-joined',
schemaVersion: 1,
entity: { entityType: 'owner', entityId: row.id },
piiClass: 'pseudonymous',
subjectId: dataSubjectId.parse(row.id),
payload: { id: row.id },
});
return row;
},
'todo/create-list': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listCreate));
// The person's own entity must exist: it is what their lists hang off, and
// what carries the grant that reaches them. Created when they join.
const owner = ctx.sql.query<OwnerRow>('SELECT * FROM todo_owners WHERE id = ?', [
ctx.principal,
])[0];
if (!owner)
throw substratError(
'precondition_failed',
'no account here — join before creating a list',
);
const id = ulid();
ctx.sql.exec(
'INSERT INTO todo_lists (id, owner_id, name, created_at) VALUES (?, ?, ?, ?)',
[id, owner.id, input.name, ctx.now()],
);
// The edge the permission walk follows. Without it the owner's grant on
// their own entity would reach nothing.
ctx.link(listRef(id), { entityType: 'owner', entityId: owner.id });
const row = listOrThrow(ctx, id);
ctx.emit({
type: 'todo.list-created',
schemaVersion: 1,
entity: listRef(id),
piiClass: 'none',
payload: { id: row.id, name: row.name, owner_id: row.owner_id },
});
return row;
},
/**
* The proof walk. Every list is a candidate and each one is asked; a list
* nobody shared simply never answers yes.
*
* Deliberately NOT a `WHERE owner_id = ?` — that would be a second, hand-kept
* description of who may see what, and the one that gets forgotten.
*/
// #811. The walk is the kernel's; the per-row proof check is this vertical's,
// and `pageVisible` is what keeps the two honest — it walks on past rows the
// caller cannot see until the page is full or the budget is spent, then seals
// the continuation so no list position reaches the caller (#2074).
'todo/my-lists': async (ctx, input) =>
pageVisible(
// #119: the kernel leaves archived and binned lists out unless the archive is asked for.
// The input is passed on whole, under the walk's own `p`: it carries the caller's `view`
// and the `sort` / `order` the platform parsed, which a hand-picked `{ view }` dropped —
// so a sort by name came back in creation order, with nothing red anywhere.
(p) => ctx.page<ListRow>('list', { ...input, ...p }),
input,
async (list) => (await ctx.check(TODO_PERM.listContribute, listRef(list.id))).allowed,
{ continuation: ctx.pageContinuation('list:my-lists', input) },
),
'todo/rename-list': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listManage, listRef(input.listId)));
listOrThrow(ctx, input.listId);
ctx.sql.exec('UPDATE todo_lists SET name = ? WHERE id = ?', [input.name, input.listId]);
const row = listOrThrow(ctx, input.listId);
ctx.emit({
type: 'todo.list-renamed',
schemaVersion: 1,
entity: listRef(row.id),
piiClass: 'none',
payload: { id: row.id, name: row.name },
});
return row;
},
'todo/delete-list': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listManage, listRef(input.listId)));
// The permanent delete empties the bin, so it reaches binned lists too (`trashed: 'purges'`),
// and it is what the 30-day purge horizon runs — as todo's system principal.
listOrThrow(ctx, input.listId);
ctx.sql.exec('DELETE FROM todo_items WHERE list_id = ?', [input.listId]);
ctx.sql.exec('DELETE FROM todo_shares WHERE list_id = ?', [input.listId]);
ctx.sql.exec('DELETE FROM todo_invites WHERE list_id = ?', [input.listId]);
ctx.sql.exec('DELETE FROM todo_lists WHERE id = ?', [input.listId]);
ctx.emit({
type: 'todo.list-deleted',
schemaVersion: 1,
entity: listRef(input.listId),
piiClass: 'none',
payload: { id: input.listId },
});
return { id: input.listId, deleted: true };
},
// `todo/list-items` has no handler: it is `derive: 'list'`, so the check, the keyset
// walk, the `done` filter and the count over the same WHERE are the kernel's.
/**
* Search on one list (#827) — one check, then hydrate.
*
* The index is SCOPE-wide: `ctx.search` knows nothing about lists, so the hits
* arrive from every list in the scope and the `list_id` in the WHERE is what
* narrows them. That filter runs AFTER the ranking, which is why the index is
* asked for more than the caller wants — a top-20 that loses 18 rows to the
* filter would answer with two and call it the whole result.
*/
'todo/search-list-items': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listContribute, listRef(input.listId)));
listOrThrow(ctx, input.listId);
const limit = input.limit ?? DEFAULT_SEARCH_LIMIT;
const fetch = overfetch(limit);
const hits = ctx.search('item', input.q, { limit: fetch });
if (hits.length === 0) return { results: [], limit, capped: false };
// The hits go in as ONE bound JSON array, not one `?` each: a hit list is as long as the
// kernel's ceiling (100) and a Durable Object allows 100 bound parameters in all (#1741).
const rows = ctx.sql.query<ItemRow>(
`SELECT * FROM todo_items WHERE list_id = ? AND id IN (SELECT value FROM json_each(?))`,
[input.listId, JSON.stringify(hits.map((h) => h.id))],
);
// `IN (…)` returns rows in whatever order the table hands them back, so the
// rank has to be put back deliberately: a search that lists the best match
// third is a search people stop using.
const ordered = rankOrder(hits, rows);
return {
results: ordered.slice(0, limit),
limit,
capped: ordered.length > limit || hits.length === fetch,
};
},
/**
* Search across every list the caller reaches — the same proof walk as
* `my-lists`, run over search hits instead of over every row.
*
* `narrows` rather than a node-level check, because there is no node-level
* answer: nobody holds `list:contribute` scope-wide, so "may you see this item"
* is only ever a question about the list it sits on. Asked once per distinct
* list rather than once per hit — forty matching items on one list is one
* question, not forty.
*
* Stopping at `limit` is what makes this cheap: the walk ends as soon as the
* answer is full, so a scope with many unreachable matches costs the checks it
* takes to find `limit` reachable ones, not one per hit.
*/
'todo/search-items': async (ctx, input) => {
const limit = input.limit ?? DEFAULT_SEARCH_LIMIT;
const fetch = overfetch(limit);
const hits = ctx.search('item', input.q, { limit: fetch });
if (hits.length === 0) return { results: [], limit, capped: false };
const rows = ctx.sql.query<ItemRow>(
`SELECT * FROM todo_items WHERE id IN (SELECT value FROM json_each(?))`,
[JSON.stringify(hits.map((h) => h.id))],
);
const byId = new Map(rows.map((row) => [row.id, row]));
const reachable = new Map<string, boolean>();
const results: ItemRow[] = [];
for (const hit of hits) {
const row = byId.get(hit.id);
if (!row) continue;
let allowed = reachable.get(row.list_id);
if (allowed === undefined) {
// #119: an item is searchable exactly when its list is in `my-lists` — reachable, and
// neither archived nor binned. The index is over items and knows nothing of lists.
allowed =
ctx.entityState(listRef(row.list_id)) === 'active' &&
(await ctx.check(TODO_PERM.listContribute, listRef(row.list_id))).allowed;
reachable.set(row.list_id, allowed);
}
if (!allowed) continue;
results.push(row);
if (results.length === limit) break;
}
// Full either because the walk stopped early or because the index itself
// capped — both mean there may be more, and neither can be paged past.
return { results, limit, capped: results.length === limit || hits.length === fetch };
},
/**
* Find your lists by name — `my-lists`' per-list check, run over search hits.
*
* The index leaves archived and binned lists out on its own, so unlike `search-items`
* there is no list state to ask about: only whether this caller reaches each hit. The
* walk stops at `limit` reachable lists, in rank order.
*/
'todo/search-lists': async (ctx, input) => {
const limit = input.limit ?? DEFAULT_SEARCH_LIMIT;
const fetch = overfetch(limit);
const hits = ctx.search('list', input.q, { limit: fetch });
if (hits.length === 0) return { results: [], limit, capped: false };
// One bound JSON array rather than a `?` per hit, for the same 100-parameter ceiling (#1741).
const rows = ctx.sql.query<ListRow>(
`SELECT * FROM todo_lists WHERE id IN (SELECT value FROM json_each(?))`,
[JSON.stringify(hits.map((h) => h.id))],
);
const results: ListRow[] = [];
for (const list of rankOrder(hits, rows)) {
if (!(await ctx.check(TODO_PERM.listContribute, listRef(list.id))).allowed) continue;
results.push(list);
if (results.length === limit) break;
}
return { results, limit, capped: results.length === limit || hits.length === fetch };
},
'todo/add-item': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listContribute, listRef(input.listId)));
listOrThrow(ctx, input.listId);
const id = ulid();
ctx.sql.exec(
'INSERT INTO todo_items (id, list_id, text, done, added_by, created_at) VALUES (?, ?, ?, 0, ?, ?)',
[id, input.listId, input.text, ctx.principal, ctx.now()],
);
const row = ctx.sql.query<ItemRow>('SELECT * FROM todo_items WHERE id = ?', [id])[0]!;
ctx.emit({
type: 'todo.item-added',
schemaVersion: 1,
entity: { entityType: 'item', entityId: id },
piiClass: 'none',
payload: { id: row.id, list_id: row.list_id, text: row.text, added_by: row.added_by },
});
return row;
},
'todo/set-item-done': async (ctx, input) => {
const { list } = itemAndList(ctx, input.itemId);
assertAllowed(await ctx.check(TODO_PERM.listContribute, listRef(list.id)));
ctx.sql.exec('UPDATE todo_items SET done = ? WHERE id = ?', [input.done ? 1 : 0, input.itemId]);
const row = ctx.sql.query<ItemRow>('SELECT * FROM todo_items WHERE id = ?', [input.itemId])[0]!;
ctx.emit({
type: 'todo.item-done-changed',
schemaVersion: 1,
entity: { entityType: 'item', entityId: row.id },
piiClass: 'none',
payload: { id: row.id, list_id: row.list_id, done: row.done },
});
return row;
},
/** Deleting is the owner's, which is what `list:manage` means here. */
'todo/delete-item': async (ctx, input) => {
const { list } = itemAndList(ctx, input.itemId);
assertAllowed(await ctx.check(TODO_PERM.listManage, listRef(list.id)));
ctx.sql.exec('DELETE FROM todo_items WHERE id = ?', [input.itemId]);
ctx.emit({
type: 'todo.item-deleted',
schemaVersion: 1,
entity: { entityType: 'item', entityId: input.itemId },
piiClass: 'none',
payload: { id: input.itemId },
});
return { id: input.itemId, deleted: true };
},
/**
* Sharing — the whole point of the app, and one line of access control.
*
* `ctx.grant` narrows `list:contribute` onto THIS list for THIS person. It
* delegates: the kernel re-checks that the caller holds it there, so an
* operation can never hand out more than it was given. Nothing else in the
* app has to remember that Björn may touch this list — the grant is the fact,
* and every check reads it.
*/
'todo/share-list': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listManage, listRef(input.listId)));
listOrThrow(ctx, input.listId);
const invitee = ownerByEmail(ctx, input.email);
if (!invitee) throw substratError('not_found', `nobody here with that address: ${input.email}`);
return await shareWith(ctx, input.listId, invitee);
},
/**
* An address nobody has joined with gets an email and a row that waits for them. The send is
* an intent in this transaction, so an operation that fails after it sends nothing.
*/
'todo/invite': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.listManage, listRef(input.listId)));
// A grant delegates, but the share an invitation becomes is made by a consumer, where nothing
// re-checks the inviter. So what they hand on is asked here, whether or not the address has joined.
assertAllowed(await ctx.check(TODO_PERM.listContribute, listRef(input.listId)));
const list = listOrThrow(ctx, input.listId);
const invitee = ownerByEmail(ctx, input.email);
if (invitee) {
const share = await shareWith(ctx, input.listId, invitee);
return { status: 'shared' as const, id: share.id, email: share.email };
}
const open = ctx.sql.query<InviteRow>('SELECT * FROM todo_invites WHERE list_id = ? AND email = ?', [
input.listId,
input.email,
])[0];
if (open) return { status: 'invited' as const, id: open.id, email: open.email };
const id = ulid();
ctx.sql.exec('INSERT INTO todo_invites (id, list_id, email, invited_by, created_at) VALUES (?, ?, ?, ?, ?)', [
id,
input.listId,
input.email,
ctx.principal,
ctx.now(),
]);
requestEmail(ctx, {
to: input.email,
subject: `You have been invited to the list ${list.name}`,
text: `You have been invited to the list ${list.name}. Sign in with this address to open it.`,
html: `<p>You have been invited to the list <strong>${escapeHtml(list.name)}</strong>.</p><p>Sign in with this address to open it.</p>`,
about: { entityType: 'invite', entityId: id },
});
ctx.emit({
type: 'todo.invite-sent',
schemaVersion: 1,
entity: { entityType: 'invite', entityId: id },
piiClass: 'none',
payload: { id },
});
return { status: 'invited' as const, id, email: input.email };
},
'todo/cancel-invite': async (ctx, input) => {
const invite = ctx.sql.query<InviteRow>('SELECT * FROM todo_invites WHERE id = ?', [input.inviteId])[0];
if (!invite) throw substratError('not_found', `invite not found: ${input.inviteId}`);
assertAllowed(await ctx.check(TODO_PERM.listManage, listRef(invite.list_id)));
liveListOrThrow(ctx, invite.list_id);
ctx.sql.exec('DELETE FROM todo_invites WHERE id = ?', [invite.id]);
ctx.emit({
type: 'todo.invite-cancelled',
schemaVersion: 1,
entity: { entityType: 'invite', entityId: invite.id },
piiClass: 'none',
payload: { id: invite.id },
});
return { id: invite.id, cancelled: true };
},
'todo/revoke-share': async (ctx, input) => {
const share = ctx.sql.query<ShareRow>('SELECT * FROM todo_shares WHERE id = ?', [
input.shareId,
])[0];
if (!share) throw substratError('not_found', `share not found: ${input.shareId}`);
assertAllowed(await ctx.check(TODO_PERM.listManage, listRef(share.list_id)));
// A share on a binned list is as gone as the list: revoking it would change a list nobody
// can see until it is restored. Reached through the share, so the host cannot refuse it.
liveListOrThrow(ctx, share.list_id);
ctx.sql.exec('DELETE FROM todo_shares WHERE id = ?', [input.shareId]);
await ctx.revoke(share.principal as PrincipalId, TODO_PERM.listContribute, listRef(share.list_id));
ctx.emit({
type: 'todo.share-revoked',
schemaVersion: 1,
entity: { entityType: 'share', entityId: share.id },
piiClass: 'none',
payload: { id: share.id },
});
return { id: share.id, revoked: true };
},
/** One page of members, and one read for which of that page hold plugin access. */
'todo/list-members': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.peopleManage));
const page = ctx.page<OwnerRow>('owner', input);
const ids = page.entries.map((m) => m.id);
const granted = new Set(
ctx.sql
.query<{ id: string }>('SELECT id FROM todo_plugin_access WHERE id IN (SELECT value FROM json_each(?))', [JSON.stringify(ids)])
.map((r) => r.id),
);
return mapPage(page, (m) => ({ ...m, plugin_access: granted.has(m.id) }));
},
'todo/grant-plugin-access': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.peopleManage));
const member = ctx.sql.query<OwnerRow>('SELECT * FROM todo_owners WHERE id = ?', [input.memberId])[0];
if (!member) throw substratError('not_found', `member not found: ${input.memberId}`);
const existing = ctx.sql.query<AccessRow>('SELECT * FROM todo_plugin_access WHERE id = ?', [member.id])[0];
if (existing) return existing;
ctx.sql.exec('INSERT INTO todo_plugin_access (id, granted_by, created_at) VALUES (?, ?, ?)', [
member.id,
ctx.principal,
ctx.now(),
]);
const row = ctx.sql.query<AccessRow>('SELECT * FROM todo_plugin_access WHERE id = ?', [member.id])[0]!;
ctx.emit({
type: 'todo.plugin-access-granted',
schemaVersion: 1,
entity: { entityType: 'access', entityId: row.id },
piiClass: 'pseudonymous',
subjectId: dataSubjectId.parse(row.id),
payload: { id: row.id },
});
return row;
},
'todo/revoke-plugin-access': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.peopleManage));
const { changes } = ctx.sql.exec('DELETE FROM todo_plugin_access WHERE id = ?', [input.memberId]);
if (changes === 0) throw substratError('not_found', `no plugin access to revoke: ${input.memberId}`);
ctx.emit({
type: 'todo.plugin-access-revoked',
schemaVersion: 1,
entity: { entityType: 'access', entityId: input.memberId },
piiClass: 'pseudonymous',
subjectId: dataSubjectId.parse(input.memberId),
payload: { id: input.memberId },
});
return { id: input.memberId, revoked: true };
},
'todo/vouch-access': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.peopleVouch));
if ((input.listId === undefined) === (input.itemId === undefined)) {
throw substratError('validation_failed', 'name exactly one of listId and itemId');
}
const listId =
input.listId ??
ctx.sql.query<{ list_id: string }>('SELECT list_id FROM todo_items WHERE id = ?', [input.itemId!])[0]?.list_id;
const list = listId === undefined ? undefined : ctx.sql.query<ListRow>('SELECT * FROM todo_lists WHERE id = ?', [listId])[0];
if (!list || ctx.entityState(listRef(list.id)) === 'trashed') return { visible: false, listId: null };
const shared = ctx.sql.query<{ id: string }>('SELECT id FROM todo_shares WHERE list_id = ? AND principal = ?', [
list.id,
input.principal,
]).length > 0;
return { visible: list.owner_id === input.principal || shared, listId: list.id };
},
/**
* The person contract, answered from what this app already records: a member is found by the
* address they joined with, which is the issuer's word for it (K-61) and the same proof an
* invitation is admitted on. This app keeps no logins, so `sub` and `issuer` go unread.
*
* A member without plugin access is known and holds nothing, which is what an empty role
* list says. Nobody here is ever `invited` or `blocked`: a list invitation is no person yet.
*/
'todo/resolve-person': async (ctx, input) => {
assertAllowed(await ctx.check(TODO_PERM.peopleResolve));
if (input.verifiedEmail === null) return { person: null };
const member = ownerByEmail(ctx, input.verifiedEmail);
if (!member) return { person: null };
const access = ctx.sql.query<{ id: string }>('SELECT id FROM todo_plugin_access WHERE id = ?', [member.id])[0];
return { person: { id: member.id, status: 'active' as const, roles: access ? ['member'] : [] } };
},
});
export const todoModule: ModuleRegistration = {
manifest: todoManifest,
migrations: todoMigrations,
// The handlers above are bound to the declaration, and the host parses every
// invocation against it, from one object — so neither can drift from the other (#953, #1835).
...bound,
consumers: { 'todo.owner-joined': shareInvitedLists },
};What this shows, and what it does not
What it does not show. Todo composes no engine. Its defineOperations takes no engine argument, and that is a fact about the app rather than an omission: nothing here has an invariant beyond "you cannot touch a list nobody shared with you", and that one is the platform's own. So this page shows the model → code pipeline and not engine composition, which is a large part of what a real vertical does. For that, read Handlebar — a repair that composes the workorder and protocol engines inside its own transaction.
What it does show. Here is the smallest app anyone could write, and it is already multi-tenant, permission-checked on every operation, and audited on every change — and none of that appears in the code above. "A todo app makes the platform look like overkill" is true only if you show the app. Show what you did not write and it is the point.
The honest comparison: Wasp
Wasp's TodoAppTs is the same app, and it is worth putting next to this one because Wasp is good and the difference is real.
On line count, Wasp wins. main.wasp.ts is about 30 lines, schema.prisma a dozen, actions.ts 34, queries.ts 13 — under a hundred lines to Substrat's roughly 800 across model.ts and module.ts. Their terseness is genuine, and this page is not structured as though it were not. A good part of the difference is that Substrat's two files carry the things Wasp leaves to convention: which permission each operation checks, what each mutation emits, what is personal data, how a list is paged.
The axis where Substrat is different is what a handler looks like. Wasp's update action is this:
return context.entities.Task.updateMany({
where: { id: args.id, user: { id: context.user.id } }, // forget this and anyone edits anything
data: { isDone: args.isDone },
});The ownership clause is the whole access control, it is restated in every handler, and nothing in the framework notices if one of them drops it — the types stay perfect. Their schema even has userId Int?, so a task can exist with no owner at all.
In todo the same edge is parents: ['list'] in the model plus one ctx.check(perm, entityRef) at the top of each handler, declared once rather than remembered per handler — and the declaration is what the conformance kit drives, so a handler that checked the node instead of the entity goes red in CI rather than shipping. That is not a claim that Substrat's code is shorter. It is a claim about where the mistake can live.