@ultimat3/testing 30.9.0 → 31.0.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 (148) hide show
  1. package/CLAUDE.md +46 -55
  2. package/README.md +179 -39
  3. package/package.json +23 -17
  4. package/src/ai-conformance-answer.ts +67 -0
  5. package/src/ai-gateway-conformance.ts +105 -0
  6. package/src/ai-provider-conformance.ts +69 -0
  7. package/src/ai-provider-transport-conformance.ts +170 -0
  8. package/src/audit-sink-conformance.ts +204 -0
  9. package/src/auth-adapter-conformance-credentials.ts +124 -0
  10. package/src/auth-adapter-conformance-mfa.ts +70 -0
  11. package/src/auth-adapter-conformance-passkeys.ts +133 -0
  12. package/src/auth-adapter-conformance-sessions.ts +115 -0
  13. package/src/auth-adapter-conformance-support.ts +71 -0
  14. package/src/auth-adapter-conformance-users.ts +128 -0
  15. package/src/auth-adapter-conformance.ts +34 -0
  16. package/src/auth-limiter-factory-conformance.ts +224 -0
  17. package/src/auth-server-store-conformance-records.ts +69 -0
  18. package/src/auth-server-store-conformance.ts +208 -0
  19. package/src/cache-tier-conformance-checks.ts +142 -0
  20. package/src/cache-tier-conformance.ts +24 -0
  21. package/src/cassette-format.ts +8 -13
  22. package/src/cassette-record.ts +1 -1
  23. package/src/cdp-browser.ts +10 -11
  24. package/src/cdp-e2e-page.ts +2 -2
  25. package/src/cdp-e2e-session.ts +2 -2
  26. package/src/cdp-network-probe.ts +1 -1
  27. package/src/cdp-offline-script.ts +2 -2
  28. package/src/clock-conformance.ts +126 -0
  29. package/src/conformance.ts +239 -0
  30. package/src/e2e-browser-handle.ts +1 -2
  31. package/src/e2e-error-codes.ts +17 -16
  32. package/src/e2e-run.ts +4 -3
  33. package/src/embedder-conformance.ts +101 -0
  34. package/src/entity-conformance-aggregates.ts +210 -0
  35. package/src/entity-conformance-batches.ts +216 -0
  36. package/src/entity-conformance-bulk.ts +379 -0
  37. package/src/entity-conformance-checks.ts +27 -0
  38. package/src/entity-conformance-entities.ts +52 -0
  39. package/src/entity-conformance-locks.ts +286 -0
  40. package/src/entity-conformance-matrix.ts +397 -0
  41. package/src/entity-conformance-reads.ts +241 -0
  42. package/src/entity-conformance-support.ts +56 -0
  43. package/src/entity-conformance-tenancy.ts +296 -0
  44. package/src/entity-conformance-values.ts +305 -0
  45. package/src/entity-conformance-versions.ts +60 -0
  46. package/src/entity-conformance-writes.ts +348 -0
  47. package/src/entity-driver-conformance.ts +103 -0
  48. package/src/error-groups-store-conformance.ts +198 -0
  49. package/src/error-reporter-conformance.ts +119 -0
  50. package/src/errors.ts +20 -2
  51. package/src/event-bus-conformance.ts +161 -0
  52. package/src/exercise-drift-hint.ts +4 -1
  53. package/src/exercise-judge.ts +5 -3
  54. package/src/exercise-override-line.ts +98 -0
  55. package/src/exercise-report.ts +30 -51
  56. package/src/exercise.ts +12 -6
  57. package/src/factories.ts +192 -179
  58. package/src/factory-api.ts +131 -0
  59. package/src/factory-associations.ts +67 -0
  60. package/src/factory-errors.ts +38 -0
  61. package/src/factory-lint.ts +92 -0
  62. package/src/factory-persist.ts +74 -16
  63. package/src/factory-pipeline.ts +191 -0
  64. package/src/factory-registry.ts +2 -1
  65. package/src/factory-types.ts +131 -0
  66. package/src/failure-store-conformance.ts +137 -0
  67. package/src/fixture-jobs.ts +27 -11
  68. package/src/fixture-mail.ts +7 -7
  69. package/src/fixture-seed.ts +111 -0
  70. package/src/fixture-statements.ts +68 -52
  71. package/src/framework-fixtures.ts +1 -1
  72. package/src/idempotency-store-conformance.ts +186 -0
  73. package/src/idempotency-store-replay-conformance.ts +140 -0
  74. package/src/idempotency-store-tx-conformance.ts +132 -0
  75. package/src/idempotency-store-world-conformance.ts +82 -0
  76. package/src/identity-provider-conformance.ts +144 -0
  77. package/src/image-transform-conformance.ts +89 -0
  78. package/src/index.ts +68 -157
  79. package/src/isr-store-conformance.ts +113 -0
  80. package/src/job-sim-effects.ts +19 -31
  81. package/src/job-sim-world.ts +6 -15
  82. package/src/lease-store-conformance.ts +195 -0
  83. package/src/mail-driver-conformance.ts +108 -0
  84. package/src/matcher-doubles.ts +104 -0
  85. package/src/matcher-stub.ts +78 -0
  86. package/src/matcher-surface.ts +21 -0
  87. package/src/matchers.ts +19 -1
  88. package/src/mcp-confirmation-store-conformance.ts +262 -0
  89. package/src/meter-store-conformance.ts +135 -0
  90. package/src/notify-digest-conformance.ts +133 -0
  91. package/src/notify-inbox-conformance.ts +130 -0
  92. package/src/notify-ledger-conformance.ts +134 -0
  93. package/src/notify-preference-conformance.ts +49 -0
  94. package/src/notify-stores-conformance.ts +73 -0
  95. package/src/outbox-store-conformance-claims.ts +112 -0
  96. package/src/outbox-store-conformance-subject.ts +65 -0
  97. package/src/outbox-store-conformance.ts +71 -0
  98. package/src/per-test-reset.ts +55 -20
  99. package/src/preload.ts +4 -2
  100. package/src/purge-conformance.ts +79 -0
  101. package/src/push-device-conformance.ts +124 -0
  102. package/src/push-subscription-conformance.ts +123 -0
  103. package/src/quiet-logs.ts +4 -4
  104. package/src/rate-limit-store-conformance.ts +178 -0
  105. package/src/registry-leak-error.ts +8 -1
  106. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  107. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  108. package/src/scrape-driver-conformance-site.ts +84 -0
  109. package/src/scrape-driver-conformance.ts +34 -0
  110. package/src/search-index-conformance-list.ts +76 -0
  111. package/src/search-index-conformance-support.ts +69 -0
  112. package/src/search-index-conformance-versions.ts +66 -0
  113. package/src/search-index-conformance.ts +126 -0
  114. package/src/secret-source-conformance.ts +91 -0
  115. package/src/seed-factories.ts +57 -0
  116. package/src/seed-writer.ts +8 -19
  117. package/src/semantic-cache-factory-conformance.ts +86 -0
  118. package/src/sms-transport-conformance.ts +102 -0
  119. package/src/step-store-conformance.ts +171 -0
  120. package/src/storage-conformance-read-checks.ts +132 -0
  121. package/src/storage-conformance-shape.ts +121 -0
  122. package/src/storage-conformance-stream-checks.ts +226 -0
  123. package/src/storage-conformance.ts +34 -0
  124. package/src/stub-action.ts +24 -0
  125. package/src/stub-errors.ts +86 -0
  126. package/src/stub-job.ts +30 -0
  127. package/src/stub-query.ts +25 -0
  128. package/src/stub-script.ts +76 -0
  129. package/src/stub-stack.ts +29 -0
  130. package/src/stub.ts +73 -0
  131. package/src/swap-adapter.ts +135 -0
  132. package/src/test-scope.ts +96 -0
  133. package/src/test-types.ts +1 -1
  134. package/src/totp-replay-guard-conformance.ts +76 -0
  135. package/src/transport-conformance.ts +179 -0
  136. package/src/upload-scanner-conformance.ts +112 -0
  137. package/src/vector-store-conformance-checks.ts +174 -0
  138. package/src/vector-store-conformance.ts +21 -0
  139. package/src/cdp-connection.ts +0 -291
  140. package/src/cdp-errors.ts +0 -179
  141. package/src/cdp-launch-attempt.ts +0 -224
  142. package/src/cdp-launch-candidates.ts +0 -62
  143. package/src/cdp-launch-profile.ts +0 -106
  144. package/src/cdp-launch-reap.ts +0 -68
  145. package/src/cdp-launch-wire.ts +0 -171
  146. package/src/cdp-launch.ts +0 -175
  147. package/src/cdp-pipe.ts +0 -77
  148. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,121 @@
1
+ // The slice of `@ultimat3/storage`'s `StorageDriver` the conformance checks call, structurally —
2
+ // as `budget-store-conformance.ts` does for `ai` — so a disk of your own is held to it without this
3
+ // package's build depending on `storage`. Every shipped disk is assignable as it is.
4
+
5
+ import type { UltimateError } from '@ultimat3/core';
6
+ import { isUltimateError } from '@ultimat3/core';
7
+
8
+ type Range = readonly [number, number];
9
+
10
+ export interface StorageObjectLike {
11
+ readonly key: string;
12
+ readonly size: number;
13
+ readonly etag: string;
14
+ readonly contentType?: string | undefined;
15
+ readonly cacheControl?: string | undefined;
16
+ readonly metadata?: Readonly<Record<string, string>> | undefined;
17
+ }
18
+
19
+ interface WriteOptions {
20
+ readonly contentType?: string | undefined;
21
+ readonly cacheControl?: string | undefined;
22
+ readonly metadata?: Readonly<Record<string, string>> | undefined;
23
+ }
24
+
25
+ /** The members a disk answers through the port, and nothing a single driver adds. */
26
+ export interface StorageDriverLike {
27
+ readonly name: string;
28
+ put(key: string, body: Uint8Array, options?: WriteOptions): Promise<StorageObjectLike>;
29
+ putStream(
30
+ key: string,
31
+ stream: ReadableStream<Uint8Array>,
32
+ options: WriteOptions & { readonly maxBytes: number },
33
+ ): Promise<StorageObjectLike>;
34
+ stat(key: string): Promise<StorageObjectLike | undefined>;
35
+ get(
36
+ key: string,
37
+ options?: { readonly range?: Range | undefined },
38
+ ): Promise<{ readonly bytes: Uint8Array; readonly object: StorageObjectLike }>;
39
+ stream(
40
+ key: string,
41
+ options?: { readonly etag?: string | undefined },
42
+ ): Promise<ReadableStream<Uint8Array>>;
43
+ streamRange(
44
+ key: string,
45
+ range: Range,
46
+ options?: { readonly etag?: string | undefined },
47
+ ): Promise<ReadableStream<Uint8Array>>;
48
+ copy(
49
+ from: string,
50
+ to: string,
51
+ options?: { readonly ifMatch?: string | undefined },
52
+ ): Promise<StorageObjectLike>;
53
+ delete(key: string): Promise<void>;
54
+ exists(key: string): Promise<boolean>;
55
+ list(options?: {
56
+ readonly prefix?: string | undefined;
57
+ readonly cursor?: string | null | undefined;
58
+ readonly limit?: number | undefined;
59
+ }): Promise<{
60
+ readonly rows: readonly { readonly key: string }[];
61
+ readonly nextCursor: string | null;
62
+ readonly hasMore: boolean;
63
+ }>;
64
+ }
65
+
66
+ /**
67
+ * What a check is handed. `maxPutBytes`, when the disk was built with one, arms the check that
68
+ * `putStream` is bounded by its own `maxBytes` and never by the disk's buffered-write ceiling.
69
+ */
70
+ export interface StorageSubject {
71
+ readonly disk: StorageDriverLike;
72
+ readonly maxPutBytes?: number | undefined;
73
+ }
74
+
75
+ export interface StorageCheck {
76
+ readonly name: string;
77
+ run(subject: StorageSubject): Promise<void>;
78
+ }
79
+
80
+ /** A key namespace per check, so a shared bucket survives two runs and a run that died. */
81
+ export const scopeOf = (): string => `conformance/${crypto.randomUUID()}/`;
82
+
83
+ export const bytesOf = (text: string): Uint8Array => new TextEncoder().encode(text);
84
+
85
+ export const textOf = (bytes: Uint8Array): string => new TextDecoder().decode(bytes);
86
+
87
+ export const drain = async (stream: ReadableStream<Uint8Array>): Promise<string> =>
88
+ new Response(stream).text();
89
+
90
+ export const streamOf = (...chunks: readonly Uint8Array[]): ReadableStream<Uint8Array> =>
91
+ new ReadableStream<Uint8Array>({
92
+ start(controller) {
93
+ for (const chunk of chunks) controller.enqueue(chunk);
94
+ controller.close();
95
+ },
96
+ });
97
+
98
+ /** What a call was refused with: its code, and the coded error itself when there was one. */
99
+ export interface Refusal {
100
+ readonly code: string;
101
+ readonly error?: UltimateError | undefined;
102
+ }
103
+
104
+ /** Code `resolved` when the call was not refused, so a test names the miss. */
105
+ export async function refusedWith(call: () => Promise<unknown>): Promise<Refusal> {
106
+ try {
107
+ await call();
108
+ } catch (caught) {
109
+ if (isUltimateError(caught)) return { code: caught.code, error: caught };
110
+ return { code: `not-a-coded-error: ${String(caught)}` };
111
+ }
112
+ return { code: 'resolved' };
113
+ }
114
+
115
+ /** Whether the refusal's `fix` (or `cause`) names `text` — false for no coded refusal at all. */
116
+ export const names = (refusal: Refusal, field: 'fix' | 'cause', text: string): boolean =>
117
+ refusal.error?.[field].includes(text) ?? false;
118
+
119
+ /** The code alone. */
120
+ export const refusalOf = async (call: () => Promise<unknown>): Promise<string> =>
121
+ (await refusedWith(call)).code;
@@ -0,0 +1,226 @@
1
+ // The listing, range and streamed-write half of the `StorageDriver` contract. Lifted from
2
+ // `storage/src/driver-parity.test.ts` and `driver-stream-parity.test.ts`: a page that is empty AND
3
+ // claims to be complete is a false erasure report, and an overrun that keeps bytes is a leak.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { StorageCheck, StorageDriverLike } from './storage-conformance-shape';
7
+ import {
8
+ bytesOf,
9
+ drain,
10
+ names,
11
+ refusalOf,
12
+ refusedWith,
13
+ scopeOf,
14
+ streamOf,
15
+ textOf,
16
+ } from './storage-conformance-shape';
17
+
18
+ const listed = async (disk: StorageDriverLike, prefix: string): Promise<readonly string[]> => {
19
+ const keys: string[] = [];
20
+ let cursor: string | null = null;
21
+ for (let pages = 0; pages < 10; pages += 1) {
22
+ const page = await disk.list({ prefix, limit: 1, cursor });
23
+ keys.push(...page.rows.map((row) => row.key));
24
+ expect(page.hasMore).toBe(page.nextCursor !== null);
25
+ if (!page.hasMore) return keys;
26
+ cursor = page.nextCursor;
27
+ }
28
+ return expect.unreachable(`list({ limit: 1 }) under ${prefix} never ended`);
29
+ };
30
+
31
+ export const STORAGE_STREAM_CHECKS: readonly StorageCheck[] = [
32
+ {
33
+ name: 'list pages through every key under a prefix, dot-prefixed ones included',
34
+ async run({ disk }) {
35
+ const scope = scopeOf();
36
+ const keys = [`${scope}.hidden.txt`, `${scope}a.txt`, `${scope}b/c.txt`];
37
+ for (const key of keys) await disk.put(key, bytesOf('x'));
38
+ expect([...(await listed(disk, scope))].sort()).toEqual([...keys].sort());
39
+ expect(await disk.list({ prefix: `${scopeOf()}` })).toEqual({
40
+ rows: [],
41
+ nextCursor: null,
42
+ hasMore: false,
43
+ });
44
+ },
45
+ },
46
+ {
47
+ name: 'a list limit is a page size or X_INVARIANT, never a silently empty page',
48
+ async run({ disk }) {
49
+ const scope = scopeOf();
50
+ await disk.put(`${scope}k`, bytesOf('x'));
51
+ for (const limit of [0, -1, 1.5, Number.NaN]) {
52
+ expect(await refusalOf(() => disk.list({ prefix: scope, limit }))).toBe('X_INVARIANT');
53
+ }
54
+ expect(await disk.list({ prefix: scope, limit: 1 })).toMatchObject({
55
+ nextCursor: null,
56
+ hasMore: false,
57
+ });
58
+ },
59
+ },
60
+ {
61
+ name: 'streamRange is the window get() answers for the same range, clamped at the end',
62
+ async run({ disk }) {
63
+ const key = `${scopeOf()}r.bin`;
64
+ await disk.put(key, bytesOf('0123456789'));
65
+ for (const range of [
66
+ [0, 0],
67
+ [2, 5],
68
+ [9, 9],
69
+ ] as const) {
70
+ const window = await drain(await disk.streamRange(key, range));
71
+ expect(window).toBe(textOf((await disk.get(key, { range })).bytes));
72
+ }
73
+ expect(await drain(await disk.streamRange(key, [7, 1_000_000]))).toBe('789');
74
+ const past = await refusedWith(() => disk.streamRange(key, [10, 12]));
75
+ expect([past.code, names(past, 'fix', 'disk.stat(')]).toEqual([
76
+ 'X_STORAGE_RANGE_UNSATISFIABLE',
77
+ true,
78
+ ]);
79
+ },
80
+ },
81
+ {
82
+ name: 'a tuple that is no range is X_INVARIANT before the disk is asked',
83
+ async run({ disk }) {
84
+ const key = `${scopeOf()}r.bin`;
85
+ for (const range of [[5, 2], [-1, 2], [0.5, 2], [0], 'bytes=0-1']) {
86
+ const bad = range as unknown as readonly [number, number];
87
+ const refused = await refusedWith(() => disk.streamRange(key, bad));
88
+ expect([refused.code, names(refused, 'cause', 'streamRange()')]).toEqual([
89
+ 'X_INVARIANT',
90
+ true,
91
+ ]);
92
+ }
93
+ expect(await refusalOf(() => disk.streamRange('../up', [0, 1]))).toBe(
94
+ 'X_STORAGE_PATH_UNSAFE',
95
+ );
96
+ },
97
+ },
98
+ {
99
+ name: 'putStream round-trips a body in the one object shape put() answers',
100
+ async run({ disk }) {
101
+ const key = `${scopeOf()}s.txt`;
102
+ const object = await disk.putStream(key, streamOf(bytesOf('hello '), bytesOf('stream')), {
103
+ maxBytes: 64,
104
+ contentType: 'text/plain',
105
+ cacheControl: 'public, max-age=60',
106
+ metadata: { uploadedBy: 'user-1' },
107
+ });
108
+ expect([object.key, object.size, object.contentType]).toEqual([key, 12, 'text/plain']);
109
+ expect([object.cacheControl, object.metadata]).toEqual([
110
+ 'public, max-age=60',
111
+ { uploadedBy: 'user-1' },
112
+ ]);
113
+ expect(await drain(await disk.stream(key))).toBe('hello stream');
114
+ expect((await disk.stat(key))?.size).toBe(12);
115
+ },
116
+ },
117
+ {
118
+ name: 'a body across many chunks lands every chunk, in order',
119
+ async run({ disk }) {
120
+ const [size, count, key] = [256 * 1024, 12, `${scopeOf()}big.bin`];
121
+ let sent = 0;
122
+ const body = new ReadableStream<Uint8Array>({
123
+ pull(controller) {
124
+ if (sent === count) return controller.close();
125
+ sent += 1;
126
+ controller.enqueue(new Uint8Array(size).fill(sent));
127
+ },
128
+ });
129
+ await disk.putStream(key, body, { maxBytes: size * count });
130
+ const stored = new Uint8Array(await new Response(await disk.stream(key)).arrayBuffer());
131
+ expect(stored.byteLength).toBe(size * count);
132
+ const lasts = Array.from({ length: count }, (_, at) => stored[at * size + size - 1]);
133
+ expect(lasts).toEqual(Array.from({ length: count }, (_, at) => at + 1));
134
+ },
135
+ },
136
+ {
137
+ name: 'an overrun is X_STORAGE_TOO_LARGE, cancels the source and keeps what the key held',
138
+ async run({ disk }) {
139
+ const scope = scopeOf();
140
+ let cancelled = false;
141
+ const endless = new ReadableStream<Uint8Array>({
142
+ pull: (controller) => controller.enqueue(bytesOf('0123456789')),
143
+ cancel: () => {
144
+ cancelled = true;
145
+ },
146
+ });
147
+ const overrun = await refusedWith(() =>
148
+ disk.putStream(`${scope}new`, endless, { maxBytes: 16 }),
149
+ );
150
+ expect([overrun.code, names(overrun, 'fix', 'maxBytes')]).toEqual([
151
+ 'X_STORAGE_TOO_LARGE',
152
+ true,
153
+ ]);
154
+ expect([cancelled, await disk.exists(`${scope}new`)]).toEqual([true, false]);
155
+
156
+ await disk.put(`${scope}old`, bytesOf('previous'));
157
+ const over = streamOf(bytesOf('0123456789'), bytesOf('0123456789'));
158
+ expect(await refusalOf(() => disk.putStream(`${scope}old`, over, { maxBytes: 16 }))).toBe(
159
+ 'X_STORAGE_TOO_LARGE',
160
+ );
161
+ expect(textOf((await disk.get(`${scope}old`)).bytes)).toBe('previous');
162
+ },
163
+ },
164
+ {
165
+ name: 'a source that dies mid-body is X_STORAGE_PUT_FAILED and leaves nothing',
166
+ async run({ disk }) {
167
+ const key = `${scopeOf()}dies`;
168
+ let sent = false;
169
+ const body = new ReadableStream<Uint8Array>({
170
+ pull(controller) {
171
+ if (sent) controller.error(new TypeError('the client went away'));
172
+ else controller.enqueue(bytesOf('partial'));
173
+ sent = true;
174
+ },
175
+ });
176
+ expect(await refusalOf(() => disk.putStream(key, body, { maxBytes: 64 }))).toBe(
177
+ 'X_STORAGE_PUT_FAILED',
178
+ );
179
+ expect(await disk.exists(key)).toBe(false);
180
+ },
181
+ },
182
+ {
183
+ name: 'putStream screens maxBytes, its body, and what needs the bytes up front, by X_INVARIANT',
184
+ async run({ disk }) {
185
+ const key = `${scopeOf()}screened`;
186
+ const refused = (options: unknown, body: unknown = streamOf()) =>
187
+ refusedWith(() =>
188
+ disk.putStream(key, body as ReadableStream<Uint8Array>, options as { maxBytes: number }),
189
+ );
190
+ for (const maxBytes of [undefined, 0, -1, 1.5, Number.NaN]) {
191
+ expect((await refused({ maxBytes })).code).toBe('X_INVARIANT');
192
+ }
193
+ for (const extra of [
194
+ { checksum: 'abc' },
195
+ { legalHold: true },
196
+ { retention: { mode: 'GOVERNANCE', retainUntil: new Date(0) } },
197
+ { serverSideEncryption: { algorithm: 'AES256' } },
198
+ ]) {
199
+ const upFront = await refused({ maxBytes: 64, ...extra });
200
+ expect([upFront.code, names(upFront, 'fix', 'disk.put(')]).toEqual(['X_INVARIANT', true]);
201
+ }
202
+ expect((await refused({ maxBytes: 64, metadata: { n: 1 } })).code).toBe('X_INVARIANT');
203
+ expect((await refused({ maxBytes: 1 }, bytesOf('x'))).code).toBe('X_INVARIANT');
204
+ const strings = new ReadableStream({
205
+ start(controller) {
206
+ controller.enqueue('not bytes');
207
+ controller.close();
208
+ },
209
+ });
210
+ expect((await refused({ maxBytes: 64 }, strings)).code).toBe('X_INVARIANT');
211
+ expect(await disk.exists(key)).toBe(false);
212
+ },
213
+ },
214
+ {
215
+ name: "putStream is bounded by its own maxBytes, never by the disk's put ceiling",
216
+ async run({ disk, maxPutBytes }) {
217
+ // Armed by a subject that names the ceiling its disk was built with.
218
+ if (maxPutBytes === undefined) return;
219
+ const [key, body] = [`${scopeOf()}past-ceiling`, bytesOf('x'.repeat(maxPutBytes + 1))];
220
+ expect(await refusalOf(() => disk.put(key, body))).toBe('X_STORAGE_TOO_LARGE');
221
+ const object = await disk.putStream(key, streamOf(body), { maxBytes: maxPutBytes * 2 });
222
+ expect(object.size).toBe(maxPutBytes + 1);
223
+ expect((await disk.stat(key))?.size).toBe(maxPutBytes + 1);
224
+ },
225
+ },
226
+ ];
@@ -0,0 +1,34 @@
1
+ // The `StorageDriver` contract as shared examples: `behavesLike(storageDriverConformance, () =>
2
+ // disk)` runs every check against a disk of your own, one test per check. Each check writes under
3
+ // a key prefix of its own, so one bucket serves every test, two runs at once, and a run that died.
4
+
5
+ import { test } from 'bun:test';
6
+ import type { SharedExamples } from './shared-examples';
7
+ import { sharedExamples } from './shared-examples';
8
+ import { STORAGE_READ_CHECKS } from './storage-conformance-read-checks';
9
+ import type { StorageCheck, StorageDriverLike, StorageSubject } from './storage-conformance-shape';
10
+ import { STORAGE_STREAM_CHECKS } from './storage-conformance-stream-checks';
11
+
12
+ export type { StorageCheck, StorageDriverLike, StorageSubject } from './storage-conformance-shape';
13
+
14
+ /** Every check, in the order a failing run reads best: writes and reads, then lists and streams. */
15
+ export const STORAGE_DRIVER_CHECKS: readonly StorageCheck[] = [
16
+ ...STORAGE_READ_CHECKS,
17
+ ...STORAGE_STREAM_CHECKS,
18
+ ];
19
+
20
+ /** A bare disk, or `{ disk, maxPutBytes }` for a disk built with a ceiling the suite should know. */
21
+ type Subject = StorageDriverLike | StorageSubject;
22
+
23
+ const subjectOf = (given: Subject): StorageSubject => ('disk' in given ? given : { disk: given });
24
+
25
+ export const storageDriverConformance: SharedExamples<Subject | Promise<Subject>> = sharedExamples(
26
+ 'a storage driver',
27
+ (subject) => {
28
+ for (const check of STORAGE_DRIVER_CHECKS) {
29
+ test(check.name, async () => {
30
+ await check.run(subjectOf(await subject()));
31
+ });
32
+ }
33
+ },
34
+ );
@@ -0,0 +1,24 @@
1
+ // Single responsibility: put a stub where an action's HANDLER is, through `@ultimat3/action`'s own
2
+ // seam — so the stub answers on every surface the action has (a direct call, `.as()`, HTTP, MCP,
3
+ // `.job()`, an `llm()`'s `.stream()`) and the policy, the input parse, the rate limit, the meter,
4
+ // idempotency and the output parse all still run. Loaded only when an action is stubbed.
5
+
6
+ import type { AnyAction } from '@ultimat3/action';
7
+ import type { Ctx } from '@ultimat3/core';
8
+ import type { StubWiring } from './stub-script';
9
+ import { stubStack } from './stub-stack';
10
+ import type { Undo } from './test-scope';
11
+
12
+ /** Stubs stack per target: a test's over a file's hands the file's back (`stub-stack.ts`). */
13
+ const push = stubStack<(args: { readonly input: unknown; readonly ctx: Ctx }) => unknown>();
14
+
15
+ /** Push `wiring`'s answers over `target`'s handler; the undo pops this stub and no other. */
16
+ export async function stubActionHandler(
17
+ target: AnyAction,
18
+ wiring: StubWiring<unknown, unknown>,
19
+ ): Promise<Undo> {
20
+ const { overrideHandler } = await import('@ultimat3/action/adapter');
21
+ const handle = (args: { readonly input: unknown; readonly ctx: Ctx }) =>
22
+ wiring.answer(args.input, args.ctx.actor);
23
+ return push(target, handle, (top) => overrideHandler(target, top));
24
+ }
@@ -0,0 +1,86 @@
1
+ // Single responsibility: the refusals of the test-double surface — `stub()`, `swapAdapter()` and
2
+ // the matchers that read them. The codes are registered in `errors.ts`, beside every other testing
3
+ // code; the classes live here because that catalogue is at its size ceiling.
4
+
5
+ import { describeValue, renderCauseValue, UltimateError } from '@ultimat3/core';
6
+
7
+ /** A double made where no preload will ever put it back. */
8
+ export class TestScopeUninstalledError extends UltimateError {
9
+ constructor(what: string) {
10
+ super({
11
+ code: 'X_TEST_SCOPE_UNINSTALLED',
12
+ cause: `${what} was made in a process the testing preload did not set up, so nothing would put it back and it would answer for every later file on the worker`,
13
+ fix: `printf '\\n[test]\\npreload = ["@ultimat3/testing/preload"]\\n' >> bunfig.toml — or, when bunfig.toml already has a [test] table, add that preload line to it`,
14
+ });
15
+ }
16
+ }
17
+
18
+ /** The body is stubbed and nobody said what it answers. */
19
+ export class TestStubUnansweredError extends UltimateError {
20
+ constructor(name: string) {
21
+ super({
22
+ code: 'X_TEST_STUB_UNANSWERED',
23
+ cause: `"${name}" is stubbed and was called before .returns() or .throws() scripted an answer`,
24
+ fix: `const stubbed = await stub(${name || 'target'}); stubbed.returns(<output>) — or .throws(new YourError(...)) — before the code under test runs`,
25
+ });
26
+ }
27
+ }
28
+
29
+ /** `stub()` handed something no seam can replace. */
30
+ export class TestStubTargetUnsupportedError extends UltimateError {
31
+ constructor(received: unknown) {
32
+ super({
33
+ code: 'X_TEST_STUB_TARGET_UNSUPPORTED',
34
+ cause: `stub() replaces the body of an action, an llm(), a query or a job, and received ${describeValue(received)}`,
35
+ fix: 'await stub(publishPost) — pass the action, llm(), query or job your module exports, never its result or its name',
36
+ });
37
+ }
38
+ }
39
+
40
+ /** The expected input of an assertion is one no call could ever have carried. */
41
+ export class TestExpectedInputInvalidError extends UltimateError {
42
+ constructor(matcher: string, name: string, issues: unknown) {
43
+ super({
44
+ code: 'X_TEST_EXPECTED_INPUT_INVALID',
45
+ cause: `${matcher} parses the expected input through "${name}"'s input schema, and it was refused: ${renderCauseValue(issues)}`,
46
+ fix: `${matcher}(<an input "${name}"'s input schema accepts>) — correct the field the issues name`,
47
+ });
48
+ }
49
+ }
50
+
51
+ /** `toHaveEnqueued` on something that is not the queue a test owns. */
52
+ export class TestRunJobsExpectedError extends UltimateError {
53
+ constructor(received: unknown) {
54
+ super({
55
+ code: 'X_TEST_RUN_JOBS_EXPECTED',
56
+ cause: `toHaveEnqueued reads the runJobs fixture's queue, and received ${describeValue(received)}`,
57
+ fix: 'unitTest(..., async ({ runJobs }) => { ...; await expect(runJobs).toHaveEnqueued(sendWelcome, { userId }); })',
58
+ });
59
+ }
60
+ }
61
+
62
+ /** `toHaveSentMail` on something that is not the outbox a test owns. */
63
+ export class TestMailExpectedError extends UltimateError {
64
+ constructor(received: unknown) {
65
+ super({
66
+ code: 'X_TEST_MAIL_EXPECTED',
67
+ cause: `toHaveSentMail reads the mail fixture's outbox, and received ${describeValue(received)}`,
68
+ fix: 'unitTest(..., async ({ mail }) => { ...; expect(mail).toHaveSentMail(welcomeMail, { to: address }); })',
69
+ });
70
+ }
71
+ }
72
+
73
+ /** `swapAdapter()` named a port with no process-global slot, or no port at all. */
74
+ export class TestAdapterPortUnswappableError extends UltimateError {
75
+ constructor(port: string, instead: Readonly<Record<string, string>>) {
76
+ const known = Object.hasOwn(instead, port) ? instead[port] : undefined;
77
+ super({
78
+ code: 'X_TEST_ADAPTER_PORT_UNSWAPPABLE',
79
+ cause:
80
+ known === undefined
81
+ ? `"${port}" is no ADAPTER_PORTS row (@ultimat3/core)`
82
+ : `"${port}" has no process-global slot a test could borrow: ${known}`,
83
+ fix: `await swapAdapter('jobs', memoryJobDriver()) — name a port SwappablePort lists, or for "${port}": ${known ?? 'pick a row of ADAPTER_PORTS'}`,
84
+ });
85
+ }
86
+ }
@@ -0,0 +1,30 @@
1
+ // Single responsibility: put a stub where a job's BODY is — `handle.run`, the one member the worker
2
+ // calls (`execute.ts`). Claim, admission, retry, the step store and settlement stay real, so a stub
3
+ // is seen by `runJobs`, a real `jobWorker` and an action's `.job()` alike.
4
+
5
+ import type { AnyJobHandle, JobRunArgs } from '@ultimat3/jobs';
6
+ import type { StubWiring } from './stub-script';
7
+ import { stubStack } from './stub-stack';
8
+ import type { Undo } from './test-scope';
9
+
10
+ type Run = (args: JobRunArgs<unknown>) => Promise<unknown>;
11
+
12
+ const push = stubStack<Run>();
13
+ /** The declared `run`, kept from the first stub on a handle until the last one is gone. */
14
+ const DECLARED = new WeakMap<object, PropertyDescriptor | undefined>();
15
+
16
+ /** Push `wiring`'s answers over `handle`'s body; the undo pops this stub and no other. */
17
+ export function stubJobBody(handle: AnyJobHandle, wiring: StubWiring<unknown, unknown>): Undo {
18
+ if (!DECLARED.has(handle)) DECLARED.set(handle, Object.getOwnPropertyDescriptor(handle, 'run'));
19
+ const run: Run = (args) => wiring.answer(args.input, args.ctx.actor);
20
+ return push(handle, run, (top) => {
21
+ if (top !== undefined) {
22
+ Object.defineProperty(handle, 'run', { configurable: true, writable: true, value: top });
23
+ return;
24
+ }
25
+ const declared = DECLARED.get(handle);
26
+ DECLARED.delete(handle);
27
+ if (declared === undefined) delete (handle as { run?: unknown }).run;
28
+ else Object.defineProperty(handle, 'run', declared);
29
+ });
30
+ }
@@ -0,0 +1,25 @@
1
+ // Single responsibility: put a stub where a query's ROWS come from, through `@ultimat3/query`'s own
2
+ // seam — the actor check, the rate limit, the input parse and the policy still run on every surface
3
+ // (a direct call, `.as()`, HTTP, MCP, a live read), and the stub answers instead of the SQL and the
4
+ // cache. Loaded only when a query is stubbed.
5
+
6
+ import type { Ctx } from '@ultimat3/core';
7
+ import type { AnyQuery } from '@ultimat3/query';
8
+ import type { StubWiring } from './stub-script';
9
+ import { stubStack } from './stub-stack';
10
+ import type { Undo } from './test-scope';
11
+
12
+ /** Stubs stack per target: a test's over a file's hands the file's back (`stub-stack.ts`). */
13
+ const push =
14
+ stubStack<(args: { readonly input: unknown; readonly ctx: Ctx }) => Promise<readonly object[]>>();
15
+
16
+ /** Push `wiring`'s rows over `target`'s reads; the undo pops this stub and no other. */
17
+ export async function stubQueryRows(
18
+ target: AnyQuery,
19
+ wiring: StubWiring<unknown, readonly object[]>,
20
+ ): Promise<Undo> {
21
+ const { overrideRows } = await import('@ultimat3/query/adapter');
22
+ const handle = (args: { readonly input: unknown; readonly ctx: Ctx }) =>
23
+ wiring.answer(args.input, args.ctx.actor);
24
+ return push(target, handle, (top) => overrideRows(target, top));
25
+ }
@@ -0,0 +1,76 @@
1
+ // Single responsibility: what a stubbed body ANSWERS and what it was ASKED — the scripted answers
2
+ // (`returns`, `throws`, played in order, the last repeated) and the call record. Which body is
3
+ // replaced, and how it is put back, is `stub.ts`'s; this module never touches a primitive.
4
+
5
+ import type { Actor, UltimateError } from '@ultimat3/core';
6
+ import type { StandardSchemaV1 } from '@ultimat3/schema';
7
+ import { TestStubUnansweredError } from './stub-errors';
8
+
9
+ /** One call the stubbed body received: the PARSED input it was handed and who was asking. */
10
+ export interface StubCall<I> {
11
+ readonly input: I;
12
+ readonly actor: Actor;
13
+ }
14
+
15
+ /**
16
+ * A primitive whose body answers from a script. `I` is the parsed input its body sees and `O` what
17
+ * its body returns — the output schema still checks every answer, on every surface.
18
+ */
19
+ export interface Stub<I, O> {
20
+ /** The primitive's registered name. */
21
+ readonly name: string;
22
+ /** Every call, oldest first. `expect(stubbed).toHaveBeenCalledWith(input)` reads it. */
23
+ readonly calls: readonly StubCall<I>[];
24
+ /** Answer `values` in order, one per call; the last one answers every call after it. */
25
+ returns(...values: readonly O[]): Stub<I, O>;
26
+ /** The next call — and, if it is the last step scripted, every call after — throws `error`. */
27
+ throws(error: UltimateError): Stub<I, O>;
28
+ }
29
+
30
+ type Step<O> =
31
+ | { readonly kind: 'value'; readonly value: O }
32
+ | { readonly kind: 'throw'; readonly error: UltimateError };
33
+
34
+ /** The half of a stub only this package reads: the body's replacement and the input schema. */
35
+ export interface StubWiring<I, O> {
36
+ readonly stub: Stub<I, O>;
37
+ /** Record the call, then play the next step. */
38
+ answer(input: I, actor: Actor): Promise<O>;
39
+ }
40
+
41
+ const SCHEMAS = new WeakMap<object, StandardSchemaV1>();
42
+
43
+ /** The input schema a stub's expected inputs are parsed by — `toHaveBeenCalledWith`'s check. */
44
+ export function stubInputSchema(value: unknown): StandardSchemaV1 | undefined {
45
+ return typeof value === 'object' && value !== null ? SCHEMAS.get(value) : undefined;
46
+ }
47
+
48
+ /** Build the script and record for one stubbed primitive, named `name`, parsed by `input`. */
49
+ export function stubScript<I, O>(name: string, input: StandardSchemaV1): StubWiring<I, O> {
50
+ const calls: StubCall<I>[] = [];
51
+ const steps: Step<O>[] = [];
52
+ let played = 0;
53
+ const stub: Stub<I, O> = {
54
+ name,
55
+ calls,
56
+ returns(...values) {
57
+ for (const value of values) steps.push({ kind: 'value', value });
58
+ return stub;
59
+ },
60
+ throws(error) {
61
+ steps.push({ kind: 'throw', error });
62
+ return stub;
63
+ },
64
+ };
65
+ SCHEMAS.set(stub, input);
66
+ return {
67
+ stub,
68
+ answer(input, actor) {
69
+ calls.push({ input, actor });
70
+ const step = steps[Math.min(played, steps.length - 1)];
71
+ played += 1;
72
+ if (step === undefined) return Promise.reject(new TestStubUnansweredError(name));
73
+ return step.kind === 'value' ? Promise.resolve(step.value) : Promise.reject(step.error);
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,29 @@
1
+ // Single responsibility: the stubs live on one target, as a stack. A test's stub over a file's
2
+ // stub answers for that test and hands the FILE's stub back when it ends — never the declared body
3
+ // — and a stub undone out of order removes only itself (frames by identity, not by position).
4
+
5
+ import type { Undo } from './test-scope';
6
+
7
+ /** Push `handle` over a target; `apply` puts the top (or, emptied, nothing) in place. */
8
+ export type StubPush<H> = (target: object, handle: H, apply: (top: H | undefined) => void) => Undo;
9
+
10
+ /** One stack per target, for one kind of seam. */
11
+ export function stubStack<H>(): StubPush<H> {
12
+ const stacks = new WeakMap<object, { readonly handle: H }[]>();
13
+ return (target, handle, apply) => {
14
+ const frames = stacks.get(target) ?? [];
15
+ stacks.set(target, frames);
16
+ // A frame per push, so one handle pushed twice is still two frames.
17
+ const frame = { handle };
18
+ frames.push(frame);
19
+ apply(handle);
20
+ let done = false;
21
+ return () => {
22
+ if (done) return;
23
+ done = true;
24
+ const at = frames.indexOf(frame);
25
+ if (at !== -1) frames.splice(at, 1);
26
+ apply(frames.at(-1)?.handle);
27
+ };
28
+ };
29
+ }