@ultimat3/testing 30.8.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 (159) hide show
  1. package/CLAUDE.md +49 -62
  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 +41 -11
  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-input.ts +22 -9
  55. package/src/exercise-override-line.ts +98 -0
  56. package/src/exercise-report.ts +30 -51
  57. package/src/exercise-sweeps.ts +3 -1
  58. package/src/exercise.ts +38 -19
  59. package/src/factories.ts +192 -179
  60. package/src/factory-api.ts +131 -0
  61. package/src/factory-associations.ts +67 -0
  62. package/src/factory-errors.ts +38 -0
  63. package/src/factory-lint.ts +92 -0
  64. package/src/factory-persist.ts +74 -16
  65. package/src/factory-pipeline.ts +191 -0
  66. package/src/factory-registry.ts +2 -1
  67. package/src/factory-types.ts +131 -0
  68. package/src/failure-store-conformance.ts +137 -0
  69. package/src/fixture-jobs.ts +50 -15
  70. package/src/fixture-mail.ts +7 -7
  71. package/src/fixture-seed.ts +111 -0
  72. package/src/fixture-statements.ts +68 -52
  73. package/src/framework-fixtures.ts +1 -1
  74. package/src/idempotency-store-conformance.ts +186 -0
  75. package/src/idempotency-store-replay-conformance.ts +140 -0
  76. package/src/idempotency-store-tx-conformance.ts +132 -0
  77. package/src/idempotency-store-world-conformance.ts +82 -0
  78. package/src/identity-provider-conformance.ts +144 -0
  79. package/src/image-transform-conformance.ts +89 -0
  80. package/src/index.ts +68 -157
  81. package/src/isr-store-conformance.ts +113 -0
  82. package/src/job-sim-effects.ts +19 -31
  83. package/src/job-sim-world.ts +6 -15
  84. package/src/lease-store-conformance.ts +195 -0
  85. package/src/mail-driver-conformance.ts +108 -0
  86. package/src/matcher-doubles.ts +104 -0
  87. package/src/matcher-stub.ts +78 -0
  88. package/src/matcher-surface.ts +21 -0
  89. package/src/matchers.ts +19 -1
  90. package/src/mcp-confirmation-store-conformance.ts +262 -0
  91. package/src/meter-store-conformance.ts +135 -0
  92. package/src/notify-digest-conformance.ts +133 -0
  93. package/src/notify-inbox-conformance.ts +130 -0
  94. package/src/notify-ledger-conformance.ts +134 -0
  95. package/src/notify-preference-conformance.ts +49 -0
  96. package/src/notify-stores-conformance.ts +73 -0
  97. package/src/outbox-store-conformance-claims.ts +112 -0
  98. package/src/outbox-store-conformance-subject.ts +65 -0
  99. package/src/outbox-store-conformance.ts +71 -0
  100. package/src/per-test-reset.ts +55 -20
  101. package/src/plan-oracle.ts +10 -3
  102. package/src/plan-sweep.ts +37 -12
  103. package/src/preload.ts +4 -2
  104. package/src/purge-conformance.ts +79 -0
  105. package/src/push-device-conformance.ts +124 -0
  106. package/src/push-subscription-conformance.ts +123 -0
  107. package/src/quiet-logs.ts +4 -4
  108. package/src/rate-limit-store-conformance.ts +178 -0
  109. package/src/registry-leak-error.ts +8 -1
  110. package/src/scale-sweep-run.ts +3 -1
  111. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  112. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  113. package/src/scrape-driver-conformance-site.ts +84 -0
  114. package/src/scrape-driver-conformance.ts +34 -0
  115. package/src/sealed-dns-resolver.ts +56 -0
  116. package/src/sealed-dns.ts +63 -64
  117. package/src/sealed-network.ts +13 -12
  118. package/src/sealed-node-sockets.ts +63 -0
  119. package/src/sealed-sockets.ts +13 -8
  120. package/src/sealed-udp.ts +118 -0
  121. package/src/search-index-conformance-list.ts +76 -0
  122. package/src/search-index-conformance-support.ts +69 -0
  123. package/src/search-index-conformance-versions.ts +66 -0
  124. package/src/search-index-conformance.ts +126 -0
  125. package/src/secret-source-conformance.ts +91 -0
  126. package/src/seed-factories.ts +57 -0
  127. package/src/seed-writer.ts +8 -19
  128. package/src/semantic-cache-factory-conformance.ts +86 -0
  129. package/src/sms-transport-conformance.ts +102 -0
  130. package/src/step-store-conformance.ts +171 -0
  131. package/src/storage-conformance-read-checks.ts +132 -0
  132. package/src/storage-conformance-shape.ts +121 -0
  133. package/src/storage-conformance-stream-checks.ts +226 -0
  134. package/src/storage-conformance.ts +34 -0
  135. package/src/stub-action.ts +24 -0
  136. package/src/stub-errors.ts +86 -0
  137. package/src/stub-job.ts +30 -0
  138. package/src/stub-query.ts +25 -0
  139. package/src/stub-script.ts +76 -0
  140. package/src/stub-stack.ts +29 -0
  141. package/src/stub.ts +73 -0
  142. package/src/swap-adapter.ts +135 -0
  143. package/src/test-scope.ts +96 -0
  144. package/src/test-types.ts +1 -1
  145. package/src/totp-replay-guard-conformance.ts +76 -0
  146. package/src/transport-conformance.ts +179 -0
  147. package/src/upload-scanner-conformance.ts +112 -0
  148. package/src/vector-store-conformance-checks.ts +174 -0
  149. package/src/vector-store-conformance.ts +21 -0
  150. package/src/cdp-connection.ts +0 -291
  151. package/src/cdp-errors.ts +0 -179
  152. package/src/cdp-launch-attempt.ts +0 -224
  153. package/src/cdp-launch-candidates.ts +0 -62
  154. package/src/cdp-launch-profile.ts +0 -106
  155. package/src/cdp-launch-reap.ts +0 -68
  156. package/src/cdp-launch-wire.ts +0 -171
  157. package/src/cdp-launch.ts +0 -175
  158. package/src/cdp-pipe.ts +0 -77
  159. package/src/cdp-wire-watch.ts +0 -113
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/testing",
3
- "version": "30.8.0",
3
+ "version": "31.0.0",
4
4
  "description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -25,6 +25,7 @@
25
25
  },
26
26
  "exports": {
27
27
  ".": "./src/index.ts",
28
+ "./conformance": "./src/conformance.ts",
28
29
  "./preload": "./src/preload.ts",
29
30
  "./e2e-preload": "./src/e2e-preload.ts",
30
31
  "./registry-isolation": "./src/registry-isolation.ts",
@@ -46,21 +47,26 @@
46
47
  "test": "bun test"
47
48
  },
48
49
  "dependencies": {
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"
50
+ "@ultimat3/action": "31.0.0",
51
+ "@ultimat3/ai": "31.0.0",
52
+ "@ultimat3/auth": "31.0.0",
53
+ "@ultimat3/cache": "31.0.0",
54
+ "@ultimat3/core": "31.0.0",
55
+ "@ultimat3/db": "31.0.0",
56
+ "@ultimat3/entity": "31.0.0",
57
+ "@ultimat3/http": "31.0.0",
58
+ "@ultimat3/i18n": "31.0.0",
59
+ "@ultimat3/jobs": "31.0.0",
60
+ "@ultimat3/mail": "31.0.0",
61
+ "@ultimat3/notify": "31.0.0",
62
+ "@ultimat3/policy": "31.0.0",
63
+ "@ultimat3/pwa": "31.0.0",
64
+ "@ultimat3/query": "31.0.0",
65
+ "@ultimat3/realtime": "31.0.0",
66
+ "@ultimat3/render": "31.0.0",
67
+ "@ultimat3/schema": "31.0.0",
68
+ "@ultimat3/scraping": "31.0.0",
69
+ "@ultimat3/seo": "31.0.0",
70
+ "@ultimat3/time": "31.0.0"
65
71
  }
66
72
  }
@@ -0,0 +1,67 @@
1
+ // What a well-formed model answer is, asserted the one way both AI suites need it: the provider's
2
+ // and the gateway's. A `GenerateResult` crosses into `llm()`, the budget ledger and the meter, so a
3
+ // float token count, a float `minor` or a refusal with no details is a defect three readers
4
+ // inherit.
5
+
6
+ import { expect } from 'bun:test';
7
+ import type { GenerateRequest, GenerateResult, StreamChunk } from '@ultimat3/ai';
8
+
9
+ const STOP_REASONS = [
10
+ 'end_turn',
11
+ 'max_tokens',
12
+ 'stop_sequence',
13
+ 'tool_use',
14
+ 'pause_turn',
15
+ 'refusal',
16
+ 'model_context_window_exceeded',
17
+ ] as const;
18
+
19
+ /** A request every model answers: one short user turn, a small ceiling. */
20
+ export const askOf = (model: string, extra: Partial<GenerateRequest> = {}): GenerateRequest => ({
21
+ model,
22
+ messages: [{ role: 'user', content: 'say hello world' }],
23
+ maxTokens: 64,
24
+ ...extra,
25
+ });
26
+
27
+ export function expectWellFormed(result: GenerateResult, model: string): void {
28
+ expect(result.model).toBe(model);
29
+ expect(typeof result.text).toBe('string');
30
+ expect(Array.isArray(result.toolCalls)).toBe(true);
31
+ for (const call of result.toolCalls) {
32
+ expect(typeof call.id).toBe('string');
33
+ expect(
34
+ typeof call.input === 'object' && call.input !== null && !Array.isArray(call.input),
35
+ ).toBe(true);
36
+ }
37
+ expect(STOP_REASONS as readonly string[]).toContain(result.stopReason);
38
+ // Required on a refusal, absent otherwise: it is the one field that says another model might
39
+ // answer.
40
+ if (result.stopReason === 'refusal') expect(result.stopDetails?.type).toBe('refusal');
41
+ else expect(result.stopDetails).toBeUndefined();
42
+ for (const count of Object.values(result.usage)) {
43
+ expect(Number.isSafeInteger(count) && count >= 0).toBe(true);
44
+ }
45
+ expect(Number.isSafeInteger(result.cost.minor) && result.cost.minor >= 0).toBe(true);
46
+ expect(result.cost.currency).toMatch(/^[A-Z]{3}$/);
47
+ }
48
+
49
+ /** Every chunk a stream yields, in order. */
50
+ export async function drained(chunks: AsyncIterable<StreamChunk>): Promise<StreamChunk[]> {
51
+ const seen: StreamChunk[] = [];
52
+ for await (const chunk of chunks) seen.push(chunk);
53
+ return seen;
54
+ }
55
+
56
+ /** Exactly one `done`, last, well-formed — and the text deltas before it spell its text. */
57
+ export function expectStreamed(chunks: readonly StreamChunk[], model: string): GenerateResult {
58
+ const done = chunks.filter((chunk) => chunk.type === 'done');
59
+ expect(done).toHaveLength(1);
60
+ const last = chunks.at(-1);
61
+ if (last?.type !== 'done') return expect.unreachable('the stream did not end on its done chunk');
62
+ expectWellFormed(last.result, model);
63
+ const spelled = chunks.flatMap((chunk) => (chunk.type === 'text' ? [chunk.text] : [])).join('');
64
+ // Trailing whitespace aside: `echoProvider` streams one word per chunk, each with its space.
65
+ expect(spelled.trimEnd()).toBe(last.result.text.trimEnd());
66
+ return last.result;
67
+ }
@@ -0,0 +1,105 @@
1
+ // The `aiGateway` port's contract as shared examples: `behavesLike(gatewayConformance, () => ({
2
+ // gateway, model }))` — `model` registered and served, answered with a turn that costs something.
3
+ // The budget half is the point: `llm()`, `agent()` and `hive()` debit through `scope`, `spent` and
4
+ // `callLedger`, and a gateway that answers well and books nothing runs every app ceiling at zero.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { ModelId } from '@ultimat3/ai';
8
+ import type { Gateway } from '@ultimat3/ai/adapter';
9
+ import { isUltimateError } from '@ultimat3/core';
10
+ import { askOf, drained, expectStreamed, expectWellFormed } from './ai-conformance-answer';
11
+ import type { SharedExamples } from './shared-examples';
12
+ import { sharedExamples } from './shared-examples';
13
+
14
+ export interface GatewaySubject {
15
+ readonly gateway: Gateway;
16
+ /** Registered, served by the gateway, and answered at a cost above zero. */
17
+ readonly model: ModelId;
18
+ }
19
+
20
+ export interface GatewayCheck {
21
+ readonly name: string;
22
+ run(subject: GatewaySubject): Promise<void>;
23
+ }
24
+
25
+ let minted = 0;
26
+ const actorKey = (): string => {
27
+ minted += 1;
28
+ return `actor:conformance:${process.pid.toString(36)}-${minted.toString(36)}`;
29
+ };
30
+
31
+ const codeOf = (pending: Promise<unknown>): Promise<string> =>
32
+ pending.then(
33
+ () => 'answered',
34
+ (error: unknown) => (isUltimateError(error) ? error.code : `not coded: ${String(error)}`),
35
+ );
36
+
37
+ export const GATEWAY_CHECKS: readonly GatewayCheck[] = [
38
+ {
39
+ name: 'generate answers a well-formed result for the model it was asked',
40
+ async run({ gateway, model }) {
41
+ expectWellFormed(await gateway.generate(askOf(model)), model);
42
+ },
43
+ },
44
+ {
45
+ name: 'stream ends on exactly one done chunk, whose text the deltas before it spell',
46
+ async run({ gateway, model }) {
47
+ expectStreamed(await drained(gateway.stream(askOf(model))), model);
48
+ },
49
+ },
50
+ {
51
+ name: 'outside a scope nothing is spent; inside one a call is spent, in its own currency',
52
+ async run({ gateway, model }) {
53
+ expect((await gateway.spent()).minor).toBe(0);
54
+ const [result, spent] = await gateway.scope({ actorKey: actorKey() }, async () => {
55
+ const answer = await gateway.generate(askOf(model));
56
+ return [answer, await gateway.spent()] as const;
57
+ });
58
+ expect(result.cost.minor).toBeGreaterThan(0);
59
+ expect(spent).toEqual({ minor: result.cost.minor, currency: result.cost.currency });
60
+ expect((await gateway.spent()).minor).toBe(0);
61
+ },
62
+ },
63
+ {
64
+ name: 'calls inside one scope share its ledger, a streamed one included',
65
+ async run({ gateway, model }) {
66
+ const [one, two] = await gateway.scope({ actorKey: actorKey() }, async () => {
67
+ await gateway.generate(askOf(model));
68
+ const once = await gateway.spent();
69
+ await drained(gateway.stream(askOf(model)));
70
+ return [once, await gateway.spent()] as const;
71
+ });
72
+ expect(one.minor).toBeGreaterThan(0);
73
+ expect(two.minor).toBeGreaterThan(one.minor);
74
+ },
75
+ },
76
+ {
77
+ name: "callLedger reports a ledger for the caller's keys, in Money",
78
+ async run({ gateway }) {
79
+ const report = await gateway.callLedger({ actorKey: actorKey() }).report();
80
+ expect(Number.isSafeInteger(report.cost.minor)).toBe(true);
81
+ expect(report.cost.currency).toMatch(/^[A-Z]{3}$/);
82
+ },
83
+ },
84
+ {
85
+ name: 'a maxTokens that is not a whole number is refused X_INVARIANT, on both calls',
86
+ async run({ gateway, model }) {
87
+ const bad = askOf(model, { maxTokens: Number.NaN });
88
+ expect([
89
+ await codeOf(gateway.generate(bad)),
90
+ await codeOf(drained(gateway.stream(bad))),
91
+ ]).toEqual(['X_INVARIANT', 'X_INVARIANT']);
92
+ },
93
+ },
94
+ ];
95
+
96
+ export const gatewayConformance: SharedExamples<GatewaySubject> = sharedExamples(
97
+ 'an AI gateway',
98
+ (subject) => {
99
+ for (const check of GATEWAY_CHECKS) {
100
+ test(check.name, async () => {
101
+ await check.run(subject());
102
+ });
103
+ }
104
+ },
105
+ );
@@ -0,0 +1,69 @@
1
+ // `@ultimat3/ai`'s `Provider` contract as shared examples: `behavesLike(providerConformance, () =>
2
+ // ({ provider, model }))` — `model` registered and listed, answered with an ordinary text turn.
3
+ // What it answers is the provider's; the SHAPE is the port's. HTTP: `providerTransportConformance`.
4
+
5
+ import { expect, test } from 'bun:test';
6
+ import type { ModelId, Provider } from '@ultimat3/ai';
7
+ import { isUltimateError } from '@ultimat3/core';
8
+ import { askOf, drained, expectStreamed, expectWellFormed } from './ai-conformance-answer';
9
+ import type { SharedExamples } from './shared-examples';
10
+ import { sharedExamples } from './shared-examples';
11
+
12
+ export interface ProviderSubject {
13
+ readonly provider: Provider;
14
+ readonly model: ModelId;
15
+ }
16
+
17
+ export interface ProviderCheck {
18
+ readonly name: string;
19
+ run(subject: ProviderSubject): Promise<void>;
20
+ }
21
+
22
+ const failureOf = (pending: Promise<unknown>): Promise<unknown> =>
23
+ pending.then(
24
+ () => 'answered',
25
+ (error: unknown) => error,
26
+ );
27
+
28
+ export const PROVIDER_CHECKS: readonly ProviderCheck[] = [
29
+ {
30
+ name: 'it has a name and lists the model it serves',
31
+ async run({ provider, model }) {
32
+ expect(provider.name.length).toBeGreaterThan(0);
33
+ expect(provider.models).toContain(model);
34
+ },
35
+ },
36
+ {
37
+ name: 'generate answers a well-formed result for the model it was asked',
38
+ async run({ provider, model }) {
39
+ expectWellFormed(await provider.generate(askOf(model)), model);
40
+ },
41
+ },
42
+ {
43
+ name: 'stream ends on exactly one done chunk, whose text the deltas before it spell',
44
+ async run({ provider, model }) {
45
+ expectStreamed(await drained(provider.stream(askOf(model))), model);
46
+ },
47
+ },
48
+ {
49
+ name: 'a request naming no model is refused X_AI_MODEL_UNRESOLVED — a provider picks none',
50
+ async run({ provider }) {
51
+ const request = { messages: [{ role: 'user' as const, content: 'hi' }], maxTokens: 16 };
52
+ const refused = await failureOf(provider.generate(request));
53
+ expect(isUltimateError(refused) ? refused.code : String(refused)).toBe(
54
+ 'X_AI_MODEL_UNRESOLVED',
55
+ );
56
+ },
57
+ },
58
+ ];
59
+
60
+ export const providerConformance: SharedExamples<ProviderSubject> = sharedExamples(
61
+ 'an AI provider',
62
+ (subject) => {
63
+ for (const check of PROVIDER_CHECKS) {
64
+ test(check.name, async () => {
65
+ await check.run(subject());
66
+ });
67
+ }
68
+ },
69
+ );
@@ -0,0 +1,170 @@
1
+ // The socket half of the `Provider` contract, over `@ultimat3/ai`'s `AiFetch` seam:
2
+ // `behavesLike(providerTransportConformance, () => ({ model, overHttp }))`. Lifted from
3
+ // `ai/src/provider-parity*.test.ts`: the abort reaches the socket, an echoed key never leaves it, an
4
+ // endless error body ends, an overflow is its own code. Error bodies are `{ error: { message } }`.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { AiFetch, GenerateRequest, ModelId, Provider } from '@ultimat3/ai';
8
+ import { isUltimateError } from '@ultimat3/core';
9
+ import { askOf, drained } from './ai-conformance-answer';
10
+ import type { SharedExamples } from './shared-examples';
11
+ import { sharedExamples } from './shared-examples';
12
+
13
+ export interface ProviderTransportSubject {
14
+ readonly model: ModelId;
15
+ /** The provider under test, every request sent through `fetch`, authenticated with `apiKey`. */
16
+ overHttp(fetch: AiFetch, apiKey: string): Provider;
17
+ }
18
+
19
+ export interface ProviderTransportCheck {
20
+ readonly name: string;
21
+ run(subject: ProviderTransportSubject): Promise<void>;
22
+ }
23
+
24
+ const KEY = 'sk-live-do-not-log-me';
25
+ const OVERFLOWS = [
26
+ 'prompt is too long: 210000 tokens > 200000 maximum',
27
+ "This model's maximum context length is 128000 tokens. However, your messages resulted in 130211 tokens.",
28
+ ];
29
+
30
+ const answering =
31
+ (status: number, message: string): AiFetch =>
32
+ async () =>
33
+ new Response(JSON.stringify({ error: { type: 'invalid_request_error', message } }), {
34
+ status,
35
+ headers: { 'content-type': 'application/json' },
36
+ });
37
+
38
+ /** Both calls the port has, each settled to what it threw. */
39
+ function bothPaths(provider: Provider, request: GenerateRequest): Promise<unknown>[] {
40
+ return [provider.generate(request), drained(provider.stream(request))].map((pending) =>
41
+ pending.then(
42
+ () => 'answered',
43
+ (error: unknown) => error,
44
+ ),
45
+ );
46
+ }
47
+
48
+ const codeOf = (error: unknown): string =>
49
+ isUltimateError(error) ? error.code : `not an UltimateError: ${String(error)}`;
50
+ const statusOf = (error: unknown): unknown =>
51
+ typeof error === 'object' && error !== null ? Reflect.get(error, 'status') : undefined;
52
+
53
+ export const PROVIDER_TRANSPORT_CHECKS: readonly ProviderTransportCheck[] = [
54
+ {
55
+ name: "the caller's abort signal reaches fetch, generating and streaming",
56
+ async run({ model, overHttp }) {
57
+ const seen: unknown[] = [];
58
+ const provider = overHttp(async (_url, init) => {
59
+ seen.push(init.signal);
60
+ return new Response('{"error":{"message":"stop here"}}', { status: 503 });
61
+ }, KEY);
62
+ const signal = new AbortController().signal;
63
+ await Promise.all(bothPaths(provider, askOf(model, { signal })));
64
+ expect(seen).toEqual([signal, signal]);
65
+ },
66
+ },
67
+ {
68
+ name: 'a request with no signal hands fetch none, rather than an explicit undefined',
69
+ async run({ model, overHttp }) {
70
+ const inits: RequestInit[] = [];
71
+ const provider = overHttp(async (_url, init) => {
72
+ inits.push(init);
73
+ return new Response('{}', { status: 503 });
74
+ }, KEY);
75
+ await Promise.all(bothPaths(provider, askOf(model)));
76
+ expect(inits.map((init) => 'signal' in init)).toEqual([false, false]);
77
+ },
78
+ },
79
+ {
80
+ name: 'a 4xx body echoing the key is a coded failure that never carries the key',
81
+ async run({ model, overHttp }) {
82
+ const provider = overHttp(answering(400, `rejected header x-api-key: ${KEY}`), KEY);
83
+ for (const failure of await Promise.all(bothPaths(provider, askOf(model)))) {
84
+ expect([codeOf(failure), statusOf(failure)]).toEqual(['X_AI_PROVIDER_UNAVAILABLE', 400]);
85
+ expect(JSON.stringify(failure)).not.toContain(KEY);
86
+ expect(isUltimateError(failure) ? failure.message : KEY).not.toContain(KEY);
87
+ }
88
+ },
89
+ },
90
+ {
91
+ name: 'an endless 503 body ends in a coded failure, read only as far as the detail needs',
92
+ async run({ model, overHttp }) {
93
+ let pulled = 0;
94
+ const provider = overHttp(
95
+ async () =>
96
+ new Response(
97
+ new ReadableStream<Uint8Array>({
98
+ pull(controller) {
99
+ pulled += 1;
100
+ controller.enqueue(new TextEncoder().encode('x'.repeat(1024)));
101
+ },
102
+ }),
103
+ { status: 503 },
104
+ ),
105
+ KEY,
106
+ );
107
+ const failure = await provider.generate(askOf(model)).catch((error: unknown) => error);
108
+ expect([codeOf(failure), statusOf(failure)]).toEqual(['X_AI_PROVIDER_UNAVAILABLE', 503]);
109
+ expect(pulled).toBeLessThan(10);
110
+ },
111
+ },
112
+ {
113
+ name: "a prompt over the window is X_AI_CONTEXT_OVERFLOW in either vendor's words, 400 or 413",
114
+ async run({ model, overHttp }) {
115
+ for (const message of OVERFLOWS) {
116
+ for (const status of [400, 413]) {
117
+ const provider = overHttp(answering(status, message), KEY);
118
+ for (const failure of await Promise.all(bothPaths(provider, askOf(model)))) {
119
+ expect(codeOf(failure)).toBe('X_AI_CONTEXT_OVERFLOW');
120
+ }
121
+ }
122
+ }
123
+ },
124
+ },
125
+ {
126
+ name: 'a 400 about anything else, or the overflow words on a 5xx, stays the transport code',
127
+ async run({ model, overHttp }) {
128
+ for (const [status, message] of [
129
+ [400, 'tools.0.input_schema: type must be object'],
130
+ [503, OVERFLOWS[0] ?? ''],
131
+ ] as const) {
132
+ const provider = overHttp(answering(status, message), KEY);
133
+ for (const failure of await Promise.all(bothPaths(provider, askOf(model)))) {
134
+ expect([codeOf(failure), statusOf(failure)]).toEqual([
135
+ 'X_AI_PROVIDER_UNAVAILABLE',
136
+ status,
137
+ ]);
138
+ }
139
+ }
140
+ },
141
+ },
142
+ {
143
+ name: 'a request the wire cannot carry is refused before the socket',
144
+ async run({ model, overHttp }) {
145
+ let sent = 0;
146
+ const provider = overHttp(async () => {
147
+ sent += 1;
148
+ return new Response('{}');
149
+ }, KEY);
150
+ const pdf = { type: 'base64', media_type: 'application/pdf', data: 'aGVsbG8=' } as const;
151
+ const failure = await provider
152
+ .generate({
153
+ model,
154
+ messages: [{ role: 'assistant', content: [{ type: 'document', source: pdf }] }],
155
+ maxTokens: 16,
156
+ })
157
+ .catch((error: unknown) => error);
158
+ expect([codeOf(failure), sent]).toEqual(['X_AI_CONTENT_UNSUPPORTED', 0]);
159
+ },
160
+ },
161
+ ];
162
+
163
+ export const providerTransportConformance: SharedExamples<ProviderTransportSubject> =
164
+ sharedExamples('an AI provider over HTTP', (subject) => {
165
+ for (const check of PROVIDER_TRANSPORT_CHECKS) {
166
+ test(check.name, async () => {
167
+ await check.run(subject());
168
+ });
169
+ }
170
+ });
@@ -0,0 +1,204 @@
1
+ // The `AuditSink` contract of `@ultimat3/core` as shared examples, for a sink of your own:
2
+ // `behavesLike(auditSinkConformance, () => subject)`. The port is one `write`, so a subject hands
3
+ // back what its storage KEPT, as facts; the suite asks every sink the same questions of them.
4
+
5
+ import { expect, test } from 'bun:test';
6
+ import { ctxOf, secret, userActor } from '@ultimat3/core';
7
+ import type { AuditRecord, AuditSink } from '@ultimat3/core/adapter';
8
+ import type { SharedExamples } from './shared-examples';
9
+ import { sharedExamples } from './shared-examples';
10
+
11
+ type Maybe<T> = T | Promise<T>;
12
+
13
+ /** What a sink kept of one record: the framework's facts, none of the storage. */
14
+ export interface AuditKept {
15
+ readonly name: string;
16
+ readonly primitive: string;
17
+ readonly outcome: string;
18
+ readonly surface: string;
19
+ readonly mutator: boolean;
20
+ readonly replayed: boolean;
21
+ readonly idempotencyKey: string | null;
22
+ readonly failureCode: string | null;
23
+ readonly actorId: string;
24
+ readonly actorKind: string;
25
+ readonly orgId: string | null;
26
+ readonly requestId: string;
27
+ readonly traceId: string;
28
+ readonly locale: string;
29
+ readonly tz: string;
30
+ readonly buildId: string;
31
+ readonly role: string;
32
+ /** `at`, as an ISO-8601 instant. */
33
+ readonly at: string;
34
+ /** The input as stored — any shape; the suite only reads its JSON. */
35
+ readonly input: unknown;
36
+ }
37
+
38
+ export interface AuditSinkSubject {
39
+ readonly sink: AuditSink;
40
+ /** Every record this sink kept under `name`, oldest first. */
41
+ kept(name: string): Promise<readonly AuditKept[]>;
42
+ /**
43
+ * True when the sink writes somewhere that outlives the process — then a credential-named input
44
+ * key must never reach it. A process-memory sink keeps the record verbatim and says `false`.
45
+ */
46
+ readonly persists: boolean;
47
+ }
48
+
49
+ export interface AuditSinkCheck {
50
+ readonly name: string;
51
+ run(subject: AuditSinkSubject): Promise<void>;
52
+ }
53
+
54
+ const AT = new Date(1_700_000_000_000);
55
+
56
+ let minted = 0;
57
+ const nameOf = (): string => {
58
+ minted += 1;
59
+ return `conformance${process.pid.toString(36)}x${minted.toString(36)}`;
60
+ };
61
+
62
+ /** Every string field a DIFFERENT value: a sink that files one fact under another is caught. */
63
+ const recordFor = (name: string, over: Partial<AuditRecord> = {}): AuditRecord => ({
64
+ at: AT,
65
+ name,
66
+ primitive: 'action',
67
+ mutator: true,
68
+ surface: 'http',
69
+ ctx: ctxOf({
70
+ requestId: 'req-1',
71
+ traceId: '0af7651916cd43dd8448eb211c80319c',
72
+ locale: 'es-ES',
73
+ tz: 'Europe/Madrid',
74
+ buildId: 'build-7',
75
+ actor: userActor({ id: 'u1', orgId: 'org-1' }),
76
+ }),
77
+ input: { postId: 'p1' },
78
+ idempotencyKey: null,
79
+ replayed: false,
80
+ outcome: 'allowed',
81
+ failure: null,
82
+ ...over,
83
+ });
84
+
85
+ /** The facts a sink must keep of `record`, input aside. */
86
+ const factsOf = (record: AuditRecord): Omit<AuditKept, 'input'> => ({
87
+ name: record.name,
88
+ primitive: record.primitive,
89
+ outcome: record.outcome,
90
+ surface: record.surface,
91
+ mutator: record.mutator,
92
+ replayed: record.replayed,
93
+ idempotencyKey: record.idempotencyKey,
94
+ failureCode: record.failure?.code ?? null,
95
+ actorId: record.ctx.actor.id,
96
+ actorKind: record.ctx.actor.kind,
97
+ orgId: record.ctx.actor.orgId ?? null,
98
+ requestId: record.ctx.requestId,
99
+ traceId: record.ctx.traceId,
100
+ locale: record.ctx.locale,
101
+ tz: record.ctx.tz,
102
+ buildId: record.ctx.buildId,
103
+ role: record.ctx.role,
104
+ at: record.at.toISOString(),
105
+ });
106
+
107
+ const only = async (subject: AuditSinkSubject, name: string): Promise<AuditKept> => {
108
+ const kept = await subject.kept(name);
109
+ expect(kept).toHaveLength(1);
110
+ return kept[0] as AuditKept;
111
+ };
112
+
113
+ const VARIANTS: readonly (readonly [string, Partial<AuditRecord>])[] = [
114
+ ['an allowed attempt', {}],
115
+ [
116
+ 'a DENIED attempt',
117
+ { outcome: 'denied', failure: { code: 'X_FORBIDDEN', error: new RangeError('no') } },
118
+ ],
119
+ [
120
+ 'a failed attempt whose thrown value carries no code',
121
+ { outcome: 'failed', failure: { code: null, error: 'a string nobody threw twice' } },
122
+ ],
123
+ ['a replayed idempotent call', { idempotencyKey: 'publishPost:k1', replayed: true }],
124
+ ['an audited READ, from the query primitive', { primitive: 'query', mutator: false }],
125
+ [
126
+ "a job's own write, from the job primitive",
127
+ { primitive: 'job', mutator: false, surface: 'job' },
128
+ ],
129
+ [
130
+ 'an input that never parsed',
131
+ { input: undefined, outcome: 'failed', failure: { code: 'X_INPUT_INVALID', error: null } },
132
+ ],
133
+ ];
134
+
135
+ export const AUDIT_SINK_CHECKS: readonly AuditSinkCheck[] = [
136
+ ...VARIANTS.map(
137
+ ([label, over]): AuditSinkCheck => ({
138
+ name: `keeps every fact of ${label}`,
139
+ async run(subject) {
140
+ const record = recordFor(nameOf(), over);
141
+ await subject.sink.write(record);
142
+ const kept = await only(subject, record.name);
143
+ const { input: _input, ...facts } = kept;
144
+ expect(facts).toEqual(factsOf(record));
145
+ },
146
+ }),
147
+ ),
148
+ {
149
+ name: 'two identical attempts are two records, never collapsed',
150
+ async run(subject) {
151
+ const record = recordFor(nameOf());
152
+ await subject.sink.write(record);
153
+ await subject.sink.write(record);
154
+ expect(await subject.kept(record.name)).toHaveLength(2);
155
+ },
156
+ },
157
+ {
158
+ name: 'a bigint, a cycle, a Secret and a Date land without a throw, and without a secret',
159
+ async run(subject) {
160
+ const cyclic: Record<string, unknown> = { note: 'a' };
161
+ cyclic['self'] = cyclic;
162
+ const record = recordFor(nameOf(), {
163
+ input: { total: 10n, cyclic, password: 'hunter2', token: secret('sk_live'), when: AT },
164
+ });
165
+ // A sink that throws turns a committed handler into a failed invocation.
166
+ await subject.sink.write(record);
167
+ const kept = await only(subject, record.name);
168
+ if (!subject.persists) return;
169
+ // Whatever a persisting sink falls back to for an unserialisable input, no secret rides it.
170
+ const stored = JSON.stringify(kept.input) ?? '';
171
+ expect(stored).not.toContain('hunter2');
172
+ expect(stored).not.toContain('sk_live');
173
+ },
174
+ },
175
+ {
176
+ name: 'a persisting sink never stores a credential-named input key, from a read or a write',
177
+ async run(subject) {
178
+ for (const primitive of ['action', 'query', 'job'] as const) {
179
+ const record = recordFor(nameOf(), {
180
+ primitive,
181
+ mutator: false,
182
+ input: { limit: 5, apiKey: 'sk_live_read', nested: { password: 'hunter2' } },
183
+ });
184
+ await subject.sink.write(record);
185
+ const stored = JSON.stringify((await only(subject, record.name)).input);
186
+ if (!subject.persists) continue;
187
+ expect(stored).toContain('"limit":5');
188
+ expect(stored).not.toContain('sk_live_read');
189
+ expect(stored).not.toContain('hunter2');
190
+ }
191
+ },
192
+ },
193
+ ];
194
+
195
+ export const auditSinkConformance: SharedExamples<Maybe<AuditSinkSubject>> = sharedExamples(
196
+ 'an audit sink',
197
+ (subject) => {
198
+ for (const check of AUDIT_SINK_CHECKS) {
199
+ test(check.name, async () => {
200
+ await check.run(await subject());
201
+ });
202
+ }
203
+ },
204
+ );