@fabrika/app 0.9.0-dev.12 → 0.9.0-dev.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +7 -4
  3. package/skill/references/app-setup.md +15 -8
  4. package/skill/references/endpoint.md +7 -1
  5. package/skill/references/errors.md +7 -6
  6. package/skill/references/jobs.md +10 -0
  7. package/skill/references/relations.md +682 -0
  8. package/skill/references/table-and-migration.md +18 -7
  9. package/skill/references/webhooks-links-connectors.md +2 -1
  10. package/src/bun.ts +10 -0
  11. package/src/contract/artifact-schema.ts +82 -1
  12. package/src/contract/build.ts +142 -12
  13. package/src/contract/compile.ts +1 -0
  14. package/src/contract/declaration.ts +4 -0
  15. package/src/contract/define.ts +12 -0
  16. package/src/contract/group.ts +10 -1
  17. package/src/contract/kit.ts +3 -1
  18. package/src/contract/platform.ts +1 -0
  19. package/src/contract/vocabulary.ts +3 -0
  20. package/src/disk-assets.ts +15 -3
  21. package/src/implement/boot.ts +59 -5
  22. package/src/implement/capability.ts +91 -6
  23. package/src/implement/dispatch.ts +334 -17
  24. package/src/implement/egress.ts +409 -9
  25. package/src/implement/implement.ts +28 -1
  26. package/src/implement/invocation.ts +10 -9
  27. package/src/implement/types.ts +15 -4
  28. package/src/implement/webhook.ts +8 -0
  29. package/src/jobs/runner.ts +7 -2
  30. package/src/source-map-path.ts +21 -0
  31. package/src/testing/caller.ts +20 -2
  32. package/src/testing/membership.ts +9 -5
  33. package/types/src/contract/declaration.d.ts +6 -0
  34. package/types/src/contract/define.d.ts +15 -0
  35. package/types/src/contract/group.d.ts +9 -1
  36. package/types/src/contract/kit.d.ts +2 -2
  37. package/types/src/contract/vocabulary.d.ts +4 -1
  38. package/types/src/implement/boot.d.ts +6 -0
  39. package/types/src/implement/capability.d.ts +14 -5
  40. package/types/src/implement/dispatch.d.ts +20 -1
  41. package/types/src/implement/egress.d.ts +36 -1
  42. package/types/src/implement/implement.d.ts +24 -1
  43. package/types/src/implement/invocation.d.ts +3 -3
  44. package/types/src/implement/types.d.ts +13 -3
  45. package/types/src/jobs/runner.d.ts +3 -0
  46. package/types/src/source-map-path.d.ts +4 -0
  47. package/types/src/testing/caller.d.ts +6 -1
  48. package/types/src/testing/membership.d.ts +1 -1
@@ -0,0 +1,682 @@
1
+ # references/relations.md — relation grants and conditions
2
+
3
+ A relation gives a role its actions at the nodes where a row of the application names the person: "the assistants of
4
+ this project, until their assignment ends". A condition (`when`) narrows an action to the rows it admits: "no task is
5
+ written in a project past its end". Both are declarations the approver reads; the data layer applies them to every
6
+ statement. This file is an application of its own (`tasks` with assistants); its `package.json`, `tsconfig.json`,
7
+ `src/app-kit.ts`, `src/app.ts` and `src/schemas.ts` are those of `app-setup.md` and `endpoint.md`.
8
+
9
+ Ask the human before you add a relation, a role's `via`, a table's `confers` or its `assign`: each lets someone reach
10
+ more, and the approver sees each as a widening. A `when` only narrows; removing or changing one widens. They need
11
+ `@fabrika/app` `0.9.0-dev.13` or later, and a `relationWhen` `0.9.0-dev.14` or later: Control refuses to publish them for
12
+ an application pinned to an earlier release. A relation held inside the node of a scoped grant needs `0.9.0-dev.14`;
13
+ an earlier release holds nothing through it. A table's `access` needs `0.9.0-dev.14` or later, which Control
14
+ checks the same way.
15
+
16
+ ## The vocabulary: a relation and a role's `via`
17
+
18
+ ```ts src/vocabulary.ts
19
+ import { defineVocabulary } from '@fabrika/app/contract'
20
+
21
+ export const vocabulary = defineVocabulary({
22
+ app: 'tasks',
23
+ dimensions: {
24
+ org: { members: { manage: 'members.manage', list: 'tasks.read' } },
25
+ project: { in: 'org' },
26
+ task: { in: 'project' },
27
+ },
28
+ actions: {
29
+ 'tasks.read': 'Read projects and tasks',
30
+ 'tasks.write': 'Create projects and tasks, and finish tasks',
31
+ 'assistants.assign': 'Assign an assistant to a project',
32
+ 'members.manage': 'Invite and remove members',
33
+ },
34
+ relations: {
35
+ assisting: { dimension: 'project' },
36
+ auditing: { dimension: 'org' },
37
+ },
38
+ roles: {
39
+ owner: {
40
+ grants: ['tasks.read', 'tasks.write', 'assistants.assign', 'members.manage'],
41
+ member: { scope: 'org', assignableBy: ['owner'] },
42
+ },
43
+ coordinator: {
44
+ grants: ['tasks.read', 'assistants.assign'],
45
+ member: { scope: 'org', assignableBy: ['owner'] },
46
+ },
47
+ assistant: {
48
+ grants: [],
49
+ via: { assisting: ['tasks.read', 'tasks.write'] },
50
+ },
51
+ auditor: {
52
+ grants: [],
53
+ via: { auditing: ['tasks.read'] },
54
+ },
55
+ },
56
+ })
57
+ ```
58
+
59
+ - `relations: { <name>: { dimension } }` names a relation and the dimension of the node its rows name.
60
+ - `via: { <relation>: [<action>, …] }` on a role: a holder of the role holds those actions at each node where a source
61
+ row names them, and nowhere else. Its `grants` still hold globally, so an assistant's are empty.
62
+ - `via` is for an internal role. A global grant of it (an operator gives `assistant` application-wide, in IAM's
63
+ console) holds the relation wherever the rows name its holder. A grant of it in a scope value, a membership role in
64
+ the value it is held in included, holds the relation only inside that value: a member row in another organization
65
+ reaches nothing, and a table or a reveal above the value gets nothing through it. A membership role's `via` names a
66
+ relation whose dimension is the role's own or lies inside it (`project` inside `org`), and the build refuses any
67
+ other. A person from outside the organization (`external: true`) holds no relation, and an external role takes no
68
+ `via`.
69
+ - Whoever gives a membership role with `via` holds every action of the role, its `via` actions included, at that value
70
+ through a grant; an action they hold only through a relation does not count.
71
+ - The token says only that the role holds those actions through `assisting`. The data layer reads the source rows on
72
+ every statement, so an inserted row grants at the next request and a deleted one stops access at the next request.
73
+ Nothing caches it.
74
+ - A principal a row names reaches nothing unless IAM grants it a role whose `via` names the relation.
75
+
76
+ ## The migration
77
+
78
+ ```sql db/migrations/20261104090000_assistants.sql
79
+ CREATE TABLE projects (
80
+ id UUID PRIMARY KEY,
81
+ org_id TEXT NOT NULL,
82
+ name TEXT NOT NULL,
83
+ ends_at TIMESTAMPTZ,
84
+ created_by TEXT NOT NULL,
85
+ version INTEGER NOT NULL,
86
+ UNIQUE (id, org_id)
87
+ );
88
+ CREATE INDEX projects_org ON projects (org_id);
89
+
90
+ -- A condition's path follows a single-column foreign key: project_id carries one beside the composite key.
91
+ CREATE TABLE tasks (
92
+ id UUID PRIMARY KEY,
93
+ project_id UUID NOT NULL REFERENCES projects (id),
94
+ org_id TEXT NOT NULL,
95
+ title TEXT NOT NULL,
96
+ done BOOLEAN NOT NULL DEFAULT false,
97
+ created_by TEXT NOT NULL,
98
+ version INTEGER NOT NULL,
99
+ FOREIGN KEY (project_id, org_id) REFERENCES projects (id, org_id) ON UPDATE CASCADE
100
+ );
101
+ CREATE INDEX tasks_project ON tasks (project_id);
102
+
103
+ -- A relation source: each row names one principal at one project until it expires.
104
+ CREATE TABLE project_assistants (
105
+ id UUID PRIMARY KEY,
106
+ project_id UUID NOT NULL,
107
+ org_id TEXT NOT NULL,
108
+ principal_id TEXT NOT NULL,
109
+ expires_at TIMESTAMPTZ NOT NULL,
110
+ created_by TEXT NOT NULL,
111
+ FOREIGN KEY (project_id, org_id) REFERENCES projects (id, org_id) ON UPDATE CASCADE ON DELETE CASCADE
112
+ );
113
+ CREATE INDEX project_assistants_principal ON project_assistants (principal_id, project_id);
114
+
115
+ -- An access view: the finished tasks of each organization, for whoever audits it there.
116
+ CREATE VIEW finished_tasks AS
117
+ SELECT id AS task_id, org_id FROM tasks WHERE done;
118
+ ```
119
+
120
+ - A source table is an ordinary child or dimension table with a principal column (`TEXT`, an IAM principal id), the
121
+ node column (by default the table's column of the relation's dimension: `project_id`) and, for a bounded
122
+ delegation, an expiry (`TIMESTAMPTZ NOT NULL`).
123
+ - Give it an index on `(principal, node)`. Every statement under the relation runs
124
+ `node in (select node from <source> where principal = $me …)`, and nothing creates the index for you.
125
+ - After the migration run `fabrika db migrate` and `fabrika db codegen` (on Cloudflare `codegen` only): the policies
126
+ below read the generated `columns`, its foreign keys and which columns are `NOT NULL`.
127
+
128
+ ## The policies
129
+
130
+ ```ts src/db/tables.ts
131
+ import { defineTables } from '@fabrika/db/tables'
132
+ import { vocabulary } from '../vocabulary'
133
+ import { columns } from './schema.generated'
134
+
135
+ export const tables = defineTables(vocabulary, columns)({
136
+ projects: {
137
+ scope: { dimension: 'project' },
138
+ actions: { read: 'tasks.read', insert: 'tasks.write' },
139
+ insert: ['name', 'ends_at'],
140
+ version: 'version',
141
+ createdBy: 'created_by',
142
+ },
143
+ tasks: {
144
+ scope: { dimension: 'task' },
145
+ actions: { read: 'tasks.read', insert: 'tasks.write', update: 'tasks.write' },
146
+ insert: ['title'],
147
+ update: ['done'],
148
+ version: 'version',
149
+ createdBy: 'created_by',
150
+ when: {
151
+ 'tasks.write': {
152
+ anyOf: [
153
+ { 'project_id.ends_at': { isNull: true } },
154
+ { 'project_id.ends_at': { gt: { now: true } } },
155
+ ],
156
+ },
157
+ },
158
+ access: {
159
+ auditing: { view: 'finished_tasks', row: 'task_id', member: 'org_id' },
160
+ },
161
+ },
162
+ project_assistants: {
163
+ scope: { child: 'projects' },
164
+ actions: {
165
+ read: 'tasks.read',
166
+ insert: 'assistants.assign',
167
+ delete: 'assistants.assign',
168
+ },
169
+ insert: ['principal_id', 'expires_at'],
170
+ createdBy: 'created_by',
171
+ confers: {
172
+ assisting: {
173
+ principal: 'principal_id',
174
+ expires: 'expires_at',
175
+ assign: { maxDays: 30 },
176
+ },
177
+ },
178
+ },
179
+ })
180
+ ```
181
+
182
+ ### `confers`: the rows that grant a relation
183
+
184
+ - `confers: { <relation>: { principal, node?, expires?, when?, assign? } }`. `node` defaults to the table's column of
185
+ the relation's dimension. A row confers nothing once `expires` passed, nor while its own `when` does not admit it.
186
+ A source's `when` never reads its `version`. It may follow one foreign key to the row the source names, such as
187
+ `{ 'person_id.active': { eq: true } }`, the far side of a many-to-many table: no update of that table may write the
188
+ column it tests, and the table is no view, queue or top-level dimension table. It takes no second foreign key and no
189
+ `some`. That table joins the source table among those `ctx.sql` of a writing endpoint never names, so a writing
190
+ statement that already names it fails at run time once the condition is added: move that write to `ctx.db` first.
191
+ - Inserting a row is delegation: the coordinator gives the assistant `tasks.read` and `tasks.write` without holding
192
+ `tasks.write` itself. The insert's own action (`assistants.assign`) decides who may write it, and the layer bounds
193
+ what it gives instead:
194
+ - the node is stamped from the writer's `Ref`, so a coordinator delegates only in a project it reaches;
195
+ - `assign.maxDays` caps the expiry; a later or a missing expiry is a 409, and `maxDays` needs `expires`;
196
+ - a row naming its writer is a 409 unless `assign.self: true` allows it. `principal` may name the table's
197
+ `createdBy`: then every row names its writer at the row's node. On `projects`, a relation at `project` makes a
198
+ creator hold it at that project, and one at `org` at the project's org; on a child table such as
199
+ `project_assistants` the writer holds it at the parent project, not at the row. So a table with an insert states
200
+ `assign: { self: true }`, and the policy is refused without it;
201
+ - a table that confers without `assign` takes no insert.
202
+ - `principal` may be read through one foreign key, `'<column>.<principal column>'`: `principal: 'person_id.principal_id'`
203
+ on a staff row that names a person of a directory table, whose own row holds the principal id. `<column>` needs a
204
+ single-column `REFERENCES <table> (id)` to the key of a contained dimension, child or application table (no view, no
205
+ queue table, no top-level dimension), and is not the source's own key, version, file or containment column (an
206
+ `org_id` a move rewrites). No other foreign key holds that column, but a composite one to the same row, such as
207
+ `(person_id, org_id) REFERENCES people (id, org_id)`, and the referenced table's key references nothing. No update of that table may write the principal column, so a person row is replaced, never edited:
208
+ deleting it, or the source row, ends the access at the next request. A row whose person names its writer is a 409
209
+ without `assign.self`, as above. The foreign key needs only the referenced table's key, not a key that holds the
210
+ tenant: a writer may name a person of another organization, which gives no more than naming that principal id
211
+ directly. Index the referenced table on `(principal column, id)` too.
212
+ - A column that holds a principal, on the source or on the table a path reads, has no `REFERENCES`: a key that
213
+ cascades on update would change whom every row names.
214
+ - A source row never moves, and no update writes its principal, node, expiry or a column its `when` reads. Change an
215
+ assignment by deleting the row and inserting a new one. `ctx.sql` of a writing endpoint never names a source table,
216
+ `unscoped` never writes one, and a queue table confers nothing.
217
+
218
+ ### `when`: a condition narrows an action
219
+
220
+ - `when: { <action>: <condition> }` is ANDed onto every grant of that action on the table: global, IAM-scoped and
221
+ through a relation alike. The owner cannot add a task to a project past its end either. A row the condition does
222
+ not admit is not there for that action: a read or an update `on` it is 404, a list leaves it out, and an insert
223
+ it refuses is a 409 with nothing written.
224
+ - A condition is data, never SQL: `{ <column>: { <operator>: <value> } }` with `eq`, `notEq`, `in`, `notIn`,
225
+ `isNull`, `lt`, `lte`, `gt` and `gte`; several columns in one object must all hold; `allOf`, `anyOf` and `not` stand
226
+ alone in their object. `{ now: true }` is the statement's clock (`{ gt: { now: true } }`), never the text `now`. A
227
+ JSON column is never compared: extract the value into a typed column.
228
+ - A path follows foreign keys: `'project_id.ends_at'` reads the task's project. The column needs a single-column
229
+ `REFERENCES <table> (id)`, and the hop must stay in the row's tenant: the row's own container or parent column, a
230
+ key into a reference table, or a key that holds every ancestor the two tables share (below). A view's path starts at
231
+ its parent column, which needs no foreign key.
232
+ - `{ some: { <table>: <condition> } }` holds when a row of `<table>` whose single-column foreign key names this row
233
+ meets the condition, `none` when no such row does: on `projects`, `{ some: { tasks: { done: { eq: false } } } }` is
234
+ a project with an open task. The rows' foreign key is held like a path's hop, so it keeps to the row's tenant, and
235
+ a key into a reference table is not followed back: `{ tag_id: { some: { project_tags: … } } }` would count every
236
+ tenant's rows that name the tag, so the policy refuses it.
237
+ - A path may end in `some` or `none`: on `tasks`, `{ project_id: { some: { project_tags: { 'tag_id.name': { eq:
238
+ 'urgent' } } } } }` is a task of a project tagged urgent, through the link table `project_tags`. A `null` foreign key
239
+ reaches no row, so neither `some` nor `none` holds there. A `some` nests in a `some`.
240
+ - A `not` follows a path only through columns declared `NOT NULL`, at any depth: on a null key the path's lookup
241
+ would turn on rows of every tenant. `{ not: { 'client_id.active': { eq: true } } }` with a nullable `client_id` is
242
+ refused and names the column: declare it `NOT NULL` in a migration and run `fabrika db codegen`, or say what a row
243
+ without a client gets, `{ anyOf: [{ client_id: { isNull: true } }, { 'client_id.active': { eq: false } }] }`. Like
244
+ the `not`, it leaves out a row whose client's `active` is null.
245
+ - A path follows at most three foreign keys, the path before a `some`, the `some` and every hop inside it counted
246
+ together. Each hop is one more subquery in every statement of the action; shorten a longer path with a stored column.
247
+ - An insert's condition is judged on the written row. One with a path runs in the insert's transaction, every row on
248
+ its paths locked `FOR SHARE` first, so nobody changes the project while the task goes in. An insert action's
249
+ condition may end a path in `some` (`{ project_id: { some: … } }`), whose rows are locked too. It takes no `none`,
250
+ no `some` under `not`, no `some` straight on the inserted row, and no `some` of the inserted table's own rows
251
+ (`{ project_id: { some: { tasks: … } } }` on `tasks`): a row inserted meanwhile could make the first two false,
252
+ nothing names the new row yet, and the last would count the new task itself, since the condition is judged after
253
+ the write. An upsert's conflict update is judged on the stored row.
254
+
255
+ ### `relationWhen`: a condition on what one relation reaches
256
+
257
+ - `relationWhen: { <relation>: { <action>: <condition> } }` narrows only what that relation reaches of the table for
258
+ the action: through `assisting`, only open tasks, while the owner's IAM grant still reaches every task. The table's
259
+ own `when` still applies to every grant; a member reveal and an IAM grant are not narrowed by it.
260
+ - The condition is a `when` in every rule above: the same operators, paths, `not` rule and insert rules. The relation
261
+ must be one the vocabulary declares and the action one the table names, and the relation must reach the table for
262
+ it (its dimension in the table's chain, a `readThrough`, or a reveal of it for that action); otherwise the policy is
263
+ refused. A view checks the relation against its parent, and its own `relationWhen` narrows its rows; the parent's
264
+ does not apply to it.
265
+ - An `on` endpoint whose `Ref` the relation holds sees a row the condition does not admit as absent (404). An insert
266
+ through the relation that the condition refuses, with no other relation to hold it, is a 409 with nothing written.
267
+ - A relation narrowed for an action does not count as holding it when a `writeThrough` column's writer is checked.
268
+
269
+ ### `access`: a view decides what a relation reaches
270
+
271
+ When no declaration above says who reaches a row (a published row of another organization, a grant that is active only
272
+ under a join, several paths to one row), write the rule as SQL in a view and name it under the relation (ADR-0076):
273
+
274
+ - `access: { <relation>: { view, row, principal?, member? } }`. `row` is the view's column with the table's key.
275
+ `member` is compared with the nodes the relation is held inside (a grant of the role in a scope value, at the
276
+ relation's own dimension); `principal` with the caller's principal id. At least one is required.
277
+ - The data layer adds `key in (select <row> from <view> where …)` to every statement under the relation, beside the
278
+ action's other grants. `when` and `relationWhen` still narrow it. A `member`-bound view is not narrowed to the node:
279
+ it may list rows of other organizations, and that is how a cross-tenant rule is written.
280
+ - The view takes no policy, and a table's key needs a single-column primary or unique key (`access-view-key`).
281
+ - The view's SQL is the access rule. The approver reads it as database code that decides the relation, and nothing
282
+ checks what it selects: a `cross join` or a missing tenant join widens access to everyone. Whoever writes the rows
283
+ it reads changes who reaches the table, with no bound. Prefer `confers` when a row per grant fits.
284
+ - Test what each principal reads through it, as `an auditor` below does: one inside the node, one outside it, through
285
+ an endpoint that filters nothing itself, so the test fails when the view's filter is wrong.
286
+
287
+ ### A key that holds the tenant needs its ancestors NOT NULL
288
+
289
+ A path into another scoped table, other than the container or parent, and a `readThrough` follow a foreign key of
290
+ exactly the column and every ancestor the two tables share, `(team_id, org_id) REFERENCES teams (id, org_id)`, beside
291
+ the column's single-column key. Each ancestor column of that key must be `NOT NULL`: under SQL's matching a null
292
+ `org_id` skips the whole key, so a row written with one could point at another org's team. A policy over a nullable
293
+ one is refused and names the column: add a migration that sets it `NOT NULL`, then run `fabrika db migrate` and
294
+ `fabrika db codegen`, which writes the `notNull` list the policy is checked against.
295
+
296
+ ### `readThrough`, `reveals` and `memberReveals`
297
+
298
+ - `readThrough: { <dimension>: <column> }` lets a `Within` of a dimension outside the table's chain, or a relation at
299
+ it, read the row through that column's tenant-holding key: a task in a project, read by the members of the team its
300
+ `team_id` names. No update writes the column. When the key
301
+ lives on the row's container, name the container's path from the row's own containment column:
302
+ `readThrough: { team: 'task_id.team_id' }` on a task's comments. The container declares `readThrough.team` through
303
+ a column of its own; the row follows it wherever the container's column points now. Such a table takes no reveal
304
+ matched through that path: declare the reveal on the container.
305
+ - `writeThrough: { <dimension>: [<actions>] }` beside `readThrough` lets the path hold those actions for an `on` or `in`
306
+ endpoint too, writes included: a member of the team a task names updates the task. A path holds reads only without
307
+ it. Whoever inserts a row naming a team must hold every listed action at that team (a grant there or above it, a
308
+ relation row there, or a member-revealing row), or the insert answers 409; so must the container's writer for the actions its rows' paths list.
309
+ A job or a webhook holds nothing there. A `Ref` held through the path never moves a row, the table is never written
310
+ `unscoped` or by `ctx.sql`, and `ctx.sql.scope` refuses such a `Ref`.
311
+ - `reveals: { <relation>: { to, actions, when? } }` on a table the relation reaches: such a row also gives the
312
+ relation `actions` (those its roles name in `via`) at its ancestor node in `to` while `when` admits the row: an
313
+ assignee of an open task reads its project. A reveal matched through `readThrough` on a table with an insert needs
314
+ `assign: {}` (or `{ self: true }`), because the writer picks the node.
315
+ - `memberReveals: { <own dimension>: { to, actions, when? } }`: a grant at the row's own node holds `actions` at its
316
+ ancestor in `to` too, while `when` admits the row: an `over` list reads through it, and an `on` or `in` endpoint of a
317
+ listed action gets a `Ref` of the ancestor, writes included. A member of an open task renames its project; once the
318
+ task closes, the next statement answers 404. Such a row is never written unscoped or by `ctx.sql`, and never moves.
319
+ `ctx.sql.scope` refuses a `Ref` held this way: read it through `ctx.db`.
320
+ - `memberReveals` may also be keyed by a dimension the table reads through: `memberReveals: { team: { to: 'project',
321
+ actions: ['projects.read'], assign: {} } }` on tasks that name a team in `readThrough.team`: a grant at that team
322
+ reads the project of each open task naming it. A link row (a child of the task naming a team) reveals its task the
323
+ same way. Through a path `to` is the row's nearest container, and a table with an insert states `assign`: without
324
+ `self`, inserting a row that names a team where the writer holds one of the listed actions answers 409, and a job or
325
+ a webhook names no team there. An `on` or `in` endpoint gets a `Ref` through it only for an action the path's
326
+ `writeThrough` also lists.
327
+ - A view under a parent takes none of them: it is read through its parent row, so a relation, a reveal, a member
328
+ reveal or a secondary path that reaches the parent reaches the view's rows of that parent.
329
+
330
+ ## The endpoints
331
+
332
+ ```ts src/projects/endpoints.ts
333
+ import { z } from 'zod/v4'
334
+ import { app } from '../app-kit'
335
+ import { Saved } from '../schemas'
336
+
337
+ const DAY_MS = 86_400_000
338
+ const NewProject = z.strictObject({
339
+ orgId: z.string().min(1).max(100),
340
+ name: z.string().min(1).max(200),
341
+ endsAt: z.iso.datetime().optional(),
342
+ })
343
+ const Assign = z.strictObject({
344
+ id: z.uuid(),
345
+ assistant: z.string().min(1).max(200),
346
+ days: z.int().min(1).max(30),
347
+ })
348
+ const Unassign = z.strictObject({ id: z.uuid(), assignment: z.uuid() })
349
+ const Assignment = z.strictObject({ id: z.uuid() })
350
+
351
+ export const projects = app.group({ callers: ['human'] }, (r) => ({
352
+ create: r.mutation({
353
+ input: NewProject,
354
+ output: Saved,
355
+ access: { action: 'tasks.write', in: 'org', from: 'orgId' },
356
+ })
357
+ .handle(({ input, ctx }) =>
358
+ ctx.db.target.projects.insert({
359
+ name: input.name,
360
+ ends_at: input.endsAt ?? null,
361
+ })
362
+ ),
363
+ assign: r.mutation({
364
+ input: Assign,
365
+ output: Assignment,
366
+ access: { action: 'assistants.assign', on: 'project', from: 'id' },
367
+ })
368
+ .handle(({ input, ctx }) =>
369
+ ctx.db.target.project_assistants.insert({
370
+ principal_id: input.assistant,
371
+ expires_at: new Date(Date.now() + input.days * DAY_MS),
372
+ })
373
+ ),
374
+ unassign: r.mutation({
375
+ input: Unassign,
376
+ output: Assignment,
377
+ access: { action: 'assistants.assign', on: 'project', from: 'id' },
378
+ })
379
+ .handle(async ({ input, ctx }) => {
380
+ await ctx.db.target.project_assistants.remove(input.assignment)
381
+ return { id: input.assignment }
382
+ }),
383
+ }))
384
+ ```
385
+
386
+ ```ts src/tasks/endpoints.ts
387
+ import { fromPage } from '@fabrika/app'
388
+ import { z } from 'zod/v4'
389
+ import { app } from '../app-kit'
390
+ import { Cursor, Saved, Versioned } from '../schemas'
391
+
392
+ const Task = z.strictObject({
393
+ id: z.uuid(),
394
+ title: z.string(),
395
+ done: z.boolean(),
396
+ version: z.int(),
397
+ })
398
+ const TaskPage = z.strictObject({
399
+ items: z.array(Task),
400
+ next: z.nullable(z.string()),
401
+ })
402
+ const ListTasks = z.strictObject({
403
+ projectId: z.uuid(),
404
+ after: Cursor.optional(),
405
+ })
406
+ const MyTasks = z.strictObject({ after: Cursor.optional() })
407
+ const NewTask = z.strictObject({
408
+ projectId: z.uuid(),
409
+ title: z.string().min(1).max(200),
410
+ })
411
+
412
+ export const tasks = app.group({ callers: ['human'] }, (r) => ({
413
+ list: r.query({
414
+ input: ListTasks,
415
+ output: TaskPage,
416
+ access: { action: 'tasks.read', in: 'project', from: 'projectId' },
417
+ })
418
+ .handle(async ({ input, ctx }) =>
419
+ fromPage(
420
+ Task,
421
+ await ctx.db.target.tasks.list({
422
+ orderBy: [['title', 'asc']],
423
+ after: input.after,
424
+ }),
425
+ )
426
+ ),
427
+ reachable: r.query({
428
+ input: MyTasks,
429
+ output: TaskPage,
430
+ access: { action: 'tasks.read', over: 'project' },
431
+ })
432
+ .handle(async ({ input, ctx }) =>
433
+ fromPage(
434
+ Task,
435
+ await ctx.db.within.tasks.list({
436
+ orderBy: [['title', 'asc']],
437
+ after: input.after,
438
+ }),
439
+ )
440
+ ),
441
+ mine: r.query({
442
+ input: MyTasks,
443
+ output: TaskPage,
444
+ access: { action: 'tasks.read', over: 'project' },
445
+ })
446
+ .handle(async ({ input, ctx }) =>
447
+ fromPage(
448
+ Task,
449
+ await ctx.db.within.tasks.list({
450
+ where: [['done', '=', false]],
451
+ orderBy: [['title', 'asc']],
452
+ after: input.after,
453
+ }),
454
+ )
455
+ ),
456
+ create: r.mutation({
457
+ input: NewTask,
458
+ output: Saved,
459
+ access: { action: 'tasks.write', in: 'project', from: 'projectId' },
460
+ })
461
+ .handle(({ input, ctx }) =>
462
+ ctx.db.target.tasks.insert({ title: input.title })
463
+ ),
464
+ finish: r.mutation({
465
+ input: Versioned,
466
+ output: Saved,
467
+ access: { action: 'tasks.write', on: 'task', from: 'id' },
468
+ })
469
+ .handle(({ input, ctx }) =>
470
+ ctx.db.target.update({ done: true }, {
471
+ expectVersion: input.expectVersion,
472
+ })
473
+ ),
474
+ }))
475
+ ```
476
+
477
+ ```ts fabrika.contract.ts
478
+ import { app } from './src/app-kit'
479
+ import { projects } from './src/projects/endpoints'
480
+ import { tasks } from './src/tasks/endpoints'
481
+
482
+ export const contract = app.contract((c) => ({
483
+ api: c.rpc('/api', { projects, tasks }),
484
+ health: c.health('/healthz'),
485
+ }))
486
+ ```
487
+
488
+ - The handlers know nothing of relations. An assistant's `on`, `in` and `over` calls reach a project and its tasks
489
+ exactly while a row names it there. Elsewhere an `on` call is 404, an `in` call 403 and an `over` list leaves the
490
+ project out, as for any caller without the action there.
491
+ - `assign` takes the assistant's principal id from the input: that is the person picked, never the caller. `days`
492
+ stops at the policy's `maxDays`, so of the layer's bounds only the writer naming itself answers 409.
493
+
494
+ ## Tests
495
+
496
+ Grant the role app-wide (`{ role: 'assistant' }`, no scope), as IAM does, or in an organization to hold it only there, and let
497
+ the endpoints write the rows:
498
+
499
+ ```ts src/__tests__/assistants.test.ts
500
+ import { createClient } from '@fabrika/app/client'
501
+ import { statusOf, testKit } from '@fabrika/app/testing'
502
+ import { testDatabase } from '@fabrika/db/testing'
503
+ import { afterAll, describe, expect, test } from 'bun:test'
504
+ import { contract } from '../../fabrika.contract'
505
+ import app from '../app'
506
+
507
+ const postgres = await testDatabase({
508
+ migrations: new URL('../../db/migrations/', import.meta.url),
509
+ label: 'assistants.test.ts',
510
+ })
511
+
512
+ if (postgres !== null) {
513
+ afterAll(() => postgres.close())
514
+ const kit = testKit(app, { database: postgres.database })
515
+ const acme = kit.scope('org', 'acme')
516
+ const assistant = kit.testCaller([{ role: 'assistant' }])
517
+ const coordinator = kit.testCaller([{ role: 'coordinator', scope: acme }])
518
+ const ownerApi = createClient(contract, 'api', {
519
+ fetch: kit.browser(kit.testCaller([{ role: 'owner', scope: acme }])),
520
+ })
521
+ const coordinatorApi = createClient(contract, 'api', {
522
+ fetch: kit.browser(coordinator),
523
+ })
524
+ const assistantApi = createClient(contract, 'api', {
525
+ fetch: kit.browser(assistant),
526
+ })
527
+
528
+ describe('an assistant', () => {
529
+ test('reaches a project only while a row names it there', async () => {
530
+ const launch = await ownerApi.projects.create({
531
+ orgId: 'acme',
532
+ name: 'Launch',
533
+ })
534
+ const other = await ownerApi.projects.create({
535
+ orgId: 'acme',
536
+ name: 'Other',
537
+ })
538
+ expect(await statusOf(assistantApi.tasks.list({ projectId: launch.id })))
539
+ .toBe(403)
540
+ const assignment = await coordinatorApi.projects.assign({
541
+ id: launch.id,
542
+ assistant: assistant.id,
543
+ days: 7,
544
+ })
545
+ const task = await assistantApi.tasks.create({
546
+ projectId: launch.id,
547
+ title: 'Brief',
548
+ })
549
+ expect((await assistantApi.tasks.mine({})).items.map((item) => item.id))
550
+ .toEqual([task.id])
551
+ expect(await assistantApi.tasks.finish({ id: task.id, expectVersion: 1 }))
552
+ .toEqual({ id: task.id, version: 2 })
553
+ expect(
554
+ await statusOf(
555
+ assistantApi.tasks.create({ projectId: other.id, title: 'No' }),
556
+ ),
557
+ ).toBe(403)
558
+ await coordinatorApi.projects.unassign({
559
+ id: launch.id,
560
+ assignment: assignment.id,
561
+ })
562
+ expect(
563
+ await statusOf(
564
+ assistantApi.tasks.finish({ id: task.id, expectVersion: 2 }),
565
+ ),
566
+ ).toBe(404)
567
+ expect((await assistantApi.tasks.mine({})).items).toEqual([])
568
+ })
569
+
570
+ test('a coordinator does not assign itself', async () => {
571
+ const project = await ownerApi.projects.create({
572
+ orgId: 'acme',
573
+ name: 'Self',
574
+ })
575
+ expect(
576
+ await statusOf(coordinatorApi.projects.assign({
577
+ id: project.id,
578
+ assistant: coordinator.id,
579
+ days: 1,
580
+ })),
581
+ ).toBe(409)
582
+ })
583
+
584
+ test('a grant of the role in an organization reaches only its projects', async () => {
585
+ const project = await ownerApi.projects.create({
586
+ orgId: 'acme',
587
+ name: 'Scoped',
588
+ })
589
+ const inAcme = kit.testCaller([{ role: 'assistant', scope: acme }])
590
+ const inGlobex = kit.testCaller([
591
+ { role: 'assistant', scope: kit.scope('org', 'globex') },
592
+ ])
593
+ for (const scoped of [inAcme, inGlobex]) {
594
+ await coordinatorApi.projects.assign({
595
+ id: project.id,
596
+ assistant: scoped.id,
597
+ days: 1,
598
+ })
599
+ }
600
+ const acmeApi = createClient(contract, 'api', { fetch: kit.browser(inAcme) })
601
+ const globexApi = createClient(contract, 'api', {
602
+ fetch: kit.browser(inGlobex),
603
+ })
604
+ expect((await acmeApi.tasks.list({ projectId: project.id })).items).toEqual(
605
+ [],
606
+ )
607
+ expect(await statusOf(globexApi.tasks.list({ projectId: project.id }))).toBe(
608
+ 403,
609
+ )
610
+ })
611
+ })
612
+
613
+ describe('an auditor', () => {
614
+ test('reads the finished tasks of the organization it audits, and only those', async () => {
615
+ const project = await ownerApi.projects.create({
616
+ orgId: 'acme',
617
+ name: 'Audited',
618
+ })
619
+ const open = await ownerApi.tasks.create({
620
+ projectId: project.id,
621
+ title: 'Open',
622
+ })
623
+ const done = await ownerApi.tasks.create({
624
+ projectId: project.id,
625
+ title: 'Done',
626
+ })
627
+ await ownerApi.tasks.finish({ id: done.id, expectVersion: 1 })
628
+ const auditorApi = createClient(contract, 'api', {
629
+ fetch: kit.browser(kit.testCaller([{ role: 'auditor', scope: acme }])),
630
+ })
631
+ const outsiderApi = createClient(contract, 'api', {
632
+ fetch: kit.browser(
633
+ kit.testCaller([{ role: 'auditor', scope: kit.scope('org', 'globex') }]),
634
+ ),
635
+ })
636
+ // `reachable` filters nothing itself: only the view keeps the open task from the auditor.
637
+ const audited = (await auditorApi.tasks.reachable({})).items.map((item) =>
638
+ item.id
639
+ )
640
+ expect(audited).toContain(done.id)
641
+ expect(audited).not.toContain(open.id)
642
+ expect((await outsiderApi.tasks.reachable({})).items).toEqual([])
643
+ })
644
+ })
645
+
646
+ describe('a project past its end', () => {
647
+ test('is read, and takes no new task from anyone', async () => {
648
+ const ended = await ownerApi.projects.create({
649
+ orgId: 'acme',
650
+ name: 'Ended',
651
+ endsAt: '2026-01-01T00:00:00Z',
652
+ })
653
+ await coordinatorApi.projects.assign({
654
+ id: ended.id,
655
+ assistant: assistant.id,
656
+ days: 7,
657
+ })
658
+ expect((await assistantApi.tasks.list({ projectId: ended.id })).items)
659
+ .toEqual([])
660
+ expect(
661
+ await statusOf(
662
+ assistantApi.tasks.create({ projectId: ended.id, title: 'Late' }),
663
+ ),
664
+ ).toBe(409)
665
+ expect(
666
+ await statusOf(
667
+ ownerApi.tasks.create({ projectId: ended.id, title: 'Late' }),
668
+ ),
669
+ ).toBe(409)
670
+ })
671
+ })
672
+ }
673
+ ```
674
+
675
+ ## Not built yet
676
+
677
+ - No widening condition (`admits`): a `when` only narrows. A row that some other rule should open to more people is
678
+ reached by a grant, a relation or an access view, never by a condition.
679
+ - A relation for a person from outside the organization is not built.
680
+ - A view is never a relation source: write the source rows to a table, under `assign`.
681
+ - An assignment never changes in place: delete the row and insert a new one.
682
+ - No raw SQL and no JSON column in a condition, and no path longer than three foreign keys.