@jskit-ai/agent-docs 0.1.328 → 0.1.329

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 (30) hide show
  1. package/guide/agent/app-extras/assistant.md +115 -2
  2. package/guide/agent/app-setup/authentication.md +16 -0
  3. package/guide/agent/app-setup/package-with-nix.md +118 -0
  4. package/guide/agent/app-setup/upgrading-jskit.md +21 -2
  5. package/guide/agent/framework/security-pass.md +136 -0
  6. package/guide/agent/framework/speed-pass.md +194 -0
  7. package/guide/agent/framework/ux-pass.md +116 -0
  8. package/guide/agent/index.md +11 -0
  9. package/package.json +1 -1
  10. package/patterns/minimal-foundation/example/package.json +2 -2
  11. package/patterns/shell-foundation/example/package.json +3 -3
  12. package/reference/autogen/PATTERN_INDEX.md +31 -31
  13. package/reference/autogen/packages/assistant-core.md +3 -3
  14. package/reference/autogen/packages/assistant-runtime.md +18 -3
  15. package/reference/autogen/packages/auth-provider-local-core.md +11 -4
  16. package/reference/autogen/packages/workspaces-core.md +7 -0
  17. package/reference/autogen/tooling/jskit-catalog.md +33 -0
  18. package/skills/jskit/SKILL.md +9 -4
  19. package/skills/jskit/references/package-with-nix.md +113 -0
  20. package/skills/jskit/references/pattern-index.md +31 -31
  21. package/skills/jskit/references/patterns/app/minimal-foundation/example/package.json +2 -2
  22. package/skills/jskit/references/patterns/app/shell-foundation/example/package.json +3 -3
  23. package/skills/jskit/references/patterns/auth/accounts-hub/example/package.json +1 -1
  24. package/skills/jskit/references/patterns/auth/oidc-sign-in/example/package.json +2 -2
  25. package/skills/jskit/references/patterns/realtime/realtime-application/example/package.json +2 -2
  26. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users/package.json +1 -1
  27. package/skills/jskit/references/patterns/users/user-administration-server/example/packages/users-workspace/package.json +2 -2
  28. package/skills/jskit/references/security-pass.md +131 -0
  29. package/skills/jskit/references/speed-pass.md +189 -0
  30. package/skills/jskit/references/ux-pass.md +111 -0
@@ -457,6 +457,97 @@ The supplied conversation routes open a conversation without a configuration,
457
457
  so the host notices a change where it opens the conversation for the person, or
458
458
  configures the person's open conversations when their profile changes.
459
459
 
460
+ ### Turn guard
461
+
462
+ An application can decide each new turn of the database-backed assistant before
463
+ anything is saved or sent, such as a topic check that answers off-topic
464
+ questions itself or a weekly message limit, by providing the optional
465
+ `assistant.turnGuard` capability from one of its features. Its `admit` returns
466
+ the decision for the person's message:
467
+
468
+ ```js
469
+ // src/server/MessageLimitFeature.js
470
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
471
+ import { createTurnGuard } from "./turnGuard.js";
472
+
473
+ const MessageLimitFeature = defineFeature({
474
+ id: "messages.limit",
475
+ requires: {
476
+ usage: "messages.usage"
477
+ },
478
+ provides: {
479
+ turnGuard: "assistant.turnGuard"
480
+ },
481
+ /** @param {{ usage: import("./types.js").MessageUsage }} capabilities */
482
+ setup({ usage }) {
483
+ return { turnGuard: createTurnGuard({ usage }) };
484
+ }
485
+ });
486
+
487
+ export { MessageLimitFeature };
488
+
489
+ // src/server/turnGuard.js
490
+ import { resolveActor } from "@jskit-ai/kernel/server/actions/actionContributorHelpers";
491
+ import { AppError } from "@jskit-ai/kernel/server/runtime";
492
+ import { isOnTopic } from "./topics.js";
493
+
494
+ /** @param {{ usage: import("./types.js").MessageUsage }} dependencies */
495
+ function createTurnGuard({ usage }) {
496
+ /** @param {{ targetSurfaceId: string, context: object, input: string, conversationId: string | null, messageId: string }} request */
497
+ async function admit({ context, input, messageId }) {
498
+ // Counted once per message ID: a resent message is not counted again.
499
+ const week = await usage.countMessage({ userId: resolveActor(context).id, messageId });
500
+ if (week.count > week.limit) {
501
+ throw new AppError(429, "You have used this week's messages.", {
502
+ code: "weekly_limit",
503
+ details: { resetsOn: week.resetsOn }
504
+ });
505
+ }
506
+ if (!isOnTopic(input)) return { reply: "I can only help with questions about your orders." };
507
+ return { allowed: true };
508
+ }
509
+
510
+ return Object.freeze({
511
+ admit
512
+ });
513
+ }
514
+
515
+ export { createTurnGuard };
516
+ ```
517
+
518
+ `admit({ targetSurfaceId, context, input, conversationId, messageId })`
519
+ receives the surface, the request context with its actor, the message's text,
520
+ the conversation it continues (`null` for a new one) and the message's ID. It
521
+ returns one of two decisions, or a promise of one:
522
+
523
+ - **`{ allowed: true }`** runs the turn as usual.
524
+ - **`{ reply }`** answers the turn with that text instead of the model. The
525
+ message and the reply are saved as one completed turn and streamed like any
526
+ other answer, so they appear in the conversation's history, are restored with
527
+ it and are part of what the model reads on later turns. The model is never
528
+ called, and the turn resolves no AI connection, so it works even while none
529
+ is configured. The turn saves the message's text; files attached to it are
530
+ not read or saved.
531
+ - **A thrown `AppError` refuses the turn** with its status, code and details,
532
+ as the route's error response, before any stream starts. Nothing is saved,
533
+ so the same message sent again is a new turn that `admit` decides again. The
534
+ example's limit answers 429 with code `weekly_limit` and `{ resetsOn }`.
535
+ - **Anything else is a programming error.** Another value, such as
536
+ `{ allowed: false }` or an empty reply, fails the turn with a 500, and the
537
+ server logs an error naming the value it returned.
538
+
539
+ Each new turn asks `admit` once, after its message ID is checked for a replay
540
+ and before the turn is claimed. A replayed message ID answers from its saved
541
+ turn and never calls `admit` again. Two simultaneous requests with the same new
542
+ message ID can both pass the replay check and both call `admit`; only one of
543
+ them then claims the turn, and the other answers as a replay of it. A guard that
544
+ counts messages therefore counts each `messageId` once, for example with a
545
+ unique key on it.
546
+
547
+ Without `assistant.turnGuard`, every turn runs as before. An application that
548
+ supplies its own `assistant.conversations` decides its turns where it sends
549
+ them, so `AssistantFeature` does not read `assistant.turnGuard` there.
550
+
460
551
  ### Database surface action tools
461
552
 
462
553
  The assistant reads automation-capable actions from `runtime.actions`. It keeps
@@ -735,7 +826,9 @@ Apply the package migrations before running the updated server. The runtime owns
735
826
  message-ID key. The database arbitrates concurrent requests across server
736
827
  processes before provider or tool execution. A reused ID with a different request
737
828
  returns a conflict. An identical retry replays the recorded answer or failure
738
- without calling the provider or tools again, including after a process restart.
829
+ without calling the provider or tools again, including after a process restart,
830
+ and without asking an application's turn guard again (see Turn guard above for
831
+ two simultaneous first sends).
739
832
  Pre-stream `AppError` failures retain their public code and details in the same
740
833
  request receipt. `ACTION_PERMISSION_DENIED` details remain private, and arbitrary
741
834
  non-`AppError` diagnostics are not added to the receipt. Older failure receipts
@@ -777,6 +870,11 @@ provider settings, authorization scope and action tools. Its adapter maps
777
870
  `streaming` to `inProgress`, `done` to `completed`, `error` to `failed`, and
778
871
  `canceled` to `interrupted`. Existing message IDs stay stable while text streams.
779
872
  Restored entries retain their database IDs; equal text is not a duplicate ID.
873
+ Each message's `storedId` is its saved row's ID: a restored message has it at
874
+ once, and a message sent in this view gets it when its turn completes (the
875
+ server's `done` event names the turn's two saved messages in
876
+ `storedMessageIds`). An unsaved message, such as a failed or stopped reply,
877
+ has `storedId: null`.
780
878
  Tool activity shows the existing tool name and status, never raw arguments or
781
879
  results. No provider reasoning is invented.
782
880
 
@@ -841,7 +939,22 @@ conversations are available through the Conversations dialog at every width.
841
939
  The current title remains visible. Activity opens the current tool-status list;
842
940
  setting `showToolActivity` to false hides presentation only. The
843
941
  `composer-tools` slot receives `{ runtime }` for application-owned supplementary
844
- controls. The element exposes `focus()` so a drawer owner can focus it once when
942
+ controls. The `message-actions` slot renders application-owned controls under
943
+ each assistant reply, after the reply's failed or stopped notice, and receives
944
+ `{ message }` with the reply's `id`, `storedId` and `role`:
945
+
946
+ ```vue
947
+ <AssistantSurfaceClientElement surface-id="home">
948
+ <template #message-actions="{ message }">
949
+ <v-btn v-if="message.storedId" size="small" variant="text" @click="report(message.storedId)">
950
+ {{ t("orders.assistant.report") }}
951
+ </v-btn>
952
+ </template>
953
+ </AssistantSurfaceClientElement>
954
+ ```
955
+
956
+ Act on `storedId`, which the server knows; `id` is the view's own identity for
957
+ the message. The element exposes `focus()` so a drawer owner can focus it once when
845
958
  opened and restore focus to the opener when closed.
846
959
 
847
960
  Page layout fills the viewport below its actual position, reserving the Vuetify
@@ -692,6 +692,22 @@ URL. Without a sender, production recovery is disabled; explicit development
692
692
  output remains available for local testing. A sender failure never falls back
693
693
  to development output. The generic recovery delivery capability is `email`.
694
694
 
695
+ The sender runs after the request has answered. Asking for a password reset
696
+ answers at once, and the same, whether or not the email has an account, so
697
+ neither the answer nor its time tells anyone which emails have accounts: local
698
+ auth looks the account up, makes its link and calls the sender only once the
699
+ request has answered. When the sender rejects, local auth logs the failure
700
+ with the address (never the link), and the person sees the same answer as for
701
+ any email; a delivery failure someone must act on belongs in the sender's own
702
+ monitoring, since an answer that reported it would say the account exists. A
703
+ stopping server waits up to 10 seconds for the emails still being sent. Asking
704
+ for a new confirmation link (`resendRegisterConfirmation`) and the
705
+ `auth.local.confirmation-sender` work the same way; a new registration's link
706
+ is still sent before its answer, which already says whether the email is
707
+ taken. A test that composes the library directly and reads the sent email
708
+ waits for it: it passes `deliveries: createLocalDeliveries({ logger })` to
709
+ `createLocalAuthService()` and awaits `deliveries.settled()`.
710
+
695
711
  Production is `NODE_ENV=production`; anything else, unset included, is
696
712
  development, so the host that serves the application sets it. A production
697
713
  server with `AUTH_LOCAL_RECOVERY_DEV_OUTPUT` set refuses to start and names the
@@ -0,0 +1,118 @@
1
+ <!-- Generated by `npm run agent-docs:build` from `packages/agent-docs/site/guide/app-setup/package-with-nix.md`. Do not edit manually. -->
2
+
3
+ ---
4
+ title: Package an App with Nix
5
+ description: Build a JSKIT app as one Nix package with no network access, for a host that runs apps only as Nix packages, without writing Nix.
6
+ ---
7
+
8
+ # Package an App with Nix
9
+
10
+ A host that runs apps only as Nix packages builds each one in Nix's sandbox,
11
+ with no network access, and runs nothing an app would install for itself.
12
+ JSKIT writes that packaging for every JSKIT app; nobody writes Nix for one.
13
+
14
+ ## Write package.nix
15
+
16
+ ```bash
17
+ npx jskit package nix
18
+ ```
19
+
20
+ It writes `package.nix` at the app's root. Commit it with the app. The file is
21
+ the same for every JSKIT app: it reads `package.json` and `package-lock.json`
22
+ while Nix evaluates it, so a changed lock file needs no change to it and there
23
+ is no hash to keep up to date. Each npm download is fetched by the integrity
24
+ hash `package-lock.json` gives it, as a fixed-output fetch, before the build;
25
+ the build itself has no network.
26
+
27
+ The command writes nothing, and says why, when:
28
+
29
+ - `package-lock.json` names a dependency a build cannot fetch by its hash: one
30
+ from git, a local file (`file:`), one with no integrity hash, or a link to a
31
+ folder outside the app. Publish such a package to a registry, or make it one
32
+ of the app's workspaces;
33
+ - `package.json` has no `name` or no `start` script;
34
+ - the app has no `package-lock.json`, or one npm 6 wrote (`lockfileVersion` 1);
35
+ - a `package.nix` it did not write is there. It never overwrites one.
36
+
37
+ Plain `jskit check`, and so the app's `npm run verify`, checks a `package.nix`
38
+ the command wrote: it must be the one the installed JSKIT writes
39
+ (`package/nix-current`: run the command again after `npm run jskit:update`),
40
+ and the app must still build with it (`package/nix-manifest`,
41
+ `package/nix-offline`). An app with no `package.nix`, or its own, is left
42
+ alone.
43
+
44
+ ## What the build does
45
+
46
+ `package.nix` is a function `{ pkgs }:` of the host's Nixpkgs that returns one
47
+ package:
48
+
49
+ 1. Node.js is the major version `engines.node` names first (`26.x` is
50
+ `pkgs.nodejs_26`), else Nixpkgs' default Node.js.
51
+ 2. The sources are the app's folder without `node_modules`, `.git`, and, at the
52
+ root, `dist`, `.jskit`, `coverage`, test results, `result` links and the
53
+ `.env` files (`.env.example` stays).
54
+ 3. npm installs `package-lock.json` (`npm ci`) offline, from a cache holding
55
+ exactly the tarballs Nix fetched, then runs the install scripts
56
+ (`npm rebuild`) as `npm ci` would: only those the root `package.json`'s
57
+ `allowScripts` approves, when npm asks for approval. A native addon compiles
58
+ there with node-gyp, against this Node's headers, with Python and a C
59
+ compiler from Nixpkgs. A prebuilt addon, inside its package or a package of
60
+ its own (a `-linux-x64` optional dependency), is a download like any other.
61
+ An install script that downloads something fails, as there is no network.
62
+ 4. `npm run build` runs when `package.json` has a `build` script (`vite build`
63
+ in a JSKIT app).
64
+ 5. The dev dependencies leave (`npm prune --omit=dev`), and the app's folder,
65
+ with `dist` and its production `node_modules`, becomes `lib/<name>` in the
66
+ package. Whatever the app runs while it runs must be a dependency, not a
67
+ devDependency: `db:migrate`'s `knex`, for one.
68
+
69
+ The package is named after `package.json`'s `name` without its scope, as a
70
+ program name (`@acme/shop_app` is `shop-app`), with its `version`. On a machine
71
+ with Nix:
72
+
73
+ ```bash
74
+ nix build --impure --expr 'import ./package.nix { pkgs = import <nixpkgs> { }; }'
75
+ ```
76
+
77
+ ## Its programs
78
+
79
+ The package's `bin/` holds the app's programs. Each takes `--env FILE`, a file
80
+ of environment variables in Node's `.env` format whose values win over the
81
+ environment's. The option is not called `--env-file` because Node reads an
82
+ `--env-file` anywhere on its command line, even after the script.
83
+
84
+ | Program | What it does |
85
+ | --- | --- |
86
+ | `<name> [--env FILE] [--migrate]` | Runs the app's `start` script as `npm start` would, without npm, in place of itself: from `lib/<name>`, with `node_modules/.bin` and Node first on `PATH`, and `NODE_ENV=production` unless the environment or the file says otherwise. With `--migrate`, runs `db:migrate` first and starts nothing when it fails. |
87
+ | `<name>-migrate [--env FILE]` | Runs the `db:migrate` script the same way. Only an app with one has it. |
88
+ | `<name>-check [--env FILE] [--wait SECONDS]` | Exits 0 once `GET /api/health` answers 200 on `HOST`:`PORT` (127.0.0.1 when `HOST` is unset or any address; port 3000 when `PORT` is unset), and 1 after `--wait` seconds (60). |
89
+ | `<name>-prepare --settings JSON --env FILE [--user NAME]` | Writes the settings, one JSON object of environment variables (each a string, a number or `true`/`false`), as `FILE`, mode 0600, owned by `NAME` (`chown NAME:`). It is for a host that hands an app's settings to a step run as root before its services start. |
90
+
91
+ ## Running it
92
+
93
+ - The app's folder is read-only. A JSKIT package that writes files keeps them
94
+ under the app's folder unless told otherwise, so point those at a writable
95
+ data folder in the settings: `JSKIT_STORAGE_FS_BASE_PATH` (uploads and
96
+ `runtime.storage`; `data/storage` by default) and `AUTH_LOCAL_STORE_DIR`
97
+ (local sign-in's files, such as the first account's setup code;
98
+ `.jskit/auth` by default).
99
+ - Secrets come at run time, in the env file or the service's environment,
100
+ never in the package: anyone who can read the Nix store can read a package.
101
+ - The server listens where its `server.js` says: in a JSKIT app, `HOST`
102
+ (0.0.0.0) and `PORT` (3000).
103
+ - The database comes from the app's own settings: `DATABASE_URL`, or
104
+ `DB_CLIENT`, `DB_HOST`, `DB_NAME` and the rest, as the
105
+ [database layer](/guide/app-setup/database-layer) guide says.
106
+ - Migrations run with `<name>-migrate` before the release starts, or with
107
+ `<name> --migrate` where the host has no such step. When several instances
108
+ start at once, Knex's migration lock lets one run them; the others fail and
109
+ start again once it is done, as a service restarted on failure does.
110
+
111
+ A host that runs apps as Nix packages typically runs the app `shop` as:
112
+
113
+ - a step run as root at each start, before the service:
114
+ `bin/shop-prepare --settings <the host's settings file> --env /run/shop/env --user shop`;
115
+ - one service, run as the user `shop`:
116
+ `bin/shop --env /run/shop/env --migrate`, on port 3000, healthy when
117
+ `/api/health` answers 200;
118
+ - a check after it starts: `bin/shop-check --env /run/shop/env`.
@@ -71,8 +71,10 @@ package, it refuses and names the import to use instead.
71
71
  and npm workspaces, and preflights every declared `@jskit-ai/*` package. It then
72
72
  updates all matching dependency, development-dependency, peer-dependency, and
73
73
  optional-dependency declarations as one validated manifest set. Non-JSKIT
74
- dependencies are unchanged. It installs once from the root and checks the new
75
- `package-lock.json` before succeeding.
74
+ dependencies are unchanged, except a direct `json-rest-api` pin, which moves to
75
+ the version JSKIT's packages require ([One json-rest-api](#one-json-rest-api)).
76
+ It installs once from the root and checks the new `package-lock.json` before
77
+ succeeding.
76
78
 
77
79
  During installation, the updater preserves non-JSKIT lockfile pins, removes the
78
80
  old JSKIT installation records from the candidate lock, and keeps the previous
@@ -176,6 +178,9 @@ The check fails when:
176
178
  - a JSKIT override tries to force a private graph;
177
179
  - a root/workspace declaration has no lockfile installation, or the lockfile is missing;
178
180
  - installed package versions or root/workspace declarations disagree with the lockfile.
181
+ - the app pins `json-rest-api` itself at another version than JSKIT's packages
182
+ require, or the lockfile installs more than one copy of it
183
+ ([One json-rest-api](#one-json-rest-api)).
179
184
  - a package script runs tests outside the machine's test budget (`test/*`, see
180
185
  [Test files run in parallel](/guide/framework/typed-features#test-files-run-in-parallel)).
181
186
  - an application package's manifest (`jskit.capabilities`) misses a capability
@@ -188,6 +193,20 @@ realtime runtime, and assistant runtime use exact peer dependencies where they
188
193
  must share application state. A partial upgrade can therefore fail during npm
189
194
  installation instead of silently nesting a second client stack.
190
195
 
196
+ ## One json-rest-api
197
+
198
+ `@jskit-ai/resource-runtime` and `@jskit-ai/crud-core` require `json-rest-api`
199
+ at one exact version, and json-rest-api knows its transactions by identity. An
200
+ app that also depends on `json-rest-api` at another version installs a second
201
+ copy, and every write its own `api.transaction` reaches inside JSKIT fails with
202
+ `RestApiWriteError: transaction must be an active transaction from
203
+ api.transaction; raw transactions and savepoints cannot own library writes`.
204
+ After an upgrade, or any change to the app's own `json-rest-api` declaration,
205
+ check that one copy is installed: `npm ls json-rest-api` shows one version, the
206
+ others marked deduped. `jskit check` refuses a direct pin at another version
207
+ and a second copy in the lockfile, naming the version to pin;
208
+ `npm run jskit:update` moves a direct pin with the catalog.
209
+
191
210
  ## Run tests within the test budget
192
211
 
193
212
  Plain `jskit check` fails a test run that ignores the machine's test budget
@@ -0,0 +1,136 @@
1
+ <!-- Generated by `npm run agent-docs:build` from `packages/agent-docs/site/guide/framework/security-pass.md`. Do not edit manually. -->
2
+
3
+ ---
4
+ title: Security pass
5
+ description: Where a JSKIT app decides who may do what, scopes rows to a workspace or a user, limits repeated requests, keeps sessions and secrets, and runs as production, and how to try each one.
6
+ ---
7
+
8
+ # Security pass
9
+
10
+ A security pass makes an app refuse what it should. Genesis's security pass
11
+ skill (`genesis-security-pass`) holds the method: map every way in, work
12
+ through authorization, sign-in, input, secrets, production settings and
13
+ dependencies, prove each finding by sending the input that breaks it, and keep
14
+ a test that fails without each fix. This page says where each of those lives in
15
+ a JSKIT app. The rules it applies are already in [Typed features](/guide/framework/typed-features),
16
+ [Data access](/guide/framework/data-access), [Authentication](/guide/app-setup/authentication),
17
+ [Workspace tenancy](/guide/app-setup/multi-homing) and the [sanity checks](/guide/framework/sanity-checks).
18
+
19
+ ## Who may call each route and action
20
+
21
+ - A route's `auth` is `"public"` unless it says otherwise, so a route
22
+ registered without `auth` answers anyone. List every `/api` route with its
23
+ `auth` (`"required"`, or `"own"` with `ownerParam` naming the route parameter
24
+ that must be the signed-in user's id) and its `permission`, and keep each
25
+ public route public on purpose.
26
+ - A workspace route registers under `/api/w/:workspaceSlug/...` with
27
+ `contextPolicy: "required"`: the server resolves the workspace and the
28
+ caller's membership from the slug and the session, and answers 404 or 403
29
+ before the handler runs
30
+ ([Workspace-scoped features and routes](/guide/app-setup/multi-homing#workspace-scoped-features-and-routes)).
31
+ - A surface's access policy guards pages in the browser only; the server reads
32
+ just `requireWorkspaceMembership: false` from it. A page hidden by
33
+ `requireAnyPermissions`, or a command whose `useCommand({ runPermissions })`
34
+ is false, still needs the route's own `auth` and `permission`.
35
+ - An action's `permission` is checked by the kernel before its input. A route
36
+ that bypasses actions, reading with `await request.callOptions()`, runs no
37
+ action permission, so its own `auth` and `permission` are its only gate
38
+ ([Layer 1](/guide/framework/data-access#layer-1-the-table-resource)).
39
+ An action on the `automation` channel is a tool the assistant may call as
40
+ the typing user.
41
+ - A rule that depends on the role reads `hasPermission(context.permissions, …)`,
42
+ never `includes()`, which misses `*` and `bookings.*` grants, and lists the
43
+ permission in `roleCatalog.customPermissions`
44
+ ([Role permissions](/guide/app-setup/multi-homing#role-permissions)).
45
+
46
+ ## Rows stay in their workspace
47
+
48
+ - A table resource's `ownership` (`workspace`, `user`, `workspace_user`,
49
+ `workspace_or_shared`, `system` or `public`) and its row policy scope every
50
+ handle call to the call's `options.context`, and only the owner feature
51
+ reaches the table ([The resource is the only door](/guide/framework/data-access#the-resource-is-the-only-door)).
52
+ Knex past the handle, a repository that drops the call's `options`, or a
53
+ context built by hand skips that scope: search for each. Confirm every
54
+ `public` table is meant to be read by anyone.
55
+ - Who acts is `resolveActor(context)`; the workspace comes from the context
56
+ only, never from the body or another input
57
+ ([Request context](/guide/framework/typed-features#request-context)). A row
58
+ policy decides from `caller` and the server-resolved `context.workspace`,
59
+ `context.membership` and `context.permissions`, never from request input.
60
+ - Jobs declare `systemScope` and narrow `systemContext(reason)` with
61
+ `forWorkspace`, `forUser` or `forWorkspaceUser`; work done as one member runs
62
+ in `workspaces.memberContext(…)`, which refuses a removed member as their
63
+ request would ([Background work](/guide/framework/data-access#background-work)).
64
+ - `expectScoped()` from `@jskit-ai/resource-runtime/test` runs a path as owner
65
+ A before and after seeding owner B, and fails when B's rows change A's answer
66
+ or B's rows change ([Tests](/guide/framework/data-access#tests)). Give each
67
+ workspace path one.
68
+
69
+ ## Sign-in, sessions and limits
70
+
71
+ - Auth's routes are limited per client address, and local auth makes an
72
+ account wait after repeated failures; both are on by default.
73
+ `config.auth.rateLimits` changes a limit and `false` removes one: a removed
74
+ limit is a finding unless the person chose it. Behind a proxy,
75
+ `TRUSTED_PROXIES` names it, or every client shares one count
76
+ ([Sign-in protection](/guide/app-setup/authentication#sign-in-protection)).
77
+ - Any other route that repetition can abuse (sending email or codes,
78
+ invitations, costly reads, calls to a paid service) declares
79
+ `rateLimit: { max, timeWindow }`, refused with 429 `kernel.http.rateLimited`.
80
+ Each limit gets a test expecting the 429.
81
+ - Sign-in cookies are httpOnly, and in production `Secure` with the `__Host-`
82
+ prefix; `AUTH_COOKIE_SAME_SITE` is `lax` or `strict`
83
+ ([Sign-in cookies and SameSite](/guide/app-setup/authentication#sign-in-cookies-and-samesite)).
84
+ Every unsafe `/api` method checks its CSRF token unless the route sets
85
+ `csrfProtection: false`; each route that does must authenticate its request
86
+ another way, as the pass sign-in route does with its signed pass.
87
+ - A dangerous action asks for a recent second factor with `secondFactor`
88
+ where the app uses one, and password-only sign-in sets
89
+ `AUTH_LOCAL_PASSWORD_MIN_LENGTH=15`
90
+ ([Second factor](/guide/app-setup/authentication#second-factor-local-auth)).
91
+ - Password recovery and a new confirmation link answer the same whether or not
92
+ an account exists. Give the app's own invitation, lookup and sign-up routes
93
+ the same answer.
94
+
95
+ ## Production settings and secrets
96
+
97
+ - `NODE_ENV=production`, set by the Deployment's Serve step, is JSKIT's only
98
+ production switch. There local auth requires `AUTH_LOCAL_SESSION_SECRET`,
99
+ refuses `AUTH_DEV_BYPASS_ENABLED` and `AUTH_LOCAL_RECOVERY_DEV_OUTPUT`, and
100
+ refuses to start without a confirmation sender while anyone may register
101
+ ([Production settings](/guide/framework/sanity-checks#production-settings)).
102
+ - On an empty production database the first account needs the setup code
103
+ (403 `auth.local.setup.codeRequired`), so whoever reaches a new deployment
104
+ first cannot own it. A registration or admin bootstrap of the app's own
105
+ needs the same protection
106
+ ([The first account in production](/guide/app-setup/authentication#the-first-account-in-production-local-auth)).
107
+ - `AUTH_LOCAL_SESSION_SECRET` and every other secret live in private Env, read
108
+ on the server, and the Deployment generates the session secret. Nothing
109
+ secret goes in `config/public.js`, which the browser imports, or in a
110
+ committed `.env` file or example.
111
+ - An internal failure is a plain `Error`, which the caller sees as "Internal
112
+ server error."; an `AppError`'s message is shown at any status, so it never
113
+ carries internals
114
+ ([Internal failures are plain errors](/guide/framework/typed-features#internal-failures-are-plain-errors)).
115
+ - `config.securityHeaders` sets the security headers. Production adds
116
+ transport security, framing protection and a content security policy that is
117
+ reported, not enforced, by default; enforce it once the pages run without
118
+ violations, and read the headers on a production build
119
+ ([Security headers](/guide/app-setup/initial-scaffolding#security-headers)).
120
+
121
+ ## Try each refusal
122
+
123
+ - Boot the server in a route test and sign each person in over `app.inject`,
124
+ one cookie jar each, sending the session's `csrfToken` as `csrf-token` with
125
+ every write ([Tests](/guide/framework/data-access#tests)).
126
+ - Send each attack and expect its refusal: no session (401
127
+ `auth.session.required`), a member without the route's permission (403), a
128
+ slug of a workspace the caller is not in (403), another workspace's record id
129
+ and `workspaceId` in the body (refused, or answered in the caller's own
130
+ workspace), a write without `csrf-token`, and one request past each
131
+ `rateLimit` (429). A body that does not validate, sent without a session,
132
+ must get the refusal, not field errors.
133
+ - Production settings: start the server with `NODE_ENV=production` and the
134
+ test database, and check that it stops without `AUTH_LOCAL_SESSION_SECRET`,
135
+ that registering asks for the setup code, and the response headers.
136
+ - Run `npm audit` and `npm run verify`.
@@ -0,0 +1,194 @@
1
+ <!-- Generated by `npm run agent-docs:build` from `packages/agent-docs/site/guide/framework/speed-pass.md`. Do not edit manually. -->
2
+
3
+ ---
4
+ title: Speed pass
5
+ description: Where a JSKIT app's tests, screens and server spend their time, the JSKIT tools that measure each wait, and the fixes each one takes.
6
+ ---
7
+
8
+ # Speed pass
9
+
10
+ A speed pass makes an app and its tests take the time their work needs.
11
+ Genesis's speed pass skill (`genesis-speed-pass`) holds the method: measure
12
+ each wait first on a realistic build at realistic sizes, fix its cause, measure
13
+ again the same way, and never raise a time limit, add retries, or shrink
14
+ realistic data or coverage to get faster. This page says where each wait lives
15
+ in a JSKIT app and which JSKIT tools measure and fix it. The rules it applies
16
+ are already in [Typed features](/guide/framework/typed-features),
17
+ [Client features](/guide/framework/client-features),
18
+ [Data access](/guide/framework/data-access) and the
19
+ [sanity checks](/guide/framework/sanity-checks). Query counts, narrowing and
20
+ indexes belong to the [data pass](/guide/framework/data-pass): when a wait is
21
+ database time, apply that page to the path.
22
+
23
+ ## Test speed
24
+
25
+ ### Measure
26
+
27
+ - `jskit test` starts by saying how many test files it runs at a time and
28
+ where that number came from (`V64_TEST_CONCURRENCY`, or half of the
29
+ machine), and ends with its 10 slowest test files and tests; each file's time
30
+ is kept in `node_modules/.cache/jskit-test/file-times.json`. Time the whole
31
+ command too (`time npm test`): a wall time close to the sum of the files'
32
+ times means they ran one after another
33
+ ([Test files run in parallel](/guide/framework/typed-features#test-files-run-in-parallel)).
34
+ - Test database preparation reports each phase and its duration
35
+ ([Test databases are prepared once](/guide/framework/typed-features#test-databases-are-prepared-once)).
36
+ Read them: slow preparation otherwise hides inside the first test that waits
37
+ for it.
38
+ - Every Playwright run through `browserTestConfig()` ends with its 10 slowest
39
+ tests. Compare a slow spec's time with the time of the app's requests it
40
+ makes, so you know whether the test or the app is slow.
41
+
42
+ ### Fix
43
+
44
+ - Scripts run `jskit test` (`jskit test --databases` for database tests), and
45
+ Playwright and Vitest take their workers from `testConcurrency()`. `jskit
46
+ check` reports a script that runs `node --test` directly, passes a fixed
47
+ concurrency or pins `V64_TEST_CONCURRENCY`, and a Playwright or Vitest config
48
+ that runs files one at a time ([test-run rules](/guide/framework/typed-features#test-run-rules)).
49
+ - Files that collide are isolated, never run one at a time: a port from
50
+ `listen(0)`, a directory from `mkdtemp`, the database `jskit test --databases`
51
+ gives each file, and a Vite `cacheDir` of its own. The
52
+ `// jskit-test: alone - <reason>` marker is only for a file that holds a
53
+ resource of the whole machine.
54
+ - `jskit test --databases` restores each file's database from a snapshot
55
+ rebuilt only when the migrations' digest changes. A file that runs
56
+ `knex.migrate.latest()` itself replays the whole history for every file:
57
+ remove it, and let the full history run once in its own check.
58
+ - A fixture every file only reads (a built app, a composed project, a
59
+ generated tree) is made once, before any file starts, by a global setup
60
+ module: `jskit test --test-global-setup=tests/helpers/globalSetup.js`
61
+ (`jskit test` passes its arguments to `node --test`). Its `globalSetup()`
62
+ makes the fixture and puts its location in an environment variable the test
63
+ processes inherit; its `globalTeardown()` removes it. A file run on its own
64
+ makes the fixture itself when the variable is absent, and a test that writes
65
+ into the fixture makes its own copy.
66
+ - `browserTestConfig()` builds the production frontend once and gives each
67
+ worker its own server, port and seeded database; with a `signIn` module
68
+ each worker signs in once. A check of what a component shows belongs in a
69
+ Vitest component test, and a new browser check is an assertion in the spec
70
+ that already reaches that screen.
71
+ - Wait for the condition, never for time: Playwright's web-first assertions
72
+ (`await expect(locator).toBeVisible()`, `await expect(page).toHaveURL(...)`)
73
+ instead of `page.waitForTimeout()`. The app's own delays (retry backoff,
74
+ debounce, polling) run on a fake clock: `mock.timers` in `node:test`,
75
+ `vi.useFakeTimers()` in Vitest and `page.clock` in Playwright.
76
+ - A file imports what it needs at its top level, so loading counts against the
77
+ file, not against a test's time limit. `jskit test` keeps Node's compile
78
+ cache in `node_modules/.cache/jskit-node-compile-cache`, so each file's
79
+ process loads the modules the files before it compiled.
80
+ - The bounds stay: `jskit test`'s 10 minutes a file and 45 a run,
81
+ `browserTestConfig()`'s `actionTimeout` (15 s), `navigationTimeout` (30 s)
82
+ and `globalTimeout`. A bound in `test-time-bounds.json` rises only with a
83
+ measurement of the work's real need; a file that got slow is fixed instead.
84
+
85
+ ### Prove
86
+
87
+ Run the whole suite before and after on the same machine with the same
88
+ `V64_TEST_CONCURRENCY`, and report the wall time, each preparation phase, the
89
+ slowest files and the test counts, which stay the same.
90
+
91
+ ## Client speed
92
+
93
+ ### Measure
94
+
95
+ - Build with `npm run build` and read Vite's report: every chunk with its
96
+ size and its gzip size. `dist/index.html` names the entry script and the
97
+ chunks it preloads (`<link rel="modulepreload">`): together they are the
98
+ JavaScript every page loads before it shows anything. Vite's warning about
99
+ a chunk over 500 kB is a finding to follow to its import, never a limit to
100
+ raise with `build.chunkSizeWarningLimit`.
101
+ - Serve that build and open each main screen with a cold cache. In a
102
+ Playwright spec, `page.on("request", ...)` counts the `/api` requests a
103
+ screen or an action makes; look for the same request twice, one request per
104
+ row, and requests made on a timer.
105
+
106
+ ### Fix
107
+
108
+ - **Screens load with their routes.** A page under `src/pages` loads as its
109
+ own chunk when its route is first visited. A library one page uses is
110
+ imported by that page or a component it shows, never by `src/main.js`, a
111
+ client provider or a layout every page renders. A heavy component that a
112
+ page shows only sometimes loads with
113
+ `defineAsyncComponent(() => import("./HeavyChart.vue"))`.
114
+ - **Packages keep their screens out of every page.** Each client provider is
115
+ exported by a subpath of its own, and its file imports only what every page
116
+ needs ([Provider subpaths](/guide/framework/client-features#provider-subpaths)).
117
+ A provider without one, or a `./client` that declares `routeComponents` or
118
+ `clientRoutes` or uses `export *`, brings all of `./client` to every page.
119
+ On the accounts starter, loading users-web's provider through its subpath
120
+ instead of all of its `./client` took the JavaScript a page loads before it
121
+ starts from 1,302 KB to 778 KB.
122
+ - **One request for related records.** A list shows its related records with
123
+ `include` and the including contract's `includeFields`, in the same request,
124
+ never with a request per row; `fields[<type>]` narrows what an included
125
+ record carries ([Layer 2: the CRUD surface](/guide/framework/data-access#layer-2-the-crud-surface)).
126
+ A picker reads its selected values past the loaded page by id, all in one
127
+ request (`filter[id]`, which `useCrudListFilterLookups()` sends for a lookup
128
+ filter), and searches on the server with `q`
129
+ ([Wire list search with the initial resource](/guide/framework/crud-operations#wire-list-search-with-the-initial-resource),
130
+ [Search on the server](/guide/framework/client-features#search-on-the-server)).
131
+ - **One read for the same data.** Read through http-web's composables
132
+ (`useList`, `useView` and the CRUD screens), which keep each read under its
133
+ query key, so components showing the same list with the same parameters
134
+ share one request, instead of a `fetch` of their own in each component.
135
+ - **Events, not polling.** A list or record refreshes on the realtime events
136
+ that change it: a read composable's `realtime` option or
137
+ `useRealtimeQueryInvalidation()` marks the matching reads stale and reads
138
+ again only those a mounted screen uses, at most twice a query for a burst of
139
+ events
140
+ ([Realtime](/guide/app-extras/realtime#event-contract)). A `setInterval`
141
+ that refetches is a finding.
142
+ - **Render what is visible.** A long list reads pages and renders with pages
143
+ or `v-virtual-scroll`
144
+ ([Screens](/guide/framework/sanity-checks#screens)).
145
+
146
+ ### Prove
147
+
148
+ Report the entry chunk and its preloads (gzip) from the build before and
149
+ after, the requests each main screen and action makes, and the main actions'
150
+ time from click to result on the production build, cold and warm. Keep a
151
+ request count in the spec that reaches the screen, as a count, never as a
152
+ time.
153
+
154
+ ## Server speed
155
+
156
+ ### Measure
157
+
158
+ - Boot the server in a test as [Tests](/guide/framework/data-access#tests)
159
+ shows, seed a realistic size in `TEST_DB_NAME`, and time the main routes
160
+ over `app.inject`, the first request after boot and later ones.
161
+ `countQueries(knex, work)`, or `countRuntimeQueries(work)` for a booted
162
+ server, from `@jskit-ai/database-runtime/server/testDatabases`, gives the
163
+ statements, so you can tell database time from the rest.
164
+ - Start the server with `node --cpu-prof` to see where a slow route or a slow
165
+ start spends its computing time, in the `.cpuprofile` file it writes.
166
+ - After the app has been idle, list the server's child processes, timers and
167
+ connections, and the jobs still running.
168
+
169
+ ### Fix
170
+
171
+ - **Do once what does not change.** A feature builds what does not change
172
+ between requests (a parsed configuration, a compiled schema, a client for an
173
+ outside service) in `setup()` and starts it in `boot()`, never per request
174
+ ([Owned state](/guide/framework/typed-features#owned-state)).
175
+ - **Nothing runs without real use.** A process, worker or timer a feature
176
+ starts has its owner stop it in `shutdown()`
177
+ ([Shutdown mirrors setup](/guide/framework/typed-features#shutdown-mirrors-setup)),
178
+ and one that serves only some requests starts on its first real use and
179
+ stops when idle. A periodic job's timer is `unref()`ed.
180
+ - **Work nobody waits for leaves the request.** Work over many rows or every
181
+ workspace runs as a background job with `systemScope`
182
+ ([Background work](/guide/framework/data-access#background-work)).
183
+ - **Database time is the data pass's.** A count that grows with the rows, a
184
+ read narrowed in code, a write that reads its row back with
185
+ `returning: "record"` when it does not use it, and a missing index are
186
+ fixed as the [data pass](/guide/framework/data-pass) says.
187
+
188
+ ### Prove
189
+
190
+ Report each main route's time before and after, with its statement count, at
191
+ the realistic size, the first after boot and later ones. Keep an
192
+ `expectFlatQueries()` test for each path whose count you changed.
193
+
194
+ Then run `npx jskit check` and `npm run verify`.