@ultimat3/testing 30.6.0 → 30.8.0

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 (42) hide show
  1. package/CLAUDE.md +3 -3
  2. package/README.md +1 -1
  3. package/package.json +17 -17
  4. package/src/define-exercise.ts +53 -17
  5. package/src/drill-writes.ts +3 -1
  6. package/src/errors.ts +9 -90
  7. package/src/exercise-actor-user.ts +63 -0
  8. package/src/exercise-actor.ts +64 -11
  9. package/src/exercise-crash.ts +7 -3
  10. package/src/exercise-drift-hint.ts +28 -0
  11. package/src/exercise-input.ts +3 -0
  12. package/src/exercise-job-tenant.ts +10 -5
  13. package/src/exercise-judge.ts +78 -0
  14. package/src/exercise-observed.ts +93 -0
  15. package/src/exercise-override-input.ts +56 -6
  16. package/src/exercise-report.ts +43 -2
  17. package/src/exercise-request.ts +7 -24
  18. package/src/exercise-setup.ts +34 -17
  19. package/src/exercise-subjects.ts +20 -5
  20. package/src/exercise-sweeps.ts +57 -12
  21. package/src/exercise.ts +141 -109
  22. package/src/fixture-island.ts +1 -1
  23. package/src/index.ts +4 -0
  24. package/src/island-errors.ts +82 -0
  25. package/src/job-crash-points.ts +36 -0
  26. package/src/job-crash-proof.ts +23 -6
  27. package/src/job-sim-errors.ts +24 -0
  28. package/src/plan-conditions.ts +106 -0
  29. package/src/plan-oracle.ts +93 -57
  30. package/src/plan-probes.ts +94 -0
  31. package/src/plan-sort-key.ts +65 -0
  32. package/src/plan-sweep-fix.ts +99 -22
  33. package/src/plan-sweep-report.ts +48 -4
  34. package/src/scale-sweep-graph.ts +3 -0
  35. package/src/scale-sweep-run.ts +14 -7
  36. package/src/seed-graph-plan.ts +11 -0
  37. package/src/seed-graph-values.ts +20 -11
  38. package/src/seed-graph.ts +39 -3
  39. package/src/subject-proof.ts +12 -2
  40. package/src/tenant-proof-report.ts +84 -25
  41. package/src/tenant-proof.ts +39 -6
  42. package/src/seed-pattern-sample.ts +0 -216
package/CLAUDE.md CHANGED
@@ -45,19 +45,19 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
45
45
  | `LOG_LEVEL` above `info` filters the TERMINAL | `quiet-logs.ts` pins the logger at `info` while core loads, so a collecting `setLogSink` still sees `warn` under `LOG_LEVEL=error`. It stays the preload's FIRST import |
46
46
  | Injection | `SqlRunner` and `connect` are parameters, so unit tests need no server |
47
47
  | Fixtures | the preload registers the framework bag — an app registers only what it alone knows (`seed`, `actorFor`) |
48
- | Every `e2eTest` is audited | `e2e-a11y.ts` (rules), `e2e-a11y-run.ts` (per-test run, `allow`, dedupe), `ax-node.ts` (the one AX reader); the full tree is read only in `cdp-e2e-page.ts` (`FULL_AX_TREE`, a convention). No switch; `allow` needs a non-blank `because`. And every raw tab: `e2e-a11y-tabs.ts`, checked after each `goto`/`reload` and at the test's end from the preload's `afterEach`; exceptions are `allowA11y([{ role, selector, because }])` |
48
+ | Every `e2eTest` is audited | `e2e-a11y.ts` (rules), `e2e-a11y-run.ts` (per-test run, `allow`, dedupe), `ax-node.ts` (the one AX reader); full tree only in `cdp-e2e-page.ts`. No switch; `allow` needs a `because`. Raw tabs: `e2e-a11y-tabs.ts` ([history](../../docs/history/testing.md#a11y-on-raw-tabs)) |
49
49
  | The exercise pass runs what is registered | `exercise.ts` (`runExercisePass`): every action, query and job once, its own tenant pair off one `seedGraph`, an actor `exercise-actor.ts` picks, 39's `runExercise` as the verdict. Rows COMMITTED. Overrides only via `defineExercise` (blank `off` refused). A job runs ALONE (`exercise-job-run.ts`): a fresh queue, one `tick()`, what it queued left on the caller's queue unrun — never a `drain()` |
50
50
  | An override `input` is awaited, as the call's actor | `exercise-override-input.ts`: run inside the call's own request, so `useContext().actor` is the seated actor; the one way to a signed input. `async` ones are left out of `x drill`'s load |
51
51
  | A passkey test signs for real | `softAuthenticator` is `@ultimat3/auth/soft-authenticator`'s, never re-exported here (one value, one path: `flight-copies`) and never a second one (auth's own suites need it, and auth cannot import testing) |
52
52
  | A reached job is crash-proven | `exercise-crash.ts`: `crashProof` with the control's input and actor, after the tenant proof; only `diverged` is red (`X_JOB_CRASH_DIVERGED`), its place `crashEffectPlace` (`inside` a step via jobs' `currentStep()`, or `after` one). Its world is `alone`: only the job's own row is claimed, a child is an `enqueue:` effect, never run. Committed: job bodies escape transactions |
53
53
  | The tenant proof is taint only | `tenant-proof.ts`: B, A, B; B is A's role minus `tenancy:cross`. Leak = seeded canary or unhanded id (`tenant-canary.ts`); write = moved digest. Only `crossed` is red |
54
- | Every statement the pass sent is planned | `plan-sweep.ts` (`sweepPlans`): first relation an app table, `PREPARE` in a READ-ONLY transaction with seq/bitmap scans and sorts off, judged by `plan-oracle.ts`; red = `X_QUERY_UNINDEXED` / `X_QUERY_SORT_UNSERVED` with the `indexes:` entry (`plan-sweep-fix.ts`). `scan:` or `expectedSeqScan` is exempt, listed; credited: a partial unique whose predicate the statement states (one row), a declared equality-then-range index under a limit; no generic plan is `X_QUERY_PLAN_UNAVAILABLE`, never a pass |
54
+ | Every statement the pass sent is planned | `plan-sweep.ts` (`sweepPlans`): first relation an app table, `PREPARE` in a READ-ONLY transaction with seq/bitmap scans and sorts off, judged by `plan-oracle.ts` (keys: `plan-sort-key.ts`, conditions: `plan-conditions.ts`); red = `X_QUERY_UNINDEXED` / `X_QUERY_SORT_UNSERVED` with the `indexes:` entry (`plan-sweep-fix.ts`). `scan:` or `expectedSeqScan` is exempt, listed; credited: a partial unique whose predicate the statement states, equality-then-range index under a limit, every `or` arm a declared index leads, a whole read a keyed join side probes by a declared index (`plan-probes.ts`); no generic plan is `X_QUERY_PLAN_UNAVAILABLE`, never a pass |
55
55
  | A shape that grows with the rows is red | `scale-sweep-run.ts`: two more tenants at `SCALE_SIZES` (2, 8 rows a table), every reached primitive once in each; `judgeScale` (pure) reds `X_QUERY_SCALES_WITH_ROWS`. Under `expectedQueryLoop` it is listed with its reason |
56
56
  | An erase is PROVED, not asserted | `subject-proof.ts` (`subjectProof`, run by cli's `exercise-subject.ts`): canaries in every table, one person erased, every stored row searched; a survivor outside `retain` is `X_SUBJECT_ERASE_INCOMPLETE`, naming table and column, never the value |
57
57
  | A captured failure replays as a test | `repro.ts`: `reproduce(bundle, { driver })` seeds the rows it read, freezes the clock at its instant, invokes as its actor; masked fields are stood in (`repro-stand-in.ts`). An unregistered name ANSWERS as the failure. `reproJob(runJobs, failure)` for a dead job. What `x repro --write` emits |
58
58
  | A vendor's answers are a cassette | `cassette.ts`: replay = one `mockFetch` route per recorded URL, seal kept (`X_CASSETTE_MISSING`, `X_CASSETTE_UNUSED`). Record = `ULTIMATE_CASSETTE=record` + `record.hosts`, refused under `CI` (`X_CASSETTE_RECORD_REFUSED`), headers allow-listed, credential keys masked, bytes scanned before disk (`X_CASSETTE_SECRET`). The request side is never written |
59
59
  | One seed writer | `entitySeedWriter({ entities, client \| driver })` (`seed-writer.ts`) writes through each entity's own repository; `snapshot` is required; `entity` loads on the first write, so the barrel stays entity-free |
60
- | Factory values are DECLARED | `factoriesFor` and `seedGraph` share `seed-graph-values.ts`: default, enum, kind, a `matches()` pattern (`seed-pattern-sample.ts`, read off the CHECK by `seed-graph-patterns.ts`), `$meta.schema` (sampler `require`d on first use), through `$parse`, never the name. `seed-graph*.ts` type-import `entity` only |
60
+ | Factory values are DECLARED | `factoriesFor` and `seedGraph` share `seed-graph-values.ts`: default, enum, kind, a `matches()` pattern (schema's `patternSamples`; CHECK read by `seed-graph-patterns.ts`), `$meta.schema` (sampler `require`d on first use), through `$parse`, never the name. `seed-graph*.ts` type-import `entity` only |
61
61
  | e2e without a driver | `e2eTest` becomes `test.skip`; the gate reports the step SKIPPED (or `X_VERIFY_SUITE_VANISHED` when `x.verify.json` requires it), never passed |
62
62
  | The seam has an inverse | `resetE2eDriver()`: `useE2eDriver` writes MODULE scope, so a file that installs a browser undoes it |
63
63
  | Built vs declared | `clock` `mail` `network` `runJobs` `statements` `subscribe` are built in-process; `page` `budget` `signIn` `deploy` are declared and wait for a driver (`X_TEST_FIXTURE_UNAVAILABLE`). |
package/README.md CHANGED
@@ -26,7 +26,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
26
26
  | `sealed-sockets.ts` | the `WebSocket` and `Bun.connect` patches, behind `sealed-network.ts`'s one gate |
27
27
  | `factories.ts` | `defineFactory` — seeded rows, traits, associations, `build` vs `create` |
28
28
  | `factory-registry.ts` | `factoriesFor(registry)` — one factory per entity, each value read off its column's declaration (default, enum, kind, money, nullability) through `$parse`, never off its name |
29
- | `seed-graph.ts` | `seedGraph(entities, { tenants, perTable, seed, factories })` — rows for every table with no factory written: parents first, same-tenant keys, every declared rule kept. Pure, same seed same bytes |
29
+ | `seed-graph.ts` | `seedGraph(entities, { tenants, perTable, seed, factories, beside })` — rows for every table with no factory written: parents first, same-tenant keys, every declared rule kept. Pure, same seed same bytes |
30
30
  | `repro.ts` | `reproduce(bundle, { driver })` and `reproJob(runJobs, failure)` — what a test `x repro --write` generated calls: captured reads seeded, clock frozen at the failure, the same actor and input (masked fields stood in from the schema); a dead job's completed steps replayed from storage |
31
31
  | `seed-graph-plan.ts` | the plan's types and `insertSeedGraph(graph, writer)` — every insert, then every deferred key, sequentially |
32
32
  | `seed-graph-values.ts` | one column's candidate values, off its declaration, kept only where `$parse` accepts them — `factoriesFor`'s source too |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "30.6.0",
3
+ "version": "30.8.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -46,21 +46,21 @@
46
46
  "test": "bun test"
47
47
  },
48
48
  "dependencies": {
49
- "@ultimat3/action": "30.6.0",
50
- "@ultimat3/cache": "30.6.0",
51
- "@ultimat3/core": "30.6.0",
52
- "@ultimat3/db": "30.6.0",
53
- "@ultimat3/entity": "30.6.0",
54
- "@ultimat3/http": "30.6.0",
55
- "@ultimat3/i18n": "30.6.0",
56
- "@ultimat3/jobs": "30.6.0",
57
- "@ultimat3/mail": "30.6.0",
58
- "@ultimat3/policy": "30.6.0",
59
- "@ultimat3/pwa": "30.6.0",
60
- "@ultimat3/query": "30.6.0",
61
- "@ultimat3/realtime": "30.6.0",
62
- "@ultimat3/render": "30.6.0",
63
- "@ultimat3/schema": "30.6.0",
64
- "@ultimat3/time": "30.6.0"
49
+ "@ultimat3/action": "30.8.0",
50
+ "@ultimat3/cache": "30.8.0",
51
+ "@ultimat3/core": "30.8.0",
52
+ "@ultimat3/db": "30.8.0",
53
+ "@ultimat3/entity": "30.8.0",
54
+ "@ultimat3/http": "30.8.0",
55
+ "@ultimat3/i18n": "30.8.0",
56
+ "@ultimat3/jobs": "30.8.0",
57
+ "@ultimat3/mail": "30.8.0",
58
+ "@ultimat3/policy": "30.8.0",
59
+ "@ultimat3/pwa": "30.8.0",
60
+ "@ultimat3/query": "30.8.0",
61
+ "@ultimat3/realtime": "30.8.0",
62
+ "@ultimat3/render": "30.8.0",
63
+ "@ultimat3/schema": "30.8.0",
64
+ "@ultimat3/time": "30.8.0"
65
65
  }
66
66
  }
@@ -1,7 +1,7 @@
1
- // `defineExercise({ publishPost: { input, actor }, sendInvoice: { off: 'why' } })`: an app's
2
- // overrides for the exercise pass, one entry per primitive. Each value IS 39's `.contract({
3
- // exercise })` option, re-exported rather than restated, so one shape answers both questions.
4
- // A blank `off` is refused here, at declaration; an unknown name when the pass runs.
1
+ // `defineExercise({ publishPost: { input, actor }, sendInvoice: { off: 'why' } })`: an app's ONE
2
+ // declaration of each primitive's exercise, read by `x exercise` and every `.contract({ exercise })`.
3
+ // A blank `off` is refused at declaration, an unknown name when the pass runs. A key is a bare name
4
+ // or a kind-qualified one (`'job:eraseAccount'`), which wins over the bare name for its kind.
5
5
 
6
6
  import type { ExerciseOptions } from '@ultimat3/action';
7
7
  import { renderCauseValue, renderFixLiteral, UltimateError } from '@ultimat3/core';
@@ -11,16 +11,39 @@ import type { SeedFactory } from './seed-graph-plan';
11
11
  /** 39's option type, exactly: `{ actor, input?, runs? }` or `{ off: '<reason>' }`. */
12
12
  export type ExerciseOverride = ExerciseOptions;
13
13
 
14
- /** What `defineExercise` returns: the overrides, by primitive name. Read by `runExercisePass`. */
14
+ /**
15
+ * What `defineExercise` returns: the overrides, by primitive name. Read by `runExercisePass` and,
16
+ * structurally, by `.contract({ exercise })` (`define-exercise.test.ts` pins the assignability).
17
+ */
15
18
  export interface ExerciseOverrides {
16
19
  readonly kind: 'exercise-overrides';
17
20
  readonly entries: ReadonlyMap<string, ExerciseOverride>;
18
21
  /** The entity an actor is a row of, by name: its id is bound to a seeded row. */
19
22
  readonly actorEntity?: string;
23
+ /** The column of that entity whose value IS the actor's id (`memberships.userId`); else its key. */
24
+ readonly actorColumn?: string;
20
25
  /** By entity name: the pass's graph builds those rows with them (`seedGraph`'s `factories`). */
21
26
  readonly factories?: Readonly<Record<string, SeedFactory>>;
22
- /** The app's hook, run once inside the pass's sealed room (`exercise-setup.ts`). */
23
- readonly setup?: ExerciseSetup;
27
+ /** The app's hooks, run once each, in order, inside the pass's sealed room (`exercise-setup.ts`). */
28
+ readonly setup?: ExerciseSetup | readonly ExerciseSetup[];
29
+ }
30
+
31
+ /** The three kinds an entry may be qualified by. */
32
+ export type ExerciseKind = 'action' | 'query' | 'job';
33
+
34
+ /** `'job:eraseAccount'`: the key that names one kind's primitive when another shares its name. */
35
+ export const exerciseEntryKey = (kind: ExerciseKind, name: string): string => `${kind}:${name}`;
36
+
37
+ /**
38
+ * The entry `kind` `name` runs with: its qualified key's, else its bare name's. An action and a job
39
+ * sharing a name each read their own — the bare key alone fed one's input to the other.
40
+ */
41
+ export function overrideFor(
42
+ overrides: ExerciseOverrides | undefined,
43
+ kind: ExerciseKind,
44
+ name: string,
45
+ ): ExerciseOverride | undefined {
46
+ return overrides?.entries.get(exerciseEntryKey(kind, name)) ?? overrides?.entries.get(name);
24
47
  }
25
48
 
26
49
  /** What the whole pass needs to know of the app, beside the per-primitive entries. */
@@ -28,9 +51,12 @@ export interface ExerciseAppOptions {
28
51
  /**
29
52
  * The entity whose rows ARE the app's actors (`members`, `users`): each actor's id becomes a
30
53
  * seeded row's key in its own tenant, so a handler writing `ctx.actor.id` into a foreign key
31
- * writes a row that exists. Omitted, an actor's id is its role's name.
54
+ * writes a row that exists. `{ entity, column }` names the column that holds the user instead
55
+ * (`{ entity: membership, column: 'userId' }`). Omitted, a deterministic uuid per role and tenant.
32
56
  */
33
- readonly actor?: { readonly $name: string };
57
+ readonly actor?:
58
+ | { readonly $name: string }
59
+ | { readonly entity: { readonly $name: string }; readonly column: string };
34
60
  /**
35
61
  * By entity name, `seedGraph`'s own option: a table whose rows a generated value cannot satisfy
36
62
  * (an `invariant` across columns) is built by the app's `defineFactory`. An unknown name is
@@ -41,9 +67,10 @@ export interface ExerciseAppOptions {
41
67
  * Run in the exercise process once the network is sealed, before the first row: install the
42
68
  * `mockFetch` routes or `cassette()` your vendor-calling handlers need, so they run for real.
43
69
  * What it returns (a cassette, any `Disposable`) is disposed after the pass. `allowHost` here is
44
- * `X_EXERCISE_SETUP_UNSEALED` — the pass never sends a call out.
70
+ * `X_EXERCISE_SETUP_UNSEALED` — the pass never sends a call out. An array runs in order and is
71
+ * disposed in reverse; one that throws disposes those that already ran.
45
72
  */
46
- readonly setup?: ExerciseSetup;
73
+ readonly setup?: ExerciseSetup | readonly ExerciseSetup[];
47
74
  }
48
75
 
49
76
  /** `X_CONTRACT_EXERCISE_UNDECLARED`, 39's code for the same silence: an `off` with no reason. */
@@ -67,23 +94,32 @@ export function defineExercise(
67
94
  return Object.freeze({
68
95
  kind: 'exercise-overrides',
69
96
  entries,
70
- ...(app.actor === undefined ? {} : { actorEntity: app.actor.$name }),
97
+ ...(app.actor === undefined
98
+ ? {}
99
+ : 'entity' in app.actor
100
+ ? { actorEntity: app.actor.entity.$name, actorColumn: app.actor.column }
101
+ : { actorEntity: app.actor.$name }),
71
102
  ...(app.factories === undefined ? {} : { factories: app.factories }),
72
103
  ...(app.setup === undefined ? {} : { setup: app.setup }),
73
104
  });
74
105
  }
75
106
 
76
107
  /**
77
- * Every override names a registered action, query or job — checked when the pass runs, because
78
- * that is when the registries are full. `X_DECLARATION_UNKNOWN`, the code an unknown name answers
79
- * everywhere else; the cause lists what IS registered so the typo is visible.
108
+ * Every override names a registered action, query or job — bare, or qualified by the kind it is
109
+ * registered as — checked when the pass runs, because that is when the registries are full.
110
+ * `X_DECLARATION_UNKNOWN`, the code an unknown name answers everywhere else; the cause lists what
111
+ * IS registered so the typo is visible.
80
112
  */
81
113
  export function assertOverridesKnown(
82
114
  overrides: ExerciseOverrides | undefined,
83
- known: ReadonlySet<string>,
115
+ registered: readonly { readonly kind: ExerciseKind; readonly name: string }[],
84
116
  ): void {
85
- const unknown = [...(overrides?.entries.keys() ?? [])].filter((name) => !known.has(name)).sort();
117
+ const keys = new Set(
118
+ registered.flatMap(({ kind, name }) => [name, exerciseEntryKey(kind, name)]),
119
+ );
120
+ const unknown = [...(overrides?.entries.keys() ?? [])].filter((key) => !keys.has(key)).sort();
86
121
  if (unknown.length === 0) return;
122
+ const known = new Set(registered.map(({ name }) => name));
87
123
  throw unknownDeclaration(unknown, known, 'defineExercise() overrides');
88
124
  }
89
125
 
@@ -6,6 +6,7 @@
6
6
  import { bindDrawn } from '@ultimat3/core';
7
7
  import type { StandardSchemaV1 } from '@ultimat3/schema';
8
8
  import type { ExerciseOverrides } from './define-exercise';
9
+ import { overrideFor } from './define-exercise';
9
10
  import type { DrillTarget } from './drill-load';
10
11
  import type { Sampler } from './exercise-input';
11
12
  import { loadSampler } from './exercise-input';
@@ -53,7 +54,8 @@ function verdictOf(
53
54
  if (/[:*]/.test(candidate.path))
54
55
  return { reason: 'its path takes a parameter the load cannot bind' };
55
56
  if (!candidate.anonymous) return { reason: 'its policy refuses an anonymous caller' };
56
- const override = overrides?.entries.get(candidate.name);
57
+ // Kind-aware, as the pass: an `'action:<name>'` entry wins over a bare one a job may share.
58
+ const override = overrideFor(overrides, 'action', candidate.name);
57
59
  if (override === undefined) return { bind: undefined };
58
60
  if ('off' in override) return { reason: `exercise.ts turns it off: ${override.off.trim()}` };
59
61
  if (override.actor !== null) return { reason: 'exercise.ts runs it as a signed-in actor' };
package/src/errors.ts CHANGED
@@ -1,11 +1,6 @@
1
1
  // The X_* codes owned by @ultimat3/testing. A test failure has to be as actionable as a runtime
2
2
  // failure — the fix line here is the mock to add, the service to start, or the seed to freeze.
3
- import {
4
- registerErrorCodes,
5
- renderCauseValue,
6
- renderFixLiteral,
7
- UltimateError,
8
- } from '@ultimat3/core';
3
+ import { registerErrorCodes, UltimateError } from '@ultimat3/core';
9
4
 
10
5
  // `X_TEST_REGISTRY_LEAK` is declared below, in this registry; its message lives beside it.
11
6
  export { RegistryLeakError } from './registry-leak-error';
@@ -70,6 +65,9 @@ export const TESTING_ERROR_CODES = [
70
65
  'X_CASSETTE_RECORD_REFUSED',
71
66
  'X_TEST_MODULE_MOCK_UNRESTORABLE',
72
67
  'X_EXERCISE_SETUP_UNSEALED',
68
+ 'X_JOB_CRASH_UNBOUNDED',
69
+ 'X_EXERCISE_ACTOR_USER_UNSEATED',
70
+ 'X_EXERCISE_INPUT_THREW',
73
71
  ] as const;
74
72
 
75
73
  export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
@@ -135,6 +133,9 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
135
133
  X_CASSETTE_RECORD_REFUSED: 'a cassette recording was refused',
136
134
  X_TEST_MODULE_MOCK_UNRESTORABLE: 'a mocked module could not be put back at the file boundary',
137
135
  X_EXERCISE_SETUP_UNSEALED: 'an exercise setup let a host through the seal',
136
+ X_JOB_CRASH_UNBOUNDED: 'a crash proof needs more kill points than its bound',
137
+ X_EXERCISE_ACTOR_USER_UNSEATED: "the exercise pass could not seat its actor's x_users row",
138
+ X_EXERCISE_INPUT_THREW: "an exercise entry's input threw",
138
139
  };
139
140
 
140
141
  // Titles must be registered for `format()` to render the contract's first line. Every code above is
@@ -146,12 +147,8 @@ registerErrorCodes(
146
147
  ),
147
148
  );
148
149
 
149
- // No `docs:` on the subclasses below. `UltimateError` fills it from `describeErrorCode(code).docs`,
150
- // which is `@ultimat3/core`'s `ERROR_DOCS_URL` — one page for every code, never one per code, because
151
- // `wiki/` is the framework's only public documentation surface and a code lives there in a TABLE ROW,
152
- // which has no anchor. The `https://ultimate.dev/errors/<code>` links this file built until 9.x
153
- // answered 404, host included, on every error it has ever thrown; restating the replacement here
154
- // would be the same constant in eight places waiting to drift again.
150
+ // No `docs:` below: `UltimateError` fills core's `ERROR_DOCS_URL`, one page per code set (a wiki
151
+ // TABLE ROW has no anchor; per-code links answered 404 until 9.x). Restating it here would drift.
155
152
 
156
153
  /**
157
154
  * A test reached the network without a mock or an allowlist entry. Always a bug, never a flake.
@@ -420,81 +417,3 @@ export class NetworkRaceError extends UltimateError {
420
417
  });
421
418
  }
422
419
  }
423
-
424
- /** Neither path is controlled by the framework: both arrive from the test's own call. */
425
- const ISLAND_PLACEHOLDER = '<the island path the cause names>';
426
-
427
- /**
428
- * The builder produced no chunk for the file the test named. Listing what it DID build is the
429
- * whole value: a path relative to the test file instead of to the app root, a typo, and an island
430
- * outside the discovery glob are one symptom and three different edits, and only the list tells
431
- * them apart. An empty list is its own answer — the glob found nothing at all under this root.
432
- */
433
- export class IslandNotBuiltError extends UltimateError {
434
- constructor(input: { file: string; root: string; built: readonly string[] }) {
435
- const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
436
- super({
437
- code: 'X_TEST_ISLAND_NOT_BUILT',
438
- cause:
439
- input.built.length === 0
440
- ? `no island was built under ${renderCauseValue(input.root)}, so ${renderCauseValue(input.file)} cannot be mounted`
441
- : `${renderCauseValue(input.file)} is not in the bundle built from ${renderCauseValue(input.root)}; it built ${input.built.join(', ')}`,
442
- fix:
443
- input.built.length === 0
444
- ? 'x g island <name> --at apps/web/site — then set root to the directory holding apps/'
445
- : `mountIsland({ build, root, file: ${renderFixLiteral(input.built[0], ISLAND_PLACEHOLDER)} }) — the path is app-root-relative, not relative to the test, and ${file} is not one of them`,
446
- });
447
- }
448
- }
449
-
450
- export const islandNotBuilt = (
451
- file: string,
452
- root: string,
453
- built: readonly string[],
454
- ): UltimateError => new IslandNotBuiltError({ file, root, built });
455
-
456
- /** A name that can be written as a JSX tag. `export default` and `export { x as 'a b' }` are both
457
- * legal ES and neither can — a paste emitting one is a syntax error in the reader's own file. */
458
- const JSX_NAME = /^[A-Za-z_$][\w$]*$/;
459
-
460
- /**
461
- * The export the paste renders. A component first — an initial capital that is not the whole name,
462
- * which is what separates `Counter` from a `PROPS` constant — and any other usable identifier
463
- * after it, because a lowercase component still compiles and beats a name the reader must invent.
464
- */
465
- const componentOf = (exported: readonly string[]): string | undefined => {
466
- const usable = exported.filter((name) => JSX_NAME.test(name) && name !== 'default');
467
- return usable.find((name) => /^[A-Z]/.test(name) && name !== name.toUpperCase()) ?? usable[0];
468
- };
469
-
470
- /**
471
- * The chunk built and imported, and exports no `mount`. Distinct from a build failure: the island
472
- * compiles, ships and is served — the hydration runtime calls `m.mount(el, props)` and the browser
473
- * throws on a page that passed every gate. Naming the exports it DOES have is what separates a
474
- * renamed export from a file that exports only its component.
475
- *
476
- * The paste is built from THOSE exports rather than from a sketch. It read
477
- * `render(() => <Island {...props} />, el)` with `props: Props` until 2026-08-21, and none of
478
- * `Island`, `Props` or `render` exists in the file the reader was told to paste it into — three
479
- * compile errors handed out as the remedy for one. Two of them the error already knew the answer
480
- * to, from its own cause; the third is an import, so the import is in the line.
481
- */
482
- export class IslandMountMissingError extends UltimateError {
483
- constructor(input: { file: string; exported: readonly string[] }) {
484
- const file = renderFixLiteral(input.file, ISLAND_PLACEHOLDER);
485
- const component = componentOf(input.exported);
486
- super({
487
- code: 'X_TEST_ISLAND_NO_MOUNT',
488
- cause: `the chunk built from ${renderCauseValue(input.file)} exports ${
489
- input.exported.length === 0 ? 'nothing' : input.exported.join(', ')
490
- } — the hydration runtime calls m.mount(el, props)`,
491
- fix:
492
- component === undefined
493
- ? `${file} exports nothing a mount could render — x g island <name> --at apps/web/site writes an island whose mount() is already there, and its shape is the one to copy`
494
- : `in ${file} add: import { render } from 'solid-js/web'; export function mount(el: HTMLElement, props: Parameters<typeof ${component}>[0]): () => void { el.textContent = ''; return render(() => <${component} {...props} />, el); }`,
495
- });
496
- }
497
- }
498
-
499
- export const islandMountMissing = (file: string, exported: readonly string[]): UltimateError =>
500
- new IslandMountMissingError({ file, exported });
@@ -0,0 +1,63 @@
1
+ // The user an exercise actor IS: one `x_users` row per actor the pass acts as, written before the
2
+ // call, so a handler reading its caller through `@ultimat3/auth` (`findUserById(ctx.actor.id)`)
3
+ // finds the row production always has. Only where the table exists — the framework schema every
4
+ // `x exercise` database is built with — and only for an actor whose id has a user's shape.
5
+
6
+ import type { Actor } from '@ultimat3/core';
7
+ import { isUltimateError, renderThrowable, UltimateError } from '@ultimat3/core';
8
+ import type { DbClient } from '@ultimat3/db';
9
+
10
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
+
12
+ /** Whether `x_users` exists on this client, asked once per client: the schema does not move. */
13
+ const hasUsers = new WeakMap<DbClient, Promise<boolean>>();
14
+
15
+ /** The insert was refused: the pass cannot act as a user it could not create. */
16
+ export class ExerciseActorUserUnseatedError extends UltimateError {
17
+ constructor(error: unknown) {
18
+ super({
19
+ code: 'X_EXERCISE_ACTOR_USER_UNSEATED',
20
+ cause: `x exercise writes one x_users row per actor it acts as, and the insert was refused: ${isUltimateError(error) ? error.cause : renderThrowable(error)}`,
21
+ fix: 'x exercise --json # after a migration under packages/db/migrations/ gives the column the app added to x_users a default, or makes it nullable',
22
+ sourceError: error,
23
+ });
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Seat every actor in `actors` as an `x_users` row: id, a reserved `.invalid` address unique per
29
+ * id, its tenant, roles, permissions and scopes. Idempotent (`on conflict (id) do nothing`), so
30
+ * the same role in the same tenant — one id, `exerciseActorId` — is written once however often the
31
+ * pass acts as it. No installed client, no table, no uuid: nothing to seat, nothing written.
32
+ */
33
+ export async function seatActorUsers(actors: readonly (Actor | null)[]): Promise<void> {
34
+ const users = [
35
+ ...new Map(
36
+ actors.filter((a): a is Actor => a !== null && UUID.test(a.id)).map((a) => [a.id, a]),
37
+ ).values(),
38
+ ];
39
+ if (users.length === 0) return;
40
+ const { db, dbClientInstalled, sql } = await import('@ultimat3/db');
41
+ if (!dbClientInstalled()) return;
42
+ const client = db();
43
+ let known = hasUsers.get(client);
44
+ if (known === undefined) {
45
+ known = client
46
+ .one<{ found: boolean }>(sql`select to_regclass('x_users') is not null as found`)
47
+ .then((row) => row?.found === true);
48
+ hasUsers.set(client, known);
49
+ }
50
+ if (!(await known)) return;
51
+ for (const user of users) {
52
+ const org = typeof user.orgId === 'string' && UUID.test(user.orgId) ? user.orgId : null;
53
+ try {
54
+ await client.execute(sql`
55
+ insert into x_users (id, email, org_id, roles, permissions, scopes)
56
+ values (${user.id}, ${`${user.id}@exercise.invalid`}, ${org}, ${[...(user.roles ?? [])]},
57
+ ${[...(user.permissions ?? [])]}, ${[...(user.scopes ?? [])]})
58
+ on conflict (id) do nothing`);
59
+ } catch (error) {
60
+ throw new ExerciseActorUserUnseatedError(error);
61
+ }
62
+ }
63
+ }
@@ -3,7 +3,7 @@
3
3
  // because the set — anonymous plus one per declared role — is `@ultimat3/cli`'s `devActors()`,
4
4
  // and a second "every role" builder here would drift from the one the policy panel shows.
5
5
 
6
- import type { Actor } from '@ultimat3/core';
6
+ import type { Actor, ActorFactMap } from '@ultimat3/core';
7
7
  import type { NamedActor, Policy } from '@ultimat3/policy';
8
8
  import { policyMatrix, rolesGranting } from '@ultimat3/policy';
9
9
  import type { ExerciseOverride } from './define-exercise';
@@ -21,10 +21,49 @@ export type ActorChoice =
21
21
 
22
22
  /**
23
23
  * An override's actor, moved into the primitive's tenant: every primitive gets a fresh pair of
24
- * tenants, so an actor declared once in `exercise.ts` cannot know the org it will act in.
24
+ * tenants, so an actor declared once in `exercise.ts` cannot know the org it will act in. A fact
25
+ * naming the org it was declared in moves too, as the input's `orgId` does
26
+ * (`exercise-override-input.ts`): else `memberOrgIds.includes(input.orgId)` denies every run.
25
27
  */
26
- export const inTenant = (actor: Actor | null, tenant: string): Actor | null =>
27
- actor === null ? null : Object.freeze({ ...actor, orgId: tenant });
28
+ export const inTenant = (actor: Actor | null, tenant: string): Actor | null => {
29
+ if (actor === null) return null;
30
+ const facts = rehomedFacts(actor.facts, actor.orgId, tenant);
31
+ return Object.freeze({ ...actor, orgId: tenant, ...(facts === undefined ? {} : { facts }) });
32
+ };
33
+
34
+ /** Each top-level fact equal to `from` — or an array holding it — with `to` in its place. */
35
+ function rehomedFacts(
36
+ facts: ActorFactMap | undefined,
37
+ from: string | undefined,
38
+ to: string,
39
+ ): ActorFactMap | undefined {
40
+ if (facts === undefined || from === undefined || from === to) return facts;
41
+ const moved: Record<string, unknown> = {};
42
+ // An app augments `ActorFacts`, so its value types say nothing here: each is read as unknown.
43
+ const entries: [string, unknown][] = Object.entries(facts);
44
+ for (const [key, value] of entries) {
45
+ if (value === from) moved[key] = to;
46
+ else if (Array.isArray(value) && value.includes(from)) {
47
+ moved[key] = value.map((one: unknown) => (one === from ? to : one));
48
+ }
49
+ }
50
+ return Object.keys(moved).length === 0 ? facts : Object.freeze({ ...facts, ...moved });
51
+ }
52
+
53
+ /**
54
+ * A role's actor id in one tenant: a uuid, as `ctx.actor.id` always is in production (an
55
+ * `x_users` key), and the same one every time for that role in that tenant — so a rerun on a seed
56
+ * replays byte for byte, and A's actor is never B's. Name-based (SHA-1, version 5 bits), never
57
+ * random: nothing about it may depend on the order the pass asks.
58
+ */
59
+ export function exerciseActorId(role: string, tenant: string): string {
60
+ const digest = new Bun.CryptoHasher('sha1').update(`x-exercise-actor\0${role}\0${tenant}`);
61
+ const bytes = digest.digest().subarray(0, 16);
62
+ bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50;
63
+ bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
64
+ const hex = bytes.toHex();
65
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
66
+ }
28
67
 
29
68
  type Verdict = 'allowed' | 'denied' | 'undecidable';
30
69
 
@@ -64,7 +103,8 @@ export function chooseActor(
64
103
  tenant: string,
65
104
  override: ExerciseOverride | undefined,
66
105
  ): ActorChoice {
67
- if (override !== undefined && 'actor' in override) {
106
+ // An input-only entry (`{ input }`, no `actor`) keeps the pick below: only a DECLARED actor wins.
107
+ if (override !== undefined && !('off' in override) && override.actor !== undefined) {
68
108
  return { kind: 'actor', actor: inTenant(override.actor, tenant), name: 'override' };
69
109
  }
70
110
  const candidates = grants(tenant);
@@ -92,12 +132,23 @@ export function chooseActor(
92
132
  : `none of ${ordered.map((c) => c.name).join(', ')} is allowed by ${policy.label} or holds ${permissions.join(', ') || 'its grant'}`,
93
133
  };
94
134
  }
95
- return { kind: 'actor', actor: pick[0].actor, name: pick[0].name };
135
+ const [{ actor, name }] = pick;
136
+ return { kind: 'actor', actor: asRoleUser(actor, name, tenant), name };
96
137
  }
97
138
 
139
+ /** A role's actor with the id a production actor has: `exerciseActorId(role, tenant)`. */
140
+ const asRoleUser = (actor: Actor | null, name: string, tenant: string): Actor | null =>
141
+ actor === null ? null : Object.freeze({ ...actor, id: exerciseActorId(name, tenant) });
142
+
98
143
  /** The seeded rows an actor can be one of: the pass's graph, read for one entity. */
99
144
  export interface ActorRows {
100
145
  readonly entity: { readonly $name: string; readonly $primaryKey: readonly string[] };
146
+ /**
147
+ * The column whose value IS the user (`memberships.userId`); omitted, the row's own key. A
148
+ * membership's id is not a user's id, and a handler that reads `ctx.actor.id` as `x_users`'s
149
+ * must find the membership by the column that holds it.
150
+ */
151
+ readonly column?: string;
101
152
  readonly rows: readonly {
102
153
  readonly tenant: string | null;
103
154
  readonly row: Readonly<Record<string, unknown>>;
@@ -106,13 +157,15 @@ export interface ActorRows {
106
157
 
107
158
  /**
108
159
  * The actor as a ROW of the entity the app named (`defineExercise(…, { actor: members })`): its
109
- * id becomes the key of a seeded row in its tenant, the one carrying one of its roles when any
110
- * does. Without it an actor's id is a role name, and every handler that writes `ctx.actor.id`
111
- * into a foreign key — `authorId` — is refused by the database.
160
+ * id becomes the key — or the named `column` — of a seeded row in its tenant, the one carrying
161
+ * one of its roles when any does. Without it an actor's id is `exerciseActorId(role, tenant)`, a
162
+ * user no table of the app's holds, so a handler writing `ctx.actor.id` into a foreign key —
163
+ * `authorId` — is refused by the database.
112
164
  */
113
165
  export function asSeededRow(actor: Actor | null, tenant: string, rows: ActorRows): Actor | null {
114
- const key = rows.entity.$primaryKey[0];
115
- if (actor === null || key === undefined || rows.entity.$primaryKey.length !== 1) return actor;
166
+ const key =
167
+ rows.column ?? (rows.entity.$primaryKey.length === 1 ? rows.entity.$primaryKey[0] : undefined);
168
+ if (actor === null || key === undefined) return actor;
116
169
  const own = rows.rows.filter((row) => row.tenant === tenant || row.tenant === null);
117
170
  const roles = actor.roles ?? [];
118
171
  const row =
@@ -1,5 +1,5 @@
1
- // The crash proof, as the exercise pass runs it: a job its control reached is killed at every step
2
- // boundary with the control's own input and actor (`crashProof`), and the answer is a plain record
1
+ // The crash proof, as the exercise pass runs it: a job its control reached is killed at every
2
+ // distinct step boundary with the control's own input and actor (`crashProof`), and the answer is a plain record
3
3
  // `.x/exercise.json` can hold. Run after the control, so its runs meet the rows the control left.
4
4
 
5
5
  import type { Actor } from '@ultimat3/core';
@@ -34,7 +34,11 @@ export async function proveCrash(
34
34
  const worker = ctxOf(actor === null ? { role: 'worker' } : { role: 'worker', actor });
35
35
  try {
36
36
  const report = await crashProof(handle, input, { context: () => worker });
37
- const counted = { boundaries: report.boundaries.length, reruns: report.reruns.length };
37
+ const counted = {
38
+ boundaries: report.boundaries.length,
39
+ crossed: report.crossed,
40
+ reruns: report.reruns.length,
41
+ };
38
42
  return report.divergences.length === 0
39
43
  ? { verdict: 'held', ...counted }
40
44
  : { verdict: 'diverged', ...counted, findings: report.divergences.map(findingOf) };
@@ -0,0 +1,28 @@
1
+ // The override line a drifted primitive's record carries: `name: { input: (drawn) => ({ ...drawn,
2
+ // digest: "<must match ^[0-9a-f]{64}$>" }) },` — the field no draw can fill, named and bound,
3
+ // rendered by core's one `renderDrawnInput`. No `actor:`: the pass picks one when the entry has none.
4
+
5
+ import { renderDrawnInput, renderExerciseKey, sampleGapBinding } from '@ultimat3/core';
6
+ import type { StandardSchemaV1 } from '@ultimat3/schema';
7
+ import type { Sampler } from './exercise-input';
8
+
9
+ /** `idFields` are the input's id-shaped keys: each wants a real row's id, as the other hints say. */
10
+ export function driftOverrideLine(
11
+ name: string,
12
+ schema: StandardSchemaV1,
13
+ sampler: Sampler,
14
+ idFields: readonly string[],
15
+ ): string {
16
+ const gaps = sampler.sampleGaps(schema);
17
+ const bindings = [
18
+ ...gaps.map((path) => sampleGapBinding(path, sampler.describeSampleGap(schema, path))),
19
+ ...idFields
20
+ .filter((field) => !gaps.includes(field))
21
+ .map((field) => ({ path: field, placeholder: '<a real id>' })),
22
+ ];
23
+ const input =
24
+ bindings.length === 0
25
+ ? "(drawn) => ({ ...drawn, field: '<a value the refinement accepts>' })"
26
+ : renderDrawnInput(bindings);
27
+ return `${renderExerciseKey(name)}: { input: ${input} },`;
28
+ }
@@ -10,6 +10,9 @@ import type { SeedEntity } from './seed-graph-shape';
10
10
  export interface Sampler {
11
11
  sampleInput(schema: StandardSchemaV1): unknown;
12
12
  arbitrary(schema: StandardSchemaV1, options: { seed: number; run: number }): unknown;
13
+ /** The fields the minimal draw cannot fill, and what each needs: a drift's hint names them. */
14
+ sampleGaps(schema: StandardSchemaV1): readonly string[];
15
+ describeSampleGap(schema: StandardSchemaV1, path: string): string;
13
16
  }
14
17
 
15
18
  /** On demand: a `packages/core` test that never exercises anything must not load the walker. */