@ultimat3/testing 30.9.0 → 31.1.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 (151) 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 +138 -115
  56. package/src/exercise-room-mail.ts +40 -0
  57. package/src/exercise.ts +33 -29
  58. package/src/factories.ts +192 -179
  59. package/src/factory-api.ts +131 -0
  60. package/src/factory-associations.ts +67 -0
  61. package/src/factory-errors.ts +38 -0
  62. package/src/factory-lint.ts +92 -0
  63. package/src/factory-persist.ts +74 -16
  64. package/src/factory-pipeline.ts +191 -0
  65. package/src/factory-registry.ts +2 -1
  66. package/src/factory-types.ts +131 -0
  67. package/src/failure-store-conformance.ts +137 -0
  68. package/src/fixture-jobs.ts +27 -11
  69. package/src/fixture-mail.ts +7 -7
  70. package/src/fixture-seed.ts +111 -0
  71. package/src/fixture-statements.ts +68 -52
  72. package/src/framework-fixtures.ts +1 -1
  73. package/src/idempotency-store-conformance.ts +186 -0
  74. package/src/idempotency-store-replay-conformance.ts +140 -0
  75. package/src/idempotency-store-tx-conformance.ts +132 -0
  76. package/src/idempotency-store-world-conformance.ts +82 -0
  77. package/src/identity-provider-conformance.ts +144 -0
  78. package/src/image-transform-conformance.ts +89 -0
  79. package/src/index.ts +68 -157
  80. package/src/isr-store-conformance.ts +113 -0
  81. package/src/job-sim-effects.ts +19 -31
  82. package/src/job-sim-world.ts +6 -15
  83. package/src/lease-store-conformance.ts +195 -0
  84. package/src/mail-driver-conformance.ts +108 -0
  85. package/src/matcher-doubles.ts +104 -0
  86. package/src/matcher-stub.ts +78 -0
  87. package/src/matcher-surface.ts +21 -0
  88. package/src/matchers.ts +19 -1
  89. package/src/mcp-confirmation-store-conformance.ts +262 -0
  90. package/src/meter-store-conformance.ts +135 -0
  91. package/src/notify-digest-conformance.ts +133 -0
  92. package/src/notify-inbox-conformance.ts +130 -0
  93. package/src/notify-ledger-conformance.ts +134 -0
  94. package/src/notify-preference-conformance.ts +49 -0
  95. package/src/notify-stores-conformance.ts +73 -0
  96. package/src/outbox-store-conformance-claims.ts +112 -0
  97. package/src/outbox-store-conformance-subject.ts +65 -0
  98. package/src/outbox-store-conformance.ts +71 -0
  99. package/src/per-test-reset.ts +55 -20
  100. package/src/preload.ts +4 -2
  101. package/src/purge-conformance.ts +79 -0
  102. package/src/push-device-conformance.ts +124 -0
  103. package/src/push-subscription-conformance.ts +123 -0
  104. package/src/quiet-logs.ts +4 -4
  105. package/src/rate-limit-store-conformance.ts +178 -0
  106. package/src/registry-leak-error.ts +8 -1
  107. package/src/scale-sweep-run.ts +6 -9
  108. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  109. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  110. package/src/scrape-driver-conformance-site.ts +84 -0
  111. package/src/scrape-driver-conformance.ts +34 -0
  112. package/src/sealed-network.ts +20 -2
  113. package/src/search-index-conformance-list.ts +76 -0
  114. package/src/search-index-conformance-support.ts +69 -0
  115. package/src/search-index-conformance-versions.ts +66 -0
  116. package/src/search-index-conformance.ts +126 -0
  117. package/src/secret-source-conformance.ts +91 -0
  118. package/src/seed-factories.ts +57 -0
  119. package/src/seed-writer.ts +8 -19
  120. package/src/semantic-cache-factory-conformance.ts +86 -0
  121. package/src/sms-transport-conformance.ts +102 -0
  122. package/src/step-store-conformance.ts +171 -0
  123. package/src/storage-conformance-read-checks.ts +132 -0
  124. package/src/storage-conformance-shape.ts +121 -0
  125. package/src/storage-conformance-stream-checks.ts +226 -0
  126. package/src/storage-conformance.ts +34 -0
  127. package/src/stub-action.ts +24 -0
  128. package/src/stub-errors.ts +86 -0
  129. package/src/stub-job.ts +30 -0
  130. package/src/stub-query.ts +25 -0
  131. package/src/stub-script.ts +76 -0
  132. package/src/stub-stack.ts +29 -0
  133. package/src/stub.ts +73 -0
  134. package/src/swap-adapter.ts +135 -0
  135. package/src/test-scope.ts +96 -0
  136. package/src/test-types.ts +1 -1
  137. package/src/totp-replay-guard-conformance.ts +76 -0
  138. package/src/transport-conformance.ts +179 -0
  139. package/src/upload-scanner-conformance.ts +112 -0
  140. package/src/vector-store-conformance-checks.ts +174 -0
  141. package/src/vector-store-conformance.ts +21 -0
  142. package/src/cdp-connection.ts +0 -291
  143. package/src/cdp-errors.ts +0 -179
  144. package/src/cdp-launch-attempt.ts +0 -224
  145. package/src/cdp-launch-candidates.ts +0 -62
  146. package/src/cdp-launch-profile.ts +0 -106
  147. package/src/cdp-launch-reap.ts +0 -68
  148. package/src/cdp-launch-wire.ts +0 -171
  149. package/src/cdp-launch.ts +0 -175
  150. package/src/cdp-pipe.ts +0 -77
  151. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,126 @@
1
+ // The `searchIndex` port's contract as shared examples: `behavesLike(searchIndexConformance, () =>
2
+ // ({ index, entity, store, drop }))`. `store`/`drop` write the SOURCE rows (the built-in Postgres
3
+ // index reads its table; an external one ignores them), then the suite calls `index`/`remove` as
4
+ // `reindex` and a write hook do. Words are chosen no English stemmer rewrites, so every index agrees.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { SearchScope } from '@ultimat3/entity/adapter';
8
+ import { SEARCH_INDEX_LIST_CHECKS } from './search-index-conformance-list';
9
+ import type { SearchIndexCheck, SearchIndexSubject } from './search-index-conformance-support';
10
+ import {
11
+ searchDoc as doc,
12
+ putSearchDocs,
13
+ SEARCH_TENANT_A,
14
+ SEARCH_TENANT_B,
15
+ searchDocId,
16
+ searchIds,
17
+ } from './search-index-conformance-support';
18
+ import { SEARCH_INDEX_VERSION_CHECKS } from './search-index-conformance-versions';
19
+ import type { SharedExamples } from './shared-examples';
20
+ import { sharedExamples } from './shared-examples';
21
+
22
+ export const SEARCH_INDEX_CHECKS: readonly SearchIndexCheck[] = [
23
+ {
24
+ name: 'an indexed document is found by a word of any field, whatever its case',
25
+ async run(subject) {
26
+ expect(subject.index.name.length).toBeGreaterThan(0);
27
+ await putSearchDocs(subject, [
28
+ doc(subject.entity, 1, 'Zebra crossing', { body: 'a lantern harbour' }),
29
+ ]);
30
+ expect(await searchIds(subject, 'zebra')).toEqual([searchDocId(1)]);
31
+ expect(await searchIds(subject, 'HARBOUR')).toEqual([searchDocId(1)]);
32
+ },
33
+ },
34
+ {
35
+ name: 'every word of the term must match',
36
+ async run(subject) {
37
+ await putSearchDocs(subject, [
38
+ doc(subject.entity, 1, 'zebra quokka'),
39
+ doc(subject.entity, 2, 'zebra lantern'),
40
+ ]);
41
+ expect(await searchIds(subject, 'zebra quokka')).toEqual([searchDocId(1)]);
42
+ expect(await searchIds(subject, 'zebra')).toEqual([searchDocId(1), searchDocId(2)]);
43
+ },
44
+ },
45
+ {
46
+ name: 'no match, an empty term and bare punctuation answer no hits, never an error',
47
+ async run(subject) {
48
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'zebra')]);
49
+ for (const term of ['walrus', '', ' ', '|||', '(((']) {
50
+ expect(await searchIds(subject, term), term).toEqual([]);
51
+ }
52
+ },
53
+ },
54
+ {
55
+ name: "a tenant is never answered another tenant's document",
56
+ async run(subject) {
57
+ await putSearchDocs(subject, [
58
+ doc(subject.entity, 1, 'zebra'),
59
+ doc(subject.entity, 2, 'zebra', { tenant: SEARCH_TENANT_B }),
60
+ ]);
61
+ expect(await searchIds(subject, 'zebra')).toEqual([searchDocId(1)]);
62
+ expect(await searchIds(subject, 'zebra', SEARCH_TENANT_B)).toEqual([searchDocId(2)]);
63
+ },
64
+ },
65
+ {
66
+ name: 'indexing a newer version of an id replaces its text, and it is one hit',
67
+ async run(subject) {
68
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'zebra')]);
69
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'quokka zebra', { version: 2 })]);
70
+ expect(await searchIds(subject, 'zebra')).toEqual([searchDocId(1)]);
71
+ await putSearchDocs(subject, [doc(subject.entity, 1, 'lantern', { version: 3 })]);
72
+ expect(await searchIds(subject, 'zebra')).toEqual([]);
73
+ expect(await searchIds(subject, 'lantern')).toEqual([searchDocId(1)]);
74
+ },
75
+ },
76
+ {
77
+ name: "a removed id is gone, and a removal under another tenant leaves this one's",
78
+ async run(subject) {
79
+ await putSearchDocs(subject, [
80
+ doc(subject.entity, 1, 'zebra'),
81
+ doc(subject.entity, 2, 'zebra'),
82
+ ]);
83
+ const other: SearchScope = { entity: subject.entity, tenant: SEARCH_TENANT_B };
84
+ await subject.drop(other, [searchDocId(1)]);
85
+ await subject.index.remove(other, [searchDocId(1)], 2);
86
+ expect(await searchIds(subject, 'zebra')).toEqual([searchDocId(1), searchDocId(2)]);
87
+ const own: SearchScope = { entity: subject.entity, tenant: SEARCH_TENANT_A };
88
+ await subject.drop(own, [searchDocId(1)]);
89
+ await subject.index.remove(own, [searchDocId(1)], 2);
90
+ expect(await searchIds(subject, 'zebra')).toEqual([searchDocId(2)]);
91
+ },
92
+ },
93
+ {
94
+ name: 'the limit bounds the hits, each id at most once',
95
+ async run(subject) {
96
+ await putSearchDocs(
97
+ subject,
98
+ [1, 2, 3].map((n) => doc(subject.entity, n, `zebra ${'quokka '.repeat(n)}`)),
99
+ );
100
+ const hits = await subject.index.query({
101
+ entity: subject.entity,
102
+ tenant: SEARCH_TENANT_A,
103
+ term: 'zebra',
104
+ limit: 2,
105
+ });
106
+ expect(hits.length).toBe(2);
107
+ expect(new Set(hits.map((hit) => hit.id)).size).toBe(2);
108
+ },
109
+ },
110
+ ];
111
+
112
+ export const SEARCH_INDEX_ALL_CHECKS: readonly SearchIndexCheck[] = [
113
+ ...SEARCH_INDEX_CHECKS,
114
+ ...SEARCH_INDEX_VERSION_CHECKS,
115
+ ...SEARCH_INDEX_LIST_CHECKS,
116
+ ];
117
+
118
+ export const searchIndexConformance: SharedExamples<
119
+ SearchIndexSubject | Promise<SearchIndexSubject>
120
+ > = sharedExamples('a search index', (subject) => {
121
+ for (const check of SEARCH_INDEX_ALL_CHECKS) {
122
+ test(check.name, async () => {
123
+ await check.run(await subject());
124
+ });
125
+ }
126
+ });
@@ -0,0 +1,91 @@
1
+ // The `secretSource` port's contract as shared examples: `behavesLike(secretSourceConformance, ()
2
+ // => subject)`. A source cannot be handed a key through the port, so the subject arranges one — the
3
+ // env var, a key file, a KMS fake's own table — and the suite asks for it back through `masterKey`
4
+ // only.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { SecretSource, SecretSourceContext } 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
+ /** A source plus the two worlds it is asked in: one holding `hex`, one holding nothing. */
14
+ export interface SecretSourceSubject {
15
+ readonly source: SecretSource;
16
+ /** A context this source answers `hex` for. A fresh one per call — two calls, two places. */
17
+ holding(hex: string): Maybe<SecretSourceContext>;
18
+ /** A context this source has no key for. */
19
+ empty(): Maybe<SecretSourceContext>;
20
+ }
21
+
22
+ export interface SecretSourceCheck {
23
+ readonly name: string;
24
+ run(subject: SecretSourceSubject): Promise<void>;
25
+ }
26
+
27
+ let minted = 0;
28
+ /** 64 hex chars, distinct per call: the AES-256 key shape `x secrets init` writes. */
29
+ const keyHex = (): string => {
30
+ minted += 1;
31
+ return `${process.pid.toString(16)}${minted.toString(16)}`.padStart(64, 'a');
32
+ };
33
+
34
+ /** The answer, or the failure itself — "absent" must never be a throw or a rejection. */
35
+ const asked = async (source: SecretSource, context: SecretSourceContext): Promise<unknown> => {
36
+ try {
37
+ return await source.masterKey(context);
38
+ } catch (error) {
39
+ return { threw: error };
40
+ }
41
+ };
42
+
43
+ export const SECRET_SOURCE_CHECKS: readonly SecretSourceCheck[] = [
44
+ {
45
+ name: 'a place holding no key answers undefined — never a throw, never a rejection',
46
+ async run({ source, empty }) {
47
+ expect(await asked(source, await empty())).toBeUndefined();
48
+ },
49
+ },
50
+ {
51
+ name: 'a place holding a key answers exactly that key, twice in a row',
52
+ async run({ source, holding }) {
53
+ const hex = keyHex();
54
+ const context = await holding(hex);
55
+ expect((await source.masterKey(context))?.hex).toBe(hex);
56
+ expect((await source.masterKey(context))?.hex).toBe(hex);
57
+ },
58
+ },
59
+ {
60
+ name: 'the answer names its source and where it was read — and the place never carries the key',
61
+ async run({ source, holding }) {
62
+ const hex = keyHex();
63
+ const ref = await source.masterKey(await holding(hex));
64
+ expect(source.name.length).toBeGreaterThan(0);
65
+ expect(ref?.source.length ?? 0).toBeGreaterThan(0);
66
+ expect(ref?.at.length ?? 0).toBeGreaterThan(0);
67
+ expect(ref?.at).not.toContain(hex);
68
+ expect(ref?.source).not.toContain(hex);
69
+ },
70
+ },
71
+ {
72
+ name: 'two places holding two keys answer each its own — nothing is kept across contexts',
73
+ async run({ source, holding }) {
74
+ const [first, second] = [keyHex(), keyHex()];
75
+ const [one, two] = [await holding(first), await holding(second)];
76
+ expect((await source.masterKey(one))?.hex).toBe(first);
77
+ expect((await source.masterKey(two))?.hex).toBe(second);
78
+ },
79
+ },
80
+ ];
81
+
82
+ export const secretSourceConformance: SharedExamples<SecretSourceSubject> = sharedExamples(
83
+ 'a secret source',
84
+ (subject) => {
85
+ for (const check of SECRET_SOURCE_CHECKS) {
86
+ test(check.name, async () => {
87
+ await check.run(subject());
88
+ });
89
+ }
90
+ },
91
+ );
@@ -0,0 +1,57 @@
1
+ // `factorySeed(name, body)`: a named seed whose rows come from factories — `defineSeed`'s own run
2
+ // (tier, dry run, metrics, `x db seed`), with every `create()` in the body written through the
3
+ // seed's idempotent insert. Every factory sequence restarts first, so a replay draws the same ids
4
+ // and writes nothing new. `@ultimat3/entity` loads on `run()`, never on import.
5
+
6
+ import type { Seed, SeedContext, SeedInit, SeedRun } from '@ultimat3/entity';
7
+ import { FactoryNotPersistedError } from './errors';
8
+ import { resetFactorySequences } from './factories';
9
+ import { isEntity, type Persister, swapPersister } from './factory-persist';
10
+
11
+ /**
12
+ * A `create()` inside a seed: the seed's `insert` — `on conflict do nothing` by primary key, counted
13
+ * in its metrics, rolled back by a dry run. It answers the row as WRITTEN (`$parse`d): a seed reads
14
+ * nothing back, so a replay's skipped row answers what this run would have written.
15
+ */
16
+ const seedPersister = (context: SeedContext): Persister => ({
17
+ async insert(entity, row) {
18
+ if (!isEntity(entity)) throw new FactoryNotPersistedError({ table: entity.$table });
19
+ const parsed = entity.$parse(row) as object;
20
+ await context.insert(entity, [parsed as Parameters<SeedContext['insert']>[1][number]]);
21
+ return parsed;
22
+ },
23
+ });
24
+
25
+ /**
26
+ * `export const demo = factorySeed('demo', async ({ id }) => { await posts.create({ comments: 2,
27
+ * org: await orgs.create({ id: id('org:acme') }) }) })` — then `x db seed demo`, or
28
+ * `demo.run({ driver })` from a test. Same name, same rows, every run.
29
+ */
30
+ export function factorySeed(
31
+ name: string,
32
+ build: (context: SeedContext) => Promise<void>,
33
+ init: SeedInit = {},
34
+ ): Seed {
35
+ const tier = init.tier ?? 'dev';
36
+ return {
37
+ name,
38
+ tier,
39
+ run: async (options = {}): Promise<SeedRun> => {
40
+ const { defineSeed } = await import('@ultimat3/entity');
41
+ const seed = defineSeed(
42
+ name,
43
+ async (context) => {
44
+ resetFactorySequences();
45
+ const previous = swapPersister(seedPersister(context));
46
+ try {
47
+ await build(context);
48
+ } finally {
49
+ swapPersister(previous);
50
+ }
51
+ },
52
+ { tier },
53
+ );
54
+ return seed.run(options);
55
+ },
56
+ };
57
+ }
@@ -6,6 +6,7 @@
6
6
  // `@ultimat3/entity` loads on the first write, never on import: this module is on the barrel, and
7
7
  // the barrel stays entity-free.
8
8
 
9
+ import { fingerprint } from '@ultimat3/core';
9
10
  import type { DbClient, SqlFragment } from '@ultimat3/db';
10
11
  import { identifier, join, sql } from '@ultimat3/db';
11
12
  import type { Driver, EntityCore, Repo } from '@ultimat3/entity';
@@ -14,25 +15,13 @@ import type { SeedRow, SeedUpdate, SeedWriter } from './seed-graph-plan';
14
15
 
15
16
  type SeedRepo = Repo<Record<string, unknown>>;
16
17
 
17
- /** Stable text for one row: keys sorted, an instant as ISO, bytes as hex — never insertion order. */
18
- const stable = (value: unknown): unknown => {
19
- if (value instanceof Date) return value.toISOString();
20
- if (value instanceof Uint8Array) {
21
- return Array.from(value, (byte) => byte.toString(16).padStart(2, '0')).join('');
22
- }
23
- if (typeof value === 'bigint') return value.toString();
24
- if (Array.isArray(value)) return value.map(stable);
25
- if (typeof value !== 'object' || value === null) return value;
26
- const record = value as Record<string, unknown>;
27
- return Object.fromEntries(
28
- Object.keys(record)
29
- .sort()
30
- .map((key) => [key, stable(record[key])]),
31
- );
32
- };
33
-
34
- const digestRow = (row: unknown): string =>
35
- new Bun.CryptoHasher('md5').update(JSON.stringify(stable(row))).digest('hex');
18
+ /**
19
+ * One row's digest: core's `fingerprint`, over `canonicalJson` — the framework's one INJECTIVE
20
+ * form: keys sorted, and a date, bytes and a bigint each tagged. A private copy rendered bytes as
21
+ * bare hex, one digest with the text holding that hex — a hash form must never fold two values
22
+ * onto one string, and a second hasher is where the next copy drifts.
23
+ */
24
+ export const digestRow = (row: unknown): string => fingerprint(row);
36
25
 
37
26
  /** The physical columns of an entity's primary key, in key order. */
38
27
  const keyColumns = (entity: EntityCore): readonly string[] => {
@@ -0,0 +1,86 @@
1
+ // The `semanticCache` port's contract as shared examples:
2
+ // `behavesLike(semanticCacheFactoryConformance, () => (scope) => yours(scope))`. The port is a
3
+ // FACTORY, one cache per scope, because two tenants asking near-identical questions of one shared
4
+ // cache is one tenant reading the other's answer — so scope isolation is the first check.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { SemanticCacheFactory } from '@ultimat3/ai/adapter';
8
+ import { uuidV7 } from '@ultimat3/core';
9
+ import type { SharedExamples } from './shared-examples';
10
+ import { sharedExamples } from './shared-examples';
11
+
12
+ export interface SemanticCacheFactoryCheck {
13
+ readonly name: string;
14
+ run(factory: SemanticCacheFactory): Promise<void>;
15
+ }
16
+
17
+ /** A fresh scope per check, so a durable store's rows from an earlier check never answer. */
18
+ const scope = (label: string): string => `conformance-${label}-${uuidV7()}`;
19
+
20
+ const NORTH = [1, 0, 0] as const;
21
+ const EAST = [0, 1, 0] as const;
22
+
23
+ export const SEMANTIC_CACHE_FACTORY_CHECKS: readonly SemanticCacheFactoryCheck[] = [
24
+ {
25
+ name: 'two scopes are two caches: what one remembers the other never answers',
26
+ async run(factory) {
27
+ const a = factory(scope('a'));
28
+ const b = factory(scope('b'));
29
+ await a.remember('k', NORTH, 'org-a answer');
30
+ expect(await b.lookup(NORTH, 0.9)).toBeUndefined();
31
+ expect((await a.lookup<string>(NORTH, 0.9))?.value).toBe('org-a answer');
32
+ },
33
+ },
34
+ {
35
+ name: 'a remembered embedding answers its own lookup, with its key and a similarity near 1',
36
+ async run(factory) {
37
+ const cache = factory(scope('hit'));
38
+ expect(cache.name.length).toBeGreaterThan(0);
39
+ await cache.remember('the-key', NORTH, { answer: 42 });
40
+ const hit = await cache.lookup<{ answer: number }>(NORTH, 0.9);
41
+ expect(hit?.key).toBe('the-key');
42
+ expect(hit?.value).toEqual({ answer: 42 });
43
+ expect(hit?.similarity).toBeGreaterThan(0.999);
44
+ },
45
+ },
46
+ {
47
+ name: 'below the threshold is a miss, never the nearest entry anyway',
48
+ async run(factory) {
49
+ const cache = factory(scope('miss'));
50
+ await cache.remember('north', NORTH, 'north');
51
+ expect(await cache.lookup(EAST, 0.9)).toBeUndefined();
52
+ },
53
+ },
54
+ {
55
+ name: 'an embedding that is not a number is not a match',
56
+ async run(factory) {
57
+ const cache = factory(scope('nan'));
58
+ await cache.remember('north', NORTH, 'north');
59
+ expect(await cache.lookup([1, Number.NaN, 0], 0.5)).toBeUndefined();
60
+ },
61
+ },
62
+ {
63
+ name: 'invalidateTags drops the tagged entries, names their keys, and keeps the rest',
64
+ async run(factory) {
65
+ const cache = factory(scope('tags'));
66
+ await cache.remember('tagged', NORTH, 'tagged', { tags: [{ entity: 'post', id: '1' }] });
67
+ await cache.remember('kept', EAST, 'kept', { tags: [{ entity: 'post', id: '2' }] });
68
+ expect(await cache.size()).toBe(2);
69
+ expect(await cache.invalidateTags([{ entity: 'post', id: '1' }])).toEqual(['tagged']);
70
+ expect(await cache.lookup(NORTH, 0.9)).toBeUndefined();
71
+ expect((await cache.lookup<string>(EAST, 0.9))?.value).toBe('kept');
72
+ expect(await cache.size()).toBe(1);
73
+ },
74
+ },
75
+ ];
76
+
77
+ export const semanticCacheFactoryConformance: SharedExamples<SemanticCacheFactory> = sharedExamples(
78
+ 'a semantic cache factory',
79
+ (subject) => {
80
+ for (const check of SEMANTIC_CACHE_FACTORY_CHECKS) {
81
+ test(check.name, async () => {
82
+ await check.run(subject());
83
+ });
84
+ }
85
+ },
86
+ );
@@ -0,0 +1,102 @@
1
+ // The `SmsTransport` contract of `@ultimat3/notify` as shared examples, for a provider adapter of
2
+ // your own (Twilio, Vonage, SNS): `behavesLike(smsTransportConformance, () => transport)`. Asked
3
+ // through `send` alone — what a transport answers about a message, never how its wire looks.
4
+
5
+ import { expect, test } from 'bun:test';
6
+ import type { SmsMessage, SmsTransport } from '@ultimat3/notify/adapter';
7
+ import type { SharedExamples } from './shared-examples';
8
+ import { sharedExamples } from './shared-examples';
9
+
10
+ export interface SmsTransportCheck {
11
+ readonly name: string;
12
+ run(transport: SmsTransport): Promise<void>;
13
+ }
14
+
15
+ const TO = '+4915112345678';
16
+ const CONCURRENT_SENDS = 8;
17
+
18
+ /** A rendered message, by hand: the port receives text already in the recipient's language. */
19
+ export const conformanceSms = (overrides: Partial<SmsMessage> = {}): SmsMessage => ({
20
+ to: TO,
21
+ body: 'Your code is 424242',
22
+ idempotencyKey: 'conformance-sms-1',
23
+ ...overrides,
24
+ });
25
+
26
+ const refusedCode = async (run: () => Promise<unknown>): Promise<unknown> => {
27
+ try {
28
+ await run();
29
+ } catch (error) {
30
+ return (error as { code?: unknown }).code;
31
+ }
32
+ return expect.unreachable('expected the transport to refuse');
33
+ };
34
+
35
+ export const SMS_TRANSPORT_CHECKS: readonly SmsTransportCheck[] = [
36
+ {
37
+ name: 'a send resolves a result naming this transport and the number it accepted',
38
+ async run(transport) {
39
+ expect(transport.name.length).toBeGreaterThan(0);
40
+ const result = await transport.send(conformanceSms());
41
+ expect([result.transport, result.to]).toEqual([transport.name, TO]);
42
+ expect(result.id.length).toBeGreaterThan(0);
43
+ },
44
+ },
45
+ {
46
+ // A caller matching a retry to its first send reads this key back.
47
+ name: 'the idempotency key is answered back unchanged, the same on every attempt',
48
+ async run(transport) {
49
+ const message = conformanceSms();
50
+ const first = await transport.send(message);
51
+ const second = await transport.send(message);
52
+ expect([first.idempotencyKey, second.idempotencyKey]).toEqual([
53
+ message.idempotencyKey,
54
+ message.idempotencyKey,
55
+ ]);
56
+ },
57
+ },
58
+ {
59
+ // The id lands in logs and the delivery ledger; the number and the body are a person's.
60
+ name: 'the result id carries neither the number nor the body',
61
+ async run(transport) {
62
+ const message = conformanceSms();
63
+ const result = await transport.send(message);
64
+ for (const leak of [TO, TO.slice(1), message.body]) expect(result.id).not.toContain(leak);
65
+ },
66
+ },
67
+ {
68
+ // A local spelling is a number the provider guesses the country of: a message to a stranger.
69
+ name: 'a number that is not E.164 is refused with X_NOTIFY_SMS_NUMBER_INVALID',
70
+ async run(transport) {
71
+ for (const to of ['015112345678', '+49 151 12345678', '']) {
72
+ expect(await refusedCode(() => transport.send(conformanceSms({ to })))).toBe(
73
+ 'X_NOTIFY_SMS_NUMBER_INVALID',
74
+ );
75
+ }
76
+ },
77
+ },
78
+ {
79
+ name: `${CONCURRENT_SENDS} concurrent sends each answer for their own message`,
80
+ async run(transport) {
81
+ const messages = Array.from({ length: CONCURRENT_SENDS }, (_, index) =>
82
+ conformanceSms({
83
+ to: `+1415555${String(index).padStart(4, '0')}`,
84
+ idempotencyKey: `conformance-sms-${String(index)}`,
85
+ }),
86
+ );
87
+ const results = await Promise.all(messages.map((message) => transport.send(message)));
88
+ expect(results.map((result) => [result.to, result.idempotencyKey])).toEqual(
89
+ messages.map((message) => [message.to, message.idempotencyKey]),
90
+ );
91
+ },
92
+ },
93
+ ];
94
+
95
+ export const smsTransportConformance: SharedExamples<SmsTransport | Promise<SmsTransport>> =
96
+ sharedExamples('an SMS transport', (subject) => {
97
+ for (const check of SMS_TRANSPORT_CHECKS) {
98
+ test(check.name, async () => {
99
+ await check.run(await subject());
100
+ });
101
+ }
102
+ });
@@ -0,0 +1,171 @@
1
+ // The `StepStore` contract of `@ultimat3/jobs` as shared examples: `behavesLike(stepStoreConformance,
2
+ // () => driver)`. The subject is the store AND the queue it is fenced on — a write made under a
3
+ // claim lands only while that claim holds the row, and only a queue row can say so. Any `JobDriver`
4
+ // is one; a store of your own goes in as `memoryJobDriver({ steps: yours })` or inside your driver.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { JobDriver, StepFence, StepRecord } from '@ultimat3/jobs';
8
+ import type { SharedExamples } from './shared-examples';
9
+ import { sharedExamples } from './shared-examples';
10
+
11
+ /** The step store under test and the slice of its queue a fence needs. */
12
+ export type StepStoreSubject = Pick<JobDriver, 'steps' | 'enqueue' | 'claim' | 'ack'>;
13
+
14
+ export interface StepStoreCheck {
15
+ readonly name: string;
16
+ run(subject: StepStoreSubject): Promise<void>;
17
+ }
18
+
19
+ const AT = Date.UTC(2026, 10, 9, 9, 0, 0);
20
+
21
+ let minted = 0;
22
+ const tag = (): string => {
23
+ minted += 1;
24
+ return `${process.pid.toString(36)}-${minted.toString(36)}`;
25
+ };
26
+
27
+ const step = (runId: string, name: string, extra: Partial<StepRecord> = {}): StepRecord => ({
28
+ runId,
29
+ name,
30
+ status: 'completed',
31
+ output: { name },
32
+ startedAt: AT,
33
+ completedAt: AT + 5,
34
+ attempts: 1,
35
+ ...extra,
36
+ });
37
+
38
+ /** A claimed row of a queue of this check's own, and the fence its claim writes under. */
39
+ async function claimed(subject: StepStoreSubject): Promise<{ runId: string; fence: StepFence }> {
40
+ const at = tag();
41
+ const [queue, job] = [`conformance-steps-${at}`, `conformance.steps-${at}`];
42
+ await subject.enqueue({ name: job, queue, input: {}, idempotencyKey: at, maxAttempts: 3 });
43
+ const [row] = await subject.claim({
44
+ queues: [queue],
45
+ limit: 1,
46
+ visibilityTimeoutMs: 30_000,
47
+ workerId: 'conformance-worker',
48
+ });
49
+ if (row === undefined) return expect.unreachable('a row enqueued on its own queue is claimable');
50
+ const fence = { job, jobId: row.id, workerId: row.claimedBy, claim: row.claim };
51
+ return { runId: row.runId, fence };
52
+ }
53
+
54
+ const leaseLost = { code: 'X_JOB_LEASE_LOST' };
55
+
56
+ export const STEP_STORE_CHECKS: readonly StepStoreCheck[] = [
57
+ {
58
+ name: 'a step nobody wrote is undefined, and a run nobody wrote lists nothing',
59
+ async run({ steps }) {
60
+ const runId = crypto.randomUUID();
61
+ expect(await steps.get(runId, 'absent')).toBeUndefined();
62
+ expect(await steps.list(runId)).toEqual([]);
63
+ },
64
+ },
65
+ {
66
+ name: 'every field of a record reads back as it was written',
67
+ async run({ steps }) {
68
+ const runId = crypto.randomUUID();
69
+ const waiting = step(runId, 'wait', {
70
+ status: 'waiting',
71
+ output: { floor: 7 },
72
+ wakeAt: AT + 60_000,
73
+ event: 'paid',
74
+ correlationKey: 'order-1',
75
+ attempts: 2,
76
+ error: 'boom',
77
+ });
78
+ await steps.put(waiting);
79
+ expect(await steps.get(runId, 'wait')).toEqual(waiting);
80
+ expect(await steps.list(runId)).toEqual([waiting]);
81
+ },
82
+ },
83
+ {
84
+ // A live reference replayed a `Date` under one store and a string under another: a step that
85
+ // worked in every test broke on its first retry in production.
86
+ name: 'an output is stored as JSON carries it: a Date as its string, undefined as null',
87
+ async run({ steps }) {
88
+ const runId = crypto.randomUUID();
89
+ const date = new Date(AT);
90
+ const cases: readonly (readonly [string, unknown, unknown])[] = [
91
+ ['date', { at: date }, { at: date.toISOString() }],
92
+ ['undefined', undefined, null],
93
+ ['member', { a: undefined, b: 1 }, { b: 1 }],
94
+ ['map', new Map([['k', 1]]), {}],
95
+ ];
96
+ for (const [name, output] of cases) await steps.put(step(runId, name, { output }));
97
+ for (const [name, , stored] of cases) {
98
+ expect((await steps.get(runId, name))?.output).toEqual(stored);
99
+ }
100
+ },
101
+ },
102
+ {
103
+ name: 'a second put of one (run, name) replaces the first',
104
+ async run({ steps }) {
105
+ const runId = crypto.randomUUID();
106
+ await steps.put(step(runId, 'nap', { status: 'sleeping', output: null, wakeAt: AT + 9 }));
107
+ const done = step(runId, 'nap', { output: 'woke', attempts: 2 });
108
+ await steps.put(done);
109
+ expect(await steps.list(runId)).toEqual([done]);
110
+ },
111
+ },
112
+ {
113
+ name: 'list reads one run in start order; del and clear scope by run',
114
+ async run({ steps }) {
115
+ const [runId, other] = [crypto.randomUUID(), crypto.randomUUID()];
116
+ const [late, early, mid] = [
117
+ step(runId, 'late', { startedAt: AT + 20 }),
118
+ step(runId, 'early', { startedAt: AT }),
119
+ step(runId, 'mid', { startedAt: AT + 10 }),
120
+ ];
121
+ for (const each of [late, early, mid, step(other, 'kept')]) await steps.put(each);
122
+ expect((await steps.list(runId)).map((each) => each.name)).toEqual(['early', 'mid', 'late']);
123
+ await steps.del(runId, 'mid');
124
+ expect((await steps.list(runId)).map((each) => each.name)).toEqual(['early', 'late']);
125
+ await steps.clear(runId);
126
+ expect(await steps.list(runId)).toEqual([]);
127
+ expect((await steps.list(other)).map((each) => each.name)).toEqual(['kept']);
128
+ },
129
+ },
130
+ {
131
+ name: 'a write under a claim that still holds the row lands',
132
+ async run(subject) {
133
+ const { runId, fence } = await claimed(subject);
134
+ await subject.steps.put(step(runId, 'fenced'), fence);
135
+ expect((await subject.steps.get(runId, 'fenced'))?.status).toBe('completed');
136
+ },
137
+ },
138
+ {
139
+ // The in-process abort cannot stop a body in ANOTHER process whose lease lapsed; this can.
140
+ name: 'a write under another claim of the row is X_JOB_LEASE_LOST and writes nothing',
141
+ async run(subject) {
142
+ const { runId, fence } = await claimed(subject);
143
+ const stale = [
144
+ { ...fence, claim: fence.claim + 1 },
145
+ { ...fence, workerId: 'another' },
146
+ ];
147
+ for (const by of stale) {
148
+ await expect(subject.steps.put(step(runId, 'stale'), by)).rejects.toMatchObject(leaseLost);
149
+ }
150
+ expect(await subject.steps.get(runId, 'stale')).toBeUndefined();
151
+ },
152
+ },
153
+ {
154
+ name: 'a write under a claim whose row was settled is X_JOB_LEASE_LOST',
155
+ async run(subject) {
156
+ const { runId, fence } = await claimed(subject);
157
+ expect(await subject.ack(fence.jobId, fence)).toBe(true);
158
+ await expect(subject.steps.put(step(runId, 'late'), fence)).rejects.toMatchObject(leaseLost);
159
+ expect(await subject.steps.get(runId, 'late')).toBeUndefined();
160
+ },
161
+ },
162
+ ];
163
+
164
+ export const stepStoreConformance: SharedExamples<StepStoreSubject | Promise<StepStoreSubject>> =
165
+ sharedExamples('a step store', (subject) => {
166
+ for (const check of STEP_STORE_CHECKS) {
167
+ test(check.name, async () => {
168
+ await check.run(await subject());
169
+ });
170
+ }
171
+ });