@jskit-ai/agent-docs 0.1.319 → 0.1.321

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 (37) hide show
  1. package/guide/agent/app-setup/authentication.md +9 -4
  2. package/guide/agent/app-setup/database-layer.md +3 -0
  3. package/guide/agent/framework/data-access.md +312 -22
  4. package/guide/agent/framework/typed-features.md +51 -9
  5. package/package.json +1 -1
  6. package/patterns/feature-package/example/booking-engine/package.json +1 -1
  7. package/patterns/minimal-foundation/example/package.json +4 -4
  8. package/patterns/shell-foundation/example/package.json +5 -5
  9. package/patterns/shell-foundation/example/packages/main/package.json +1 -1
  10. package/reference/autogen/KERNEL_MAP.md +4 -2
  11. package/reference/autogen/PATTERN_INDEX.md +38 -38
  12. package/reference/autogen/packages/auth-web.md +2 -0
  13. package/reference/autogen/packages/kernel.md +7 -4
  14. package/reference/autogen/packages/resource-runtime.md +7 -2
  15. package/reference/autogen/packages/workspaces-core.md +7 -2
  16. package/skills/jskit/references/data-access.md +312 -22
  17. package/skills/jskit/references/database-layer.md +3 -0
  18. package/skills/jskit/references/heuristics/INDEX.md +3 -3
  19. package/skills/jskit/references/heuristics/data-access.md +4 -1
  20. package/skills/jskit/references/heuristics/row-policies.md +6 -1
  21. package/skills/jskit/references/heuristics/typed-features.md +2 -0
  22. package/skills/jskit/references/pattern-index.md +38 -38
  23. package/skills/jskit/references/patterns/app/minimal-foundation/example/package.json +4 -4
  24. package/skills/jskit/references/patterns/app/shell-foundation/example/package.json +5 -5
  25. package/skills/jskit/references/patterns/app/shell-foundation/example/packages/main/package.json +1 -1
  26. package/skills/jskit/references/patterns/auth/accounts-hub/example/package.json +3 -3
  27. package/skills/jskit/references/patterns/auth/oidc-sign-in/example/package.json +2 -2
  28. package/skills/jskit/references/patterns/auth/supabase-auth/example/package.json +1 -1
  29. package/skills/jskit/references/patterns/connectors/calendar-cli/example/package.json +4 -4
  30. package/skills/jskit/references/patterns/crud/crud-feature-package/example/packages/books/package.json +3 -3
  31. package/skills/jskit/references/patterns/database/mysql-application/example/package.json +2 -2
  32. package/skills/jskit/references/patterns/database/postgres-application/example/package.json +2 -2
  33. package/skills/jskit/references/patterns/realtime/realtime-application/example/package.json +2 -2
  34. package/skills/jskit/references/patterns/server/feature-package/example/booking-engine/package.json +1 -1
  35. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/package.json +3 -3
  36. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/package.json +6 -6
  37. package/skills/jskit/references/typed-features.md +51 -9
@@ -39,6 +39,7 @@ through its handle's calls, and every call takes the call's `options` last:
39
39
  | `patchMany(rows, options)` | many records, each with its own changes |
40
40
  | `patchWhere(filters, changes, options)`, `deleteWhere(filters, options)` | every matching row |
41
41
  | `lock(id, txOptions)`, `lockMany(ids, txOptions)`, `lockWhere(filters, txOptions)` | rows locked until the transaction ends |
42
+ | `lockPages(filters, txOptions)` | every matching row locked, handed over a page at a time ([Layer 4](#layer-4-locks)) |
42
43
  | `lockOrCreate({ id, ...initial }, options, work)` | a keyed record locked, created first when missing, for `work` |
43
44
  | `claim({ filters, sort, take }, txOptions)` | the next rows no other worker holds |
44
45
  | `withTransaction(options, work)` | one transaction; `work` gets its `txOptions` |
@@ -83,6 +84,7 @@ the filters match.
83
84
  | scoped query | The read-only Knex builder `scopedQuery()` returns, with ownership and the row policy already applied. |
84
85
  | system scope | Why a feature works across every workspace and user, declared with `systemScope`. |
85
86
  | system context | The context of that work, from `systemContext(reason)`; `forWorkspace`, `forUser` and `forWorkspaceUser` narrow it. |
87
+ | member context | The context of work done as one member of one workspace, from `workspaces.memberContext({ workspaceId, userId }, { context: systemContext(reason) })`: resolved as the member's request is, and signed in as them. |
86
88
  | `txOptions` | What `withTransaction(options, work)` hands `work`: only the call's context and its transaction, `{ context, trx }`, passed to every call inside. |
87
89
  | record | What a handle answers: `{ id, ...fields }`, relationships as ids, included records nested. |
88
90
 
@@ -328,6 +330,43 @@ code reads by the key with a filter and writes by it with an upsert,
328
330
  guide](existing-application-migration.md#moving-hand-written-sql-behind-resources)
329
331
  has the migration for a table that exists already.
330
332
 
333
+ A table its feature counts but must never read back row by row (who took part
334
+ in an anonymous survey whose answers are stored without names) takes a `uuid`
335
+ primary key the code makes with `crypto.randomUUID()`, never a sequence, and a
336
+ unique index on the columns that identify a row, the ownership column among
337
+ them. A random v4 id carries no time and no order, and MySQL and MariaDB store
338
+ rows in primary key order, so the stored order is random too; a sequence or a
339
+ time-ordered id (UUIDv7, or the v1 that MySQL's and MariaDB's `UUID()` makes)
340
+ would let whoever reads the rows match them to the order of the answers.
341
+ PostgreSQL's heap keeps the order rows were inserted in, which a direct read
342
+ of the table shows whatever the key, so the protection that holds everywhere is
343
+ that no code reads the rows: the owning feature offers only an insert and a
344
+ count, functions of its own over its handle, and ownership keeps every other
345
+ feature from reading the table.
346
+
347
+ ```js
348
+ import { randomUUID } from "node:crypto";
349
+
350
+ // the owning feature's whole API over the table: record that a member took part, and count who did
351
+ const recordParticipation = ({ recordId, userId }, options) =>
352
+ participations.createMany([{ id: randomUUID(), recordId, userId }], {
353
+ ...options,
354
+ onConflict: { keys: ["workspaceId", "recordId", "userId"], action: "ignore" }
355
+ });
356
+ const countParticipants = async (recordId, options) => {
357
+ const [{ participants }] = await participations.aggregate({ measures: { participants: { count: "*" } }, filters: { recordId } }, options);
358
+ return participants;
359
+ };
360
+ ```
361
+
362
+ `onConflict` ignore makes a second participation a no-op that keeps the stored
363
+ row and its id, and a new row takes the id it brings. Only a clash on the keys'
364
+ unique index is ignored, so an id that is already another row's still fails.
365
+ Plain `create({ id: randomUUID(), recordId, userId }, options)` refuses the
366
+ second participation instead, with the unique key's error; inside a
367
+ transaction the failed insert fails the whole transaction (PostgreSQL aborts it
368
+ at once), so work that must go on uses the ignore.
369
+
331
370
  A route that reads or writes without an action (a provider's callback, a
332
371
  download it streams) takes its options from `await request.callOptions()`: the
333
372
  context the same request's action would get, its user, workspace and route
@@ -430,10 +469,13 @@ request, `{ kind: "anonymous" }` for one by no one, and `{ kind: "system" }` or
430
469
  `reason`, for background work. A job names a user only as `actorId`, the
431
470
  person it works for ([below](#background-work)), so never read a missing actor
432
471
  as an anonymous request. The owner's policy also receives the capabilities its
433
- feature requires (and its optional ones), by local name, as `requires`, the
434
- same ones its setup receives: a policy that needs another feature's answer
435
- declares that feature's capability in `requires` and reads `requires.<name>`.
436
- It runs on every read, so what it asks there must be cheap.
472
+ feature requires (and its optional and late ones), by local name, as
473
+ `requires`, the same ones its setup receives: a policy that needs another
474
+ feature's answer declares that feature's capability in `requires` and reads
475
+ `requires.<name>`. When that feature requires the policy's own feature, the
476
+ two form a ring; the policy's feature declares the capability `late` instead
477
+ ([Capability cycles](#capability-cycles)). A policy runs on every read, so
478
+ what it asks there must be cheap.
437
479
 
438
480
  ```js
439
481
  // good: one predicate on the row being read
@@ -468,7 +510,12 @@ subquery to the row with `whereExists`: over `ownTable(name)`, which may join
468
510
  the owner's other tables, or over another owner's join source. A policy is told
469
511
  the call's `options`, `{ context, trx }` as the caller passed them, and passes
470
512
  them on unchanged to `joinSource({ alias }, options)`, so the join source reads
471
- in the caller's scope and transaction; never build them by hand.
513
+ in the caller's scope and transaction; never build them by hand. `options.trx`
514
+ names the transaction the read runs in: the caller's, or, for a write whose
515
+ caller named none, the one json-rest-api opens for it, which the lookup before
516
+ a patch and the read-back after a create run in. So an owner API the policy
517
+ calls with its `options` (a join source, or a handle read such as a role check)
518
+ joins that transaction and never waits for a second connection.
472
519
 
473
520
  ```js
474
521
  // good: a member of the document's team sees it, through the teams owner's join source
@@ -490,6 +537,45 @@ function teamDocumentsPolicy({ query, caller, column }) {
490
537
  }
491
538
  ```
492
539
 
540
+ A policy whose rule reads another owner's rows as stored (a document is
541
+ visible while its folder is open, whether or not the reader may see the folder
542
+ itself) reads them through that owner's API, never through a context it builds.
543
+ The owner answers a join source of its rows under its own `systemScope`,
544
+ narrowed to the call's workspace, so the rows stay that workspace's and `jskit
545
+ check` lists the reason. The policy passes its `options` on unchanged, as
546
+ always, and returns early for background work, whose own context already
547
+ decides. It still only narrows: the stored rows feed its predicate and are
548
+ never answered, so the reader sees no folder it could not see before.
549
+
550
+ ```js
551
+ // good: the folders' owner API, in the folders feature, whose setup receives systemContext
552
+ function storedSource({ alias }, options) {
553
+ const context = systemContext("the documents' row policy reads each folder's status as stored")
554
+ .forWorkspace(resolveWorkspaceScopeValue(options.context));
555
+ return folders.joinSource({ alias }, { ...passedOn(options), context });
556
+ }
557
+
558
+ // good: the documents' policy, which requires the folders' owner API
559
+ async function openFolderDocuments({ query, caller, column, options, requires }) {
560
+ if (caller.kind !== "user") {
561
+ return caller.kind !== "anonymous";
562
+ }
563
+ const folder = await requires.folders.storedSource({ alias: "f" }, options);
564
+ query.whereExists(folder.query.select(1).whereColumn(folder.column("id"), column("folderId")).where(folder.column("status"), "open"));
565
+ return true;
566
+ }
567
+ ```
568
+
569
+ A policy never walks a tree with a recursive query (`withRecursive`). No builder
570
+ it holds takes a common table expression, and a walk that starts at the row
571
+ being read does not compile on MariaDB, which lets no outer column into a
572
+ recursive query's first member; a walk that starts elsewhere (the reader's
573
+ grants, walking down) reads the reader's whole subtree on every read. Keep the
574
+ tree's ancestry stored instead: its owner writes a closure table (each node's
575
+ ancestors, one row each, with their depth) in the same transaction that adds
576
+ or moves a node, and the policy ties one `whereExists` over that table's join
577
+ source to the row, on indexed columns, on every database.
578
+
493
579
  A rule that depends on the caller's role reads `context.permissions` with
494
580
  `hasPermission(context.permissions, "bookings.view-all")` from
495
581
  `@jskit-ai/kernel/shared/support`, never with `includes()`. A role may hold
@@ -684,11 +770,14 @@ could update or hide another workspace's row. `merge` is refused under a row
684
770
  policy; use `ignore`, then `patchMany`. A table with no owners and no row
685
771
  policy, keyed by a natural id such as an email, may key the upsert on the id
686
772
  alone: `onConflict: { keys: ["id"], action: "merge" }`, with an id on every
687
- row, creates the record or replaces the fields given in one statement. Of two
688
- upserts at once the later stays, so a counter that must count both is created
689
- plainly and its duplicate retried instead. Inserting and catching the
690
- duplicate works only outside a transaction: inside one, the failed insert
691
- fails the whole transaction, so use an upsert there.
773
+ row, creates the record or replaces the fields given in one statement. A merge's
774
+ rows carry no other id; an `ignore`'s may, for ids the code makes (a random
775
+ `uuid`): a new row takes its own, and a row the keys match keeps the stored one
776
+ (see the count-only table above). Of two upserts at once the later stays, so a
777
+ counter that must count both is created plainly and its duplicate retried
778
+ instead. Inserting and catching the duplicate works only outside a transaction:
779
+ inside one, the failed insert fails the whole transaction, so use an upsert
780
+ there.
692
781
 
693
782
  A transaction whose insert loses a race for a unique key (another request with
694
783
  the same idempotency key committed first) runs once more:
@@ -722,6 +811,21 @@ or a counter row taken with `lock(id)`. Every lock needs a transaction; SQLite
722
811
  runs one transaction at a time, so there is no row lock to take. Take locks in
723
812
  one order on every path, a parent before its children.
724
813
 
814
+ `lockWhere` takes that order from `sort` too: `lockWhere({ batchId }, {
815
+ ...txOptions, sort: ["moduleKey"] })` locks the rows in `sort` order
816
+ (fields, `"-moduleKey"` for descending), then by id, and answers them in it,
817
+ so two paths that lock overlapping rows wait for each other instead of
818
+ deadlocking. `limit` locks only the first rows of that order, by id without a
819
+ `sort`: a check whether any row matches, or the lock of one row by a unique key
820
+ other than its id, takes `limit: 1`, one statement as `lock(id)` is
821
+ (`workspaces.memberships.lockByWorkspaceIdAndUserId` locks its membership so).
822
+ Without either, `lockWhere` locks every match in id order (on MySQL and MariaDB
823
+ in the order of the index it reads, below), at most 1,000 (more throw), and
824
+ PostgreSQL reads them once more under its locks, for a row that started to
825
+ match while it waited; with a `limit` it stops once it holds that many. A
826
+ `limit` outside 1 to 1,000, or a `sort` on no stored field, is refused before
827
+ any statement.
828
+
725
829
  A lock answers the rows it locks, with the fields `fields` names. Its
726
830
  `include` names belongs-to relationships (`include: ["customer"]`, or
727
831
  `"batch.yard"` a level further): after its own rows, the lock locks the
@@ -761,13 +865,57 @@ const [booked] = await bookings.queryAll({ filters: { seatIds: [seatId] }, take:
761
865
  await seats.lock(seatId, txOptions);
762
866
  ```
763
867
 
868
+ A whole set of rows the work decides on (a register's entries, an account's
869
+ movements) is read the same way: every writer of the set first locks the one
870
+ row that governs it (the register, the account), and the work locks that row
871
+ before its first plain read. The plain reads after it (`queryAll`,
872
+ `queryPages`, `aggregate`) are then current and stay so until commit, at any
873
+ size, for one statement more. Work that joins its caller's transaction cannot
874
+ know whether the caller already read plainly, and on MySQL and MariaDB a lock
875
+ taken after that no longer moves the snapshot, so it reads the set with
876
+ locking reads, which see the latest rows whatever the snapshot:
877
+ `lockPages(filters, txOptions)` locks every row the filters select, a page of
878
+ up to 1,000 (`pageSize`) at a time, in id order, each page one locking read
879
+ after the last id of the page before. It still locks the governing row first,
880
+ since PostgreSQL keeps no new row out of a page already locked. In a request it
881
+ throws past the request row limit, as `queryPages` does. Isolation is not the
882
+ tool: MySQL and MariaDB fix it when a transaction starts, and READ COMMITTED
883
+ alone reads each page at a different moment. `patchWhere` and `deleteWhere`
884
+ select their rows with a locking read on MySQL and MariaDB, so they too see
885
+ what committed after the transaction's first plain read. With MariaDB's
886
+ `innodb_snapshot_isolation` on, a locking read that meets a row changed since
887
+ the snapshot fails (errno 1020) instead, and `withTransaction` runs the work
888
+ again when it opened the transaction.
889
+
890
+ ```js
891
+ // good: inside the caller's transaction, the register locked, then every entry locked and read as it is now
892
+ const closeRegister = (registerId, options) => registers.withTransaction({ ...options, joinOnly: true }, async (txOptions) => {
893
+ await registers.lock(registerId, { ...txOptions, lockMode: "share", fields: ["id"] });
894
+ let total = 0;
895
+ for await (const page of entries.lockPages({ registerId }, { ...txOptions, lockMode: "share", fields: ["amount"] })) {
896
+ total += page.reduce((sum, entry) => sum + entry.amount, 0);
897
+ }
898
+ return total;
899
+ });
900
+
901
+ // bad: a plain read inside a joined transaction reads the caller's snapshot, which can miss entries
902
+ const all = await entries.queryAll({ filters: { registerId } }, txOptions);
903
+ ```
904
+
764
905
  On MySQL and MariaDB a locking read locks every row it examines, so two rules
765
906
  apply there. Lock ids taken from your own scoped reads, never a list straight
766
907
  from a request: every id listed is locked, a hidden one too, before it is left
767
908
  out. And `lockWhere` needs an index that starts with the ownership columns (on
768
909
  a table with no owners, with a column the filters compare); without one it
769
910
  refuses with `RestApiBulkWriteUnsupportedError` naming the index to add in a
770
- migration.
911
+ migration. With `sort` or `limit` the index must also read the rows in the
912
+ lock's order, since the database locks them in the order it reads them: after
913
+ the ownership columns and the columns the filters fix to one value, it holds
914
+ the sort's columns, ascending, and then nothing but the id, and the sort's
915
+ fields go one way (all ascending or all descending). A unique key the filters
916
+ fix whole, as a membership's workspace and user are, needs nothing more.
917
+ `lockPages` locks in id order, so its index holds nothing after the ownership
918
+ columns and the columns the filters fix but the id.
771
919
 
772
920
  A worker taking the next job uses `claim({ filters, sort, take }, txOptions)`,
773
921
  which skips rows another worker holds. A record that serializes work on a key
@@ -822,8 +970,15 @@ await memberships.patch(input.membershipId, { lastFiledAt: new Date() }, txOptio
822
970
  ```
823
971
 
824
972
  Locks stay on the owner's handle and its owner API. A `scopedQuery()` or
825
- `joinSource()` builder takes no lock, and a row policy is not told a read's
826
- lock mode: it says which rows a caller may see, the same for every read. Rows
973
+ `joinSource()` builder takes no lock, not even a shared one: PostgreSQL's `FOR
974
+ SHARE OF` an alias would lock only that source's rows, but MariaDB has no `FOR
975
+ SHARE OF` at all, and its `LOCK IN SHARE MODE` covers every row the statement
976
+ examines, in every table. A report that needs another
977
+ owner's rows unchanged until it commits first locks them through that owner's
978
+ handle or owner API with `lockMode: "share"` (by a unique key with `limit:
979
+ 1`), then reads its join. A row policy is not told a read's lock mode, and
980
+ never takes a lock: it says which rows a caller may see, the same for every
981
+ read, and the lock call it narrows takes its own mode. Rows
827
982
  of several owners are never locked in one statement over a join, which on
828
983
  MySQL and MariaDB locks every joined row the read examines: lock each owner's
829
984
  rows with its own `lock`, `lockMany` or `lockWhere`, the owners in one fixed
@@ -1217,6 +1372,38 @@ const SettlementFeature = defineFeature({
1217
1372
  request's `caller.userId`, so a job for a person sees what that person may
1218
1373
  see, and a job for no one its whole scope. Work on one person's rows only
1219
1374
  takes their scope (`forUser`, `forWorkspaceUser`) or filters its reads.
1375
+ - Work done as one member of a workspace, running what their own request would
1376
+ (an action that checks their permissions, code that reads `context.actor`):
1377
+ a record started for the person it is assigned to, a notification for one
1378
+ recipient, a submission synced for the person who made it. It asks
1379
+ workspaces-core for the member's context, never builds one by hand, since a
1380
+ hand-built context drifts from what a request resolves:
1381
+
1382
+ ```js
1383
+ // requires: { workspaces: "workspaces.core", actions: "runtime.actions" }; the feature declares systemScope
1384
+ const member = await workspaces.memberContext(
1385
+ { workspaceId: record.workspaceId, userId: record.assigneeId },
1386
+ { context: systemContext("start each scheduled record for the person it is assigned to") }
1387
+ );
1388
+ await actions.execute({ actionId: "crud.visits.create", input, context: { ...member, surface: "app" } });
1389
+ ```
1390
+
1391
+ `memberContext` resolves the member as their request on a `workspace_user`
1392
+ route does, by the same reads: the workspace, their active membership (the
1393
+ owner's ensured), their role's permissions and the settings. It refuses as
1394
+ that request does: a missing or deleted workspace is 404
1395
+ `workspaces.workspace.notFound`, and a user who is no active member of it
1396
+ (removed, inactive, never one, or no user) 403
1397
+ `workspaces.workspace.accessDenied`. The context signs the member in, unlike
1398
+ `{ actorId }`: `resolveActorId` answers them, an action checks their
1399
+ permissions, a row policy is told `caller.kind` "user", request row limits
1400
+ apply and other owners' hidden fields stay hidden. Its scope is the workspace
1401
+ and the member, so an event reaches that member there. Only a system context
1402
+ makes one, and an action it runs names the surface the member's request would
1403
+ use. It reads no sign-in state: JSKIT keeps no disabled flag on users, so an
1404
+ account its auth provider refuses at sign-in (a local account marked
1405
+ disabled) is still resolved; a job that must skip such people asks the
1406
+ provider first.
1220
1407
  - A job finds its units with an `aggregate` grouped by the ownership field,
1221
1408
  which a system context may group by (and count distinct) even when the table
1222
1409
  hides it, then runs each unit scoped to it. It reads the units in pages, all
@@ -1237,21 +1424,46 @@ const SettlementFeature = defineFeature({
1237
1424
  }
1238
1425
  }
1239
1426
  ```
1427
+ - A job whose units are the workspaces themselves (each workspace's daily
1428
+ digest, whether or not it has rows yet) pages through them with the
1429
+ `workspaces` owner API, never the table by name:
1430
+ `workspaces.listForSystem({ afterId, limit }, { context: systemContext(reason) })`
1431
+ answers the `{ id, slug }` of the workspaces that are not deleted, in id
1432
+ order, after `afterId` (from the first when it is null), at most `limit` (1 to
1433
+ `pageLimits().request`, 100 by default). Each page is one statement however
1434
+ many workspaces there are: pass a page's last id as the next `afterId`, and a
1435
+ page shorter than `limit` is the last. Any other context, a `forWorkspace`
1436
+ job's too, is refused, as are an `afterId` that is no workspace id and a
1437
+ `limit` out of range:
1438
+
1439
+ ```js
1440
+ // requires: { workspaceRecords: "workspaces" }; the feature declares systemScope
1441
+ for (let afterId = null; ;) {
1442
+ const page = await workspaceRecords.listForSystem({ afterId, limit: 100 }, { context: systemContext("send every workspace's daily digest") });
1443
+ for (const { id } of page) await sendDigest({ context: systemContext("send every workspace's daily digest").forWorkspace(id) });
1444
+ if (page.length < 100) break;
1445
+ afterId = page.at(-1).id;
1446
+ }
1447
+ ```
1240
1448
  - A job that must learn each row's owner across workspaces names the hidden
1241
1449
  ownership field in its read's `fields`, `queryAll({ filters, fields:
1242
1450
  ["workspaceId", "email"] }, { context })`, as a system context may do through
1243
1451
  another feature's CRUD repository too (see [Layer
1244
1452
  1](#layer-1-the-table-resource)). Never unhide it for the job.
1245
1453
  - A request uses its own context. The exceptions are a console report
1246
- behind a console permission, with bounded output, and the write of a shared
1247
- row it has proved it reaches ([Layer 1](#layer-1-the-table-resource)).
1454
+ behind a console permission, with bounded output, the write of a shared
1455
+ row it has proved it reaches ([Layer 1](#layer-1-the-table-resource)), and
1456
+ an owner API that answers its own rows as stored to another owner's row
1457
+ policy, narrowed to the call's workspace ([Layer
1458
+ 1](#layer-1-the-table-resource)).
1248
1459
  - `jskit check` lists every system scope and every `systemContext` call with
1249
1460
  its reason, read from the string literal at the call: a reason kept in a
1250
1461
  constant reads as none.
1251
1462
  - A system context comes only from `systemScope`, and a context's scope only
1252
- from the request or from `forWorkspace`, `forUser` and `forWorkspaceUser`:
1253
- lint refuses `createSystemContext` and hand-written `scopeValues`, and a
1254
- context naming two workspaces or two users throws.
1463
+ from the request, from `forWorkspace`, `forUser` and `forWorkspaceUser`, or
1464
+ from `workspaces.memberContext`: lint refuses `createSystemContext` and
1465
+ hand-written `scopeValues`, and a context naming two workspaces or two users
1466
+ throws.
1255
1467
  - A table only the feature's own background work reads and writes, whose rows
1256
1468
  belong to no workspace or user (an agent's runs, a server's leases, a queue
1257
1469
  keyed by something other than an owner), takes ownership `system`. Every call
@@ -1293,7 +1505,7 @@ never open one of its own, passes `{ ...options, joinOnly: true }`: called
1293
1505
  outside a transaction it throws a TypeError before the work runs. Code never
1294
1506
  asks whether it runs in a transaction: `withTransaction` joins the caller's,
1295
1507
  `outermost` refuses one, `joinOnly` requires one, and `lock`, `lockMany`,
1296
- `lockWhere` and `claim` refuse to run outside one; `lockOrCreate` opens its own
1508
+ `lockWhere`, `lockPages` and `claim` refuse to run outside one; `lockOrCreate` opens its own
1297
1509
  (and retries a lost insert race only then).
1298
1510
 
1299
1511
  ```js
@@ -1364,6 +1576,9 @@ workspaces. A report that reads people, their settings, workspaces or
1364
1576
  memberships beside its own rows joins `joinSource({ alias, filters },
1365
1577
  options)` of `users.profiles`, `users.settings`, `workspaces` or
1366
1578
  `workspaces.memberships` ([Layer 5](#layer-5-reports-the-resource-cannot-express)).
1579
+ A background job that visits every workspace pages them with
1580
+ `workspaces.listForSystem({ afterId, limit }, options)`, in its system context
1581
+ ([Background work](#background-work)).
1367
1582
 
1368
1583
  An app that had a table resource of its own over a JSKIT table (such as
1369
1584
  `users`) deletes it: its CRUD contract is built on the package's table resource
@@ -1420,7 +1635,8 @@ without it.
1420
1635
 
1421
1636
  A capability cycle is a ring of requires: feature A requires a capability that
1422
1637
  feature B provides while B, directly or through others, requires one that A
1423
- provides. An `optional` require closes a ring as a required one does. The
1638
+ provides. An `optional` require closes a ring as a required one does; a
1639
+ `late` one does not ([below](#late-requirements)). The
1424
1640
  kernel sets features up in the order their requires give, so it cannot start a
1425
1641
  ring: boot fails before any setup, naming it,
1426
1642
  `Provider capability cycle detected: children -> parents -> children.`
@@ -1444,10 +1660,74 @@ Keep every require pointing one way:
1444
1660
  definitions, move those table resources into a package of their own that
1445
1661
  holds only shared definitions and depends on neither.
1446
1662
  - Never break a ring with a value handed over later (a setter, a capability
1447
- looked up at call time): a call's destination then depends on what ran
1448
- before. A setter kept until the split carries typed features' `cycle:`
1663
+ looked up by name at call time): a call's destination then depends on what
1664
+ ran before. A setter kept until the split carries typed features' `cycle:`
1449
1665
  exception ([Optional tokens](typed-features.md#optional-tokens)).
1450
1666
 
1667
+ ### Late requirements
1668
+
1669
+ A ring that only a read at call time closes, most often a row policy's, and
1670
+ that you cannot or do not want to split, is broken with a late requirement:
1671
+ the kernel's declared alternative to a setter. An audit history whose row
1672
+ policy narrows through the evidence files' owner, while the evidence owner
1673
+ records each change in the audit history, is one: the evidence feature
1674
+ requires `audit.history` as usual, and the audit feature declares
1675
+ `late: { evidence: "evidence.files" }`.
1676
+
1677
+ - A late requirement takes no part in the order features start in, nor in the
1678
+ cycle check, so the ring starts. The kernel resolves it once, after every
1679
+ feature's `boot()`: its destination is declared, so it never depends on what
1680
+ ran before.
1681
+ - It is read at call time only: in a row policy (`requires.evidence`), a
1682
+ request handler, or a method setup builds that runs later, which keeps the
1683
+ capabilities object and reads the name when it runs. A read before every
1684
+ feature has booted (in setup or boot, or a late name destructured in setup's
1685
+ parameters) throws `Provider "audit" read its late requirement "evidence"
1686
+ (capability "evidence.files") before every provider booted: ...`, which
1687
+ says where it may be read. A shutdown reads it only after a start that
1688
+ finished.
1689
+ - It is required: when no feature or runtime input provides it, start fails at
1690
+ the end of boot, `Provider "audit" late-requires missing capability
1691
+ "evidence.files": no provider or runtime input provides it.`, and stops what
1692
+ started, as any startup failure does. The package manifest lists it under
1693
+ `requires`.
1694
+ - A feature never late-requires a capability it provides, nor one it already
1695
+ requires or takes as optional.
1696
+ - The one-way rules above still come first: split the ring when you can. A
1697
+ ring that both features' setup or boot needs cannot be broken this way,
1698
+ since a late requirement is never read there.
1699
+
1700
+ ```js
1701
+ // good: the audit history's row policy reads the evidence owner's join source at call time
1702
+ const AuditFeature = defineFeature({
1703
+ id: "audit",
1704
+ owns: [{ resource: auditEntryResource, rowPolicy: auditEntriesPolicy }],
1705
+ late: {
1706
+ evidence: "evidence.files"
1707
+ },
1708
+ provides: {
1709
+ history: "audit.history"
1710
+ },
1711
+ setup({ resources }) {
1712
+ return { history: createAuditHistory({ entries: resources.auditEntries }) };
1713
+ }
1714
+ });
1715
+
1716
+ async function auditEntriesPolicy({ query, caller, column, options, requires }) {
1717
+ if (caller.kind !== "user") {
1718
+ return caller.kind !== "anonymous";
1719
+ }
1720
+ const file = await requires.evidence.joinSource({ alias: "ef" }, options);
1721
+ query.whereExists(file.query.select(1).whereColumn(file.column("id"), column("evidenceFileId")));
1722
+ return true;
1723
+ }
1724
+
1725
+ // bad: the late name destructured in setup, before every feature has booted; boot fails
1726
+ setup({ resources, evidence }) {
1727
+ return { history: createAuditHistory({ entries: resources.auditEntries, evidence }) };
1728
+ }
1729
+ ```
1730
+
1451
1731
  ## Check and judge
1452
1732
 
1453
1733
  Before calling data work done, apply the
@@ -1604,6 +1884,16 @@ server code is server code. Neither `eslint-disable`, an inline
1604
1884
 
1605
1885
  ### Exceptions
1606
1886
 
1887
+ A data-access rule that refuses a statement points at a missing API, never at a
1888
+ statement to excuse: no rule takes a per-statement exception. When no owner
1889
+ API does what the work needs (locks in a given order, one row by a unique key,
1890
+ a check the row policy cannot write), ask for one: from the feature that owns
1891
+ the table, or from JSKIT for its own packages and for the handle itself. Only
1892
+ statements that are data access themselves go under an exception, in a file
1893
+ of their own declared as infrastructure (below), kept small and holding only
1894
+ those statements, so the exception hides nothing else: a repository, a row
1895
+ policy or a report never moves into such a file to pass lint.
1896
+
1607
1897
  A module whose job is data access itself (a database runtime, a migration
1608
1898
  runner, test-database setup, an operator's data import or cutover tool, a
1609
1899
  database console that runs the person's own SQL) may opt out of
@@ -330,6 +330,9 @@ the application's `knexfile.js`:
330
330
  prepare), the files run one at a time on the connected database. A copy
331
331
  named like the application's database or `PROD_DB_NAME`, or a server that
332
332
  cannot be reached, fails the run instead.
333
+ Every file starts from the snapshot, rows included: a copy an earlier file of
334
+ the run used is restored before the next file takes it, so no file sees what
335
+ another wrote.
333
336
  - The snapshot holds the schema as the engine reports it and the rows the
334
337
  migrations wrote, including the migration ledger. On MySQL and MariaDB it is
335
338
  each table's `SHOW CREATE TABLE` and rows, in
@@ -42,11 +42,11 @@ How to use it:
42
42
  - [server-search.md](./server-search.md)
43
43
  - `actualField`, `storage.column`, `storage.writeSerializer`, `storage.virtual`, `queryFields`, computed field, virtual field, projection, `defaultTo`, datetime write serialization, temporalPrecision, json-rest-schema dates
44
44
  - [table-resource-fields.md](./table-resource-fields.md)
45
- - data access, database table, knex, raw, SQL, repository, bulk, batch, many rows, set write, upsert, lock, claim, totals, report, aggregate, newest per group, transaction, `trx`, background job, system scope, `systemContext`, owner, owns, owner API, another feature's table, scope test, `expectFlatQueries`, `requireTestDatabase`, `jskit/no-direct-knex`, `jskit/no-transaction-reader`, `jskit/no-hand-scope`, `jskit/sql-literal`, `jskit/knex-reason`, `infrastructure:`
45
+ - data access, database table, knex, raw, SQL, repository, bulk, batch, many rows, set write, upsert, lock, claim, totals, report, aggregate, newest per group, transaction, `trx`, background job, system scope, `systemContext`, every workspace, `listForSystem`, work done as a member, member context, `memberContext`, owner, owns, owner API, another feature's table, scope test, `expectFlatQueries`, `requireTestDatabase`, `jskit/no-direct-knex`, `jskit/no-transaction-reader`, `jskit/no-hand-scope`, `jskit/sql-literal`, `jskit/knex-reason`, `infrastructure:`
46
46
  - [data-access.md](./data-access.md)
47
- - row policy, permission filtering, visibility before pagination, recursive CTE, descendants, package cycle, `RowPolicyPlugin`, row policy cost, slow writes through a policy, access check per history item
47
+ - row policy, permission filtering, visibility before pagination, recursive CTE, descendants, package cycle, capability cycle a row policy closes, `late`, `RowPolicyPlugin`, row policy cost, slow writes through a policy, access check per history item
48
48
  - [row-policies.md](./row-policies.md)
49
- - typed features, server feature, provider, service, repository, collaborator, `typeof`, `= null`, `setProvider`, `register`, `input || {}`, `payload = {}`, `async execute`, `Object.freeze`, `requires`, `optional`, `types.js`, `RuntimeKnex`, `silentLogger`, `create<Name>Actions`, `ActionSpecifications`, request context, `handle.query`, `queryAll`, every row, list stops at one page, `jskit/*` lint findings, `readable-check: allow`, `optional operation:`, `process.env`, `AppError` code, `Object.assign(new Error`, `idempotency`, `…ForTests` export, file or function size, read per row, N+1 queries, slow endpoint, query budget, realistic row counts, slow tests, raised timeout, `migrate.latest()` in tests, test database snapshot, `--test-concurrency=1`, `node --test`, `jskit test`, `testConcurrency()`, `V64_TEST_CONCURRENCY`, Playwright `workers`, Vitest `maxWorkers`, tests one file at a time, test files colliding in parallel, `jskit-test: alone`, `test/*` findings of `jskit check`
49
+ - typed features, server feature, provider, service, repository, collaborator, `typeof`, `= null`, `setProvider`, `register`, `input || {}`, `payload = {}`, `async execute`, `Object.freeze`, `requires`, `optional`, `late`, `Provider capability cycle detected`, `types.js`, `RuntimeKnex`, `silentLogger`, `create<Name>Actions`, `ActionSpecifications`, request context, `handle.query`, `queryAll`, every row, list stops at one page, `jskit/*` lint findings, `readable-check: allow`, `optional operation:`, `process.env`, `AppError` code, `Object.assign(new Error`, `idempotency`, `…ForTests` export, file or function size, read per row, N+1 queries, slow endpoint, query budget, realistic row counts, slow tests, raised timeout, `migrate.latest()` in tests, test database snapshot, `--test-concurrency=1`, `node --test`, `jskit test`, `testConcurrency()`, `V64_TEST_CONCURRENCY`, Playwright `workers`, Vitest `maxWorkers`, tests one file at a time, test files colliding in parallel, `jskit-test: alone`, `test/*` findings of `jskit check`
50
50
  - [typed-features.md](./typed-features.md)
51
51
  - client features, composable, `use<Name>`, Vue component, client provider, props, emits, `inject`, `provide`, `ref`, `reactive`, `watch`, `addEventListener`, `setInterval`, module state, `Object.freeze` on a composable, `?.()` in a template, `jskit/typed-inject`, `jskit/collaborator-props`, `jskit/fixed-result-shape`, `jskit/released-listeners`, `jskit/no-module-state`, `jskit/no-frozen-vue-state`, `clientFeaturesConfig`, `shared resource:`
52
52
  - [client-features.md](./client-features.md)
@@ -11,10 +11,13 @@ Pick the layer ([Data access](../data-access.md)):
11
11
  - Screens over HTTP: a CRUD contract on the same table resource.
12
12
  - Many rows from one action: `createMany`, `patchMany`, `patchWhere`, `deleteWhere`; never a loop of single writes.
13
13
  - Two requests could change the same rows: `lockMany` inside `withTransaction`, rows in id order.
14
+ - A whole set the work decides on (a register's entries): the row that governs it locked first by every writer, and by the work before its first plain read; inside a transaction it joined, which may have read plainly already (MySQL and MariaDB then keep that snapshot), `lockPages` after that lock, never a plain `queryAll`.
15
+ - A table counted but never read back (anonymous participation): a `crypto.randomUUID()` id, a unique index on the identifying columns, and an owner API of insert (`createMany` with `onConflict` ignore) and count only.
14
16
  - Work inside `withTransaction`: `txOptions` is only `{ context, trx }`, so a key the work needs, the app's own included, comes from the method's `options`, and a write on the method's own table gets `{ ...options, ...txOptions }` so the caller's `returning`, `missing` or `format` reaches it.
15
17
  - A change only while a row still holds a value (open to booked, once): `patch` with `onlyIf`, or `patchWhere` with that value in its filters (a compare-and-set on every database, so of two concurrent writers one wins); a filter on a related table is refused on MySQL and MariaDB (`selection_cross_table`), so filter on the row's own columns, after locking the related rows with `lockMany`, or use `claim`.
16
18
  - Only some of the rows, one row, whether one exists: in the read (a searchSchema filter, `take: 1` or a page of size 1), never `.filter()`, `.find()`, `.some()`, `.slice()` or `.length` over the rows it answered ([Narrow in the query](../data-access.md#narrow-in-the-query)).
17
19
  - Counts, sums, buckets: `aggregate`; newest per group: a window include; anything else: one `scopedQuery()` method under `// Knex: <kind> - <reason>`.
18
- - Every workspace or user at once: a job with `systemScope`, finding its units with an `aggregate` grouped by the ownership field and looping over them, never rows.
20
+ - Every workspace or user at once: a job with `systemScope`, finding its units with an `aggregate` grouped by the ownership field and looping over them, never rows; every workspace itself, a page at a time: `workspaces.listForSystem({ afterId, limit }, { context: systemContext(reason) })`, never the workspaces table.
21
+ - Work done as one member (an action with their permissions, code that reads `context.actor`): `workspaces.memberContext({ workspaceId, userId }, { context: systemContext(reason) })` (`workspaces.core`), which resolves and refuses as their request does; never a hand-built `{ actor, workspace, membership, permissions }`.
19
22
  - A table another feature owns: its service or owner API, never its table. A report that joins it joins the `{ query, column }` its owner API answers from `scopedQuery({ alias })`, as a subquery: one statement, both scopes kept.
20
23
  - Every path: a scope test and `expectFlatQueries`; a data test fails without `TEST_DB_NAME`.
@@ -38,6 +38,8 @@ Package composition:
38
38
  - a package that narrows visibility further depends on the resource owner and calls `resources.contributeRowPolicy(name, policy)` on the handles its own `owns` gave it; a contribution is ANDed with the owner's policy inside its own group, so it can only narrow
39
39
  - a contribution never grants visibility: wider visibility (shared rows, grants another package records) is a rule in the owner's own policy over its own tables, and a contribution narrows every read of the table, every feature's included, so a rule for one surface is an owner API method instead
40
40
  - the resource owner does not import contributing packages
41
+ - a policy that narrows through another owner's join source, when that owner requires the policy's own feature, declares the owner's capability `late` and reads `requires.<name>` at call time: the kernel resolves it once every feature has booted ([Late requirements](../data-access.md#late-requirements))
42
+ - a policy whose rule reads another owner's rows as stored, whether or not the reader may see them, reads them through that owner's API, which answers a join source under its own `systemScope` narrowed to the call's workspace; never through a context the policy builds
41
43
  - do not use module-global mutable registries
42
44
 
43
45
  Example, "your rooms or shared rooms":
@@ -58,7 +60,9 @@ owns: [{
58
60
 
59
61
  A policy is told who the call runs for as `caller`: `user`, `anonymous`,
60
62
  `system` or `job`. Background work is `system` or `job`, never a missing user,
61
- and a job names its person only as `caller.actorId`. A policy hides a row from
63
+ and a job names its person only as `caller.actorId`; work done as one member
64
+ (`workspaces.memberContext`) is that member's `user`, as at their request. A
65
+ policy hides a row from
62
66
  every read, including other tables' links to it, so narrowing what one screen
63
67
  lists is a filter on that screen's read.
64
68
 
@@ -68,6 +72,7 @@ Cost:
68
72
  - never load the subject's whole history (every source, notice or grant they were ever linked to) to build an `IN` list, and never call another owner's access check per item of it; another package's restriction is a predicate contribution, and another package's grant is a predicate in the owner's policy over facts the owner keeps
69
73
  - the policy runs on every single-record read, including the read-back after a handle's `create()` and `patch()` (`returning: "record"`, their default) and the lookup before `patch` and `delete`, so a write pays it once per row it writes; the many-row writes check access once per statement
70
74
  - a write decides access once, inside its transaction; a batch write that would pay an expensive read-back per row follows the data access guide's [Layer 3](../data-access.md#layer-3-many-rows-at-once)
75
+ - a hierarchy (descendants, ancestors) is read through a closure table the tree's owner keeps, with one `whereExists` correlated with the row: no builder a policy holds takes a recursive CTE, and MariaDB compiles none that starts at the row being read
71
76
 
72
77
  Child-resource rules:
73
78
 
@@ -29,6 +29,8 @@ ends with the same link.
29
29
  - [Environment from the caller](../typed-features.md#environment-from-the-caller)
30
30
  - `setProvider`, `attach*`, any `set<Name>()` that fills a slot, `X | null` below the hook, `deferred until boot: <reason>` (`jskit/no-slot-setter`)
31
31
  - [Optional tokens](../typed-features.md#optional-tokens)
32
+ - `Provider capability cycle detected` that only a row policy or another call-time read closes, `late:`, `read its late requirement ... before every provider booted`, `late-requires missing capability`
33
+ - [Late requirements](../typed-features.md#late-requirements)
32
34
  - a module-level `register<Name>()`, `let x` or a `WeakMap` filled in `boot()` (`jskit/no-module-registry`)
33
35
  - [Owned state](../typed-features.md#owned-state)
34
36
  - `shutdown()` with `?.()` or `?? []`