@ontrails/testing 1.0.0-beta.2 → 1.0.0-beta.21

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 (91) hide show
  1. package/CHANGELOG.md +396 -5
  2. package/README.md +86 -22
  3. package/package.json +34 -5
  4. package/src/all-established.ts +168 -0
  5. package/src/all.ts +51 -12
  6. package/src/assertions.ts +253 -0
  7. package/src/cli.ts +6 -0
  8. package/src/composes.ts +433 -0
  9. package/src/context.ts +200 -14
  10. package/src/contracts.ts +45 -21
  11. package/src/detours.ts +155 -18
  12. package/src/effective-examples.ts +414 -0
  13. package/src/errors.ts +47 -0
  14. package/src/examples.ts +302 -177
  15. package/src/harness-cli.ts +83 -58
  16. package/src/harness-http.ts +341 -0
  17. package/src/harness-mcp.ts +46 -16
  18. package/src/http.ts +10 -0
  19. package/src/index.ts +22 -14
  20. package/src/logger.ts +3 -1
  21. package/src/mcp.ts +6 -0
  22. package/src/scenario.ts +375 -0
  23. package/src/signals.ts +221 -0
  24. package/src/surface-parity.ts +389 -0
  25. package/src/trail.ts +1 -1
  26. package/src/types.ts +24 -52
  27. package/.turbo/turbo-build.log +0 -1
  28. package/.turbo/turbo-lint.log +0 -3
  29. package/.turbo/turbo-typecheck.log +0 -1
  30. package/dist/all.d.ts +0 -30
  31. package/dist/all.d.ts.map +0 -1
  32. package/dist/all.js +0 -47
  33. package/dist/all.js.map +0 -1
  34. package/dist/assertions.d.ts +0 -49
  35. package/dist/assertions.d.ts.map +0 -1
  36. package/dist/assertions.js +0 -84
  37. package/dist/assertions.js.map +0 -1
  38. package/dist/context.d.ts +0 -19
  39. package/dist/context.d.ts.map +0 -1
  40. package/dist/context.js +0 -33
  41. package/dist/context.js.map +0 -1
  42. package/dist/contracts.d.ts +0 -16
  43. package/dist/contracts.d.ts.map +0 -1
  44. package/dist/contracts.js +0 -56
  45. package/dist/contracts.js.map +0 -1
  46. package/dist/detours.d.ts +0 -12
  47. package/dist/detours.d.ts.map +0 -1
  48. package/dist/detours.js +0 -30
  49. package/dist/detours.js.map +0 -1
  50. package/dist/examples.d.ts +0 -22
  51. package/dist/examples.d.ts.map +0 -1
  52. package/dist/examples.js +0 -187
  53. package/dist/examples.js.map +0 -1
  54. package/dist/harness-cli.d.ts +0 -21
  55. package/dist/harness-cli.d.ts.map +0 -1
  56. package/dist/harness-cli.js +0 -213
  57. package/dist/harness-cli.js.map +0 -1
  58. package/dist/harness-mcp.d.ts +0 -21
  59. package/dist/harness-mcp.d.ts.map +0 -1
  60. package/dist/harness-mcp.js +0 -50
  61. package/dist/harness-mcp.js.map +0 -1
  62. package/dist/hike.d.ts +0 -32
  63. package/dist/hike.d.ts.map +0 -1
  64. package/dist/hike.js +0 -169
  65. package/dist/hike.js.map +0 -1
  66. package/dist/index.d.ts +0 -14
  67. package/dist/index.d.ts.map +0 -1
  68. package/dist/index.js +0 -16
  69. package/dist/index.js.map +0 -1
  70. package/dist/logger.d.ts +0 -15
  71. package/dist/logger.d.ts.map +0 -1
  72. package/dist/logger.js +0 -87
  73. package/dist/logger.js.map +0 -1
  74. package/dist/trail.d.ts +0 -20
  75. package/dist/trail.d.ts.map +0 -1
  76. package/dist/trail.js +0 -80
  77. package/dist/trail.js.map +0 -1
  78. package/dist/types.d.ts +0 -80
  79. package/dist/types.d.ts.map +0 -1
  80. package/dist/types.js +0 -5
  81. package/dist/types.js.map +0 -1
  82. package/src/__tests__/context.test.ts +0 -60
  83. package/src/__tests__/contracts.test.ts +0 -68
  84. package/src/__tests__/detours.test.ts +0 -55
  85. package/src/__tests__/examples.test.ts +0 -176
  86. package/src/__tests__/hike.test.ts +0 -164
  87. package/src/__tests__/logger.test.ts +0 -136
  88. package/src/__tests__/trail.test.ts +0 -99
  89. package/src/hike.ts +0 -283
  90. package/tsconfig.json +0 -9
  91. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,414 @@
1
+ import type { AnyContour, Trail, TrailExample } from '@ontrails/core';
2
+ import {
3
+ getContourReferences,
4
+ getTrailVersionEntryKind,
5
+ isArchivedTrailVersionEntry,
6
+ } from '@ontrails/core';
7
+ import { z } from 'zod';
8
+
9
+ type ExampleRecord = Readonly<Record<string, unknown>>;
10
+
11
+ export interface TrailExampleTarget {
12
+ readonly composes: readonly string[];
13
+ readonly current: boolean;
14
+ readonly examples: readonly TrailExample<unknown, unknown>[];
15
+ readonly id: string;
16
+ readonly input: Trail<unknown, unknown, unknown>['input'];
17
+ readonly output: Trail<unknown, unknown, unknown>['output'];
18
+ readonly trail: Trail<unknown, unknown, unknown>;
19
+ readonly version?: number | undefined;
20
+ }
21
+
22
+ const normalizeComposeRef = (value: string | { readonly id: string }): string =>
23
+ typeof value === 'string' ? value : value.id;
24
+
25
+ /**
26
+ * Tracks examples that `deriveTrailExamples` synthesizes from contour
27
+ * fixtures. Authored examples are passed through untouched and never
28
+ * appear here, so consumers can distinguish the two by identity.
29
+ *
30
+ * Exposed via `isDerivedExample` so downstream testing helpers (e.g.
31
+ * `testExamples` composing coverage) can relax invariants that only make
32
+ * sense for authored inputs.
33
+ */
34
+ const derivedExamples = new WeakSet<TrailExample<unknown, unknown>>();
35
+
36
+ /**
37
+ * Returns `true` if the given example was synthesized from contour fixtures
38
+ * by `deriveTrailExamples`, `false` if it was authored on the trail.
39
+ */
40
+ export const isDerivedExample = (
41
+ example: TrailExample<unknown, unknown>
42
+ ): boolean => derivedExamples.has(example);
43
+
44
+ interface ContourFixture {
45
+ readonly contour: AnyContour;
46
+ readonly example: ExampleRecord;
47
+ readonly index: number;
48
+ }
49
+
50
+ const capitalize = (value: string): string =>
51
+ value.length === 0 ? value : value.slice(0, 1).toUpperCase() + value.slice(1);
52
+
53
+ const collectReferenceMap = (
54
+ contours: readonly AnyContour[]
55
+ ): ReadonlyMap<string, ReturnType<typeof getContourReferences>> => {
56
+ const contourNames = new Set(contours.map((contour) => contour.name));
57
+
58
+ return new Map(
59
+ contours.map((contour) => [
60
+ contour.name,
61
+ getContourReferences(contour).filter((reference) =>
62
+ contourNames.has(reference.contour)
63
+ ),
64
+ ])
65
+ );
66
+ };
67
+
68
+ const getIdentityValue = (fixture: ContourFixture): unknown =>
69
+ fixture.example[fixture.contour.identity];
70
+
71
+ const candidateMatchesSelectedReference = (
72
+ candidate: ContourFixture,
73
+ target: ContourFixture,
74
+ reference: ReturnType<typeof getContourReferences>[number]
75
+ ): boolean =>
76
+ Object.is(candidate.example[reference.field], getIdentityValue(target));
77
+
78
+ const selectedMatchesCandidateReference = (
79
+ fixture: ContourFixture,
80
+ candidate: ContourFixture,
81
+ reference: ReturnType<typeof getContourReferences>[number]
82
+ ): boolean =>
83
+ Object.is(fixture.example[reference.field], getIdentityValue(candidate));
84
+
85
+ const matchesCandidateReferences = (
86
+ candidate: ContourFixture,
87
+ selected: readonly ContourFixture[],
88
+ referencesByContour: ReadonlyMap<
89
+ string,
90
+ ReturnType<typeof getContourReferences>
91
+ >
92
+ ): boolean => {
93
+ const candidateReferences =
94
+ referencesByContour.get(candidate.contour.name) ?? [];
95
+
96
+ for (const reference of candidateReferences) {
97
+ const target = selected.find(
98
+ (fixture) => fixture.contour.name === reference.contour
99
+ );
100
+ if (target === undefined) {
101
+ continue;
102
+ }
103
+ if (!candidateMatchesSelectedReference(candidate, target, reference)) {
104
+ return false;
105
+ }
106
+ }
107
+
108
+ return true;
109
+ };
110
+
111
+ const matchesSelectedReferences = (
112
+ candidate: ContourFixture,
113
+ selected: readonly ContourFixture[],
114
+ referencesByContour: ReadonlyMap<
115
+ string,
116
+ ReturnType<typeof getContourReferences>
117
+ >
118
+ ): boolean => {
119
+ for (const fixture of selected) {
120
+ const fixtureReferences =
121
+ referencesByContour.get(fixture.contour.name) ?? [];
122
+ for (const reference of fixtureReferences) {
123
+ if (reference.contour !== candidate.contour.name) {
124
+ continue;
125
+ }
126
+ if (!selectedMatchesCandidateReference(fixture, candidate, reference)) {
127
+ return false;
128
+ }
129
+ }
130
+ }
131
+
132
+ return true;
133
+ };
134
+
135
+ const matchesKnownReferences = (
136
+ candidate: ContourFixture,
137
+ selected: readonly ContourFixture[],
138
+ referencesByContour: ReadonlyMap<
139
+ string,
140
+ ReturnType<typeof getContourReferences>
141
+ >
142
+ ): boolean =>
143
+ matchesCandidateReferences(candidate, selected, referencesByContour) &&
144
+ matchesSelectedReferences(candidate, selected, referencesByContour);
145
+
146
+ const selectContourFixtures = (
147
+ contours: readonly AnyContour[],
148
+ referencesByContour: ReadonlyMap<
149
+ string,
150
+ ReturnType<typeof getContourReferences>
151
+ >,
152
+ index = 0,
153
+ selected: readonly ContourFixture[] = []
154
+ ): readonly (readonly ContourFixture[])[] => {
155
+ const contour = contours[index];
156
+ if (contour === undefined) {
157
+ return [selected];
158
+ }
159
+
160
+ const examples = contour.examples ?? [];
161
+ const matchingFixtures = examples.flatMap((example, exampleIndex) => {
162
+ const fixture = {
163
+ contour,
164
+ example: example as ExampleRecord,
165
+ index: exampleIndex,
166
+ } satisfies ContourFixture;
167
+
168
+ if (!matchesKnownReferences(fixture, selected, referencesByContour)) {
169
+ return [];
170
+ }
171
+
172
+ return selectContourFixtures(contours, referencesByContour, index + 1, [
173
+ ...selected,
174
+ fixture,
175
+ ]);
176
+ });
177
+
178
+ return matchingFixtures;
179
+ };
180
+
181
+ /**
182
+ * Merge selected contour fixtures into a single candidate input object.
183
+ *
184
+ * The resulting record contains:
185
+ * - `<contour>`: the full fixture payload keyed by contour name.
186
+ * - `<contour><Identity>`: the fixture's identity value on a prefixed key.
187
+ * - `<contour><Field>`: every fixture field on a prefixed key.
188
+ * - Unqualified `<field>` keys: first-write-wins across contours.
189
+ *
190
+ * The first-write-wins behaviour on unqualified keys is intentional but can
191
+ * silently drop a later contour's value when two contours share a field name
192
+ * (e.g. both declare `id`). The prefixed aliases above are unambiguous and
193
+ * always written, so schemas that consume the prefixed form are unaffected;
194
+ * schemas that rely on the bare field name should disambiguate via the
195
+ * prefixed alias instead.
196
+ */
197
+ const buildDerivedInput = (
198
+ fixtures: readonly ContourFixture[]
199
+ ): Record<string, unknown> => {
200
+ const candidate: Record<string, unknown> = {};
201
+
202
+ for (const fixture of fixtures) {
203
+ candidate[fixture.contour.name] = fixture.example;
204
+ candidate[
205
+ `${fixture.contour.name}${capitalize(fixture.contour.identity)}`
206
+ ] = getIdentityValue(fixture);
207
+
208
+ for (const [field, value] of Object.entries(fixture.example)) {
209
+ if (!Object.hasOwn(candidate, field)) {
210
+ candidate[field] = value;
211
+ }
212
+
213
+ candidate[`${fixture.contour.name}${capitalize(field)}`] = value;
214
+ }
215
+ }
216
+
217
+ return candidate;
218
+ };
219
+
220
+ /**
221
+ * Project the merged candidate input down to keys the trail's input schema
222
+ * knows about.
223
+ *
224
+ * `buildDerivedInput` emits synthesized prefixed aliases (e.g. `userEmail`)
225
+ * alongside bare field names. Strict schemas (`z.object(...).strict()`)
226
+ * reject any unknown key, which means an otherwise valid derived fixture
227
+ * would silently fail `safeParse` just because of the synthesized aliases.
228
+ * When the input is a `ZodObject`, trim the candidate to its declared keys
229
+ * before validation. Non-object inputs pass through unchanged — they are
230
+ * validated as-is and can decide for themselves.
231
+ */
232
+ const projectInputForSchema = (
233
+ inputSchema: Trail<unknown, unknown, unknown>['input'],
234
+ candidate: Record<string, unknown>
235
+ ): Record<string, unknown> => {
236
+ if (!(inputSchema instanceof z.ZodObject)) {
237
+ return candidate;
238
+ }
239
+
240
+ const known = Object.keys(inputSchema.shape);
241
+ const projected: Record<string, unknown> = {};
242
+ for (const key of known) {
243
+ if (Object.hasOwn(candidate, key)) {
244
+ projected[key] = candidate[key];
245
+ }
246
+ }
247
+ return projected;
248
+ };
249
+
250
+ /**
251
+ * Derive an expected output value from the selected contour fixtures when
252
+ * exactly one fixture's payload satisfies the trail's output schema.
253
+ *
254
+ * Returns `undefined` when the trail has no output schema, when no fixture
255
+ * matches, or when more than one matches — callers should then leave the
256
+ * derived example without an `expected` and fall back to schema-only
257
+ * validation. We intentionally do **not** infer `expected` from the merged
258
+ * candidate input: input and output schemas frequently overlap structurally
259
+ * but represent different semantics, so inferring from the input would
260
+ * produce false deep-equality failures.
261
+ */
262
+ const deriveExpectedValue = (
263
+ trail: Trail<unknown, unknown, unknown>,
264
+ fixtures: readonly ContourFixture[]
265
+ ): unknown => {
266
+ if (trail.output === undefined) {
267
+ return undefined;
268
+ }
269
+
270
+ const outputSchema = trail.output;
271
+ const contourMatches = fixtures
272
+ .map((fixture) => outputSchema.safeParse(fixture.example))
273
+ .filter((candidate) => candidate.success);
274
+
275
+ if (contourMatches.length !== 1) {
276
+ return undefined;
277
+ }
278
+
279
+ const [singleMatch] = contourMatches;
280
+ if (singleMatch === undefined) {
281
+ return undefined;
282
+ }
283
+ return singleMatch.data;
284
+ };
285
+
286
+ const formatFixtureName = (
287
+ fixtures: readonly ContourFixture[],
288
+ index: number
289
+ ): string => {
290
+ const label = fixtures
291
+ .map((fixture) => {
292
+ const identity = getIdentityValue(fixture);
293
+ const fallback = fixture.index + 1;
294
+ return `${fixture.contour.name}:${String(identity ?? fallback)}`;
295
+ })
296
+ .join(', ');
297
+
298
+ return label.length > 0
299
+ ? `Derived fixture ${index + 1} (${label})`
300
+ : `Derived fixture ${index + 1}`;
301
+ };
302
+
303
+ /**
304
+ * Prefer authored trail examples and fall back to contour-derived fixtures.
305
+ *
306
+ * Examples returned by this helper come from one of two provenances:
307
+ * - **Authored.** When `trail.examples` is non-empty, its entries are
308
+ * returned verbatim. These are the developer's stated intent and carry
309
+ * full invariants — including composing-coverage assertions in
310
+ * `testExamples`.
311
+ * - **Derived.** When there are no authored examples but the trail has
312
+ * contours with examples, candidate inputs are synthesized from contour
313
+ * fixtures and validated against `trail.input`. These are opportunistic
314
+ * coverage that exists to let `testAll(app)` exercise contour-backed
315
+ * trails without per-test setup; they are not guaranteed to exercise
316
+ * every composition branch, so consumers should relax invariants that
317
+ * only make sense for authored inputs (see `isDerivedExample`).
318
+ *
319
+ * Contour examples stay as the raw input payload so Trails validation /
320
+ * transforms still happen exactly once inside the normal test execution
321
+ * path. Derived examples are additionally tagged via a module-level
322
+ * `WeakSet` so consumers can detect them without widening the public
323
+ * `TrailExample` shape.
324
+ */
325
+ export const deriveTrailExamples = (
326
+ trail: Trail<unknown, unknown, unknown>
327
+ ): readonly TrailExample<unknown, unknown>[] => {
328
+ if (trail.examples !== undefined && trail.examples.length > 0) {
329
+ return trail.examples;
330
+ }
331
+
332
+ if (trail.contours.length === 0) {
333
+ return [];
334
+ }
335
+
336
+ if (
337
+ trail.contours.some(
338
+ (contour) =>
339
+ contour.examples === undefined || contour.examples.length === 0
340
+ )
341
+ ) {
342
+ return [];
343
+ }
344
+
345
+ const referencesByContour = collectReferenceMap(trail.contours);
346
+ const fixtureSets = selectContourFixtures(
347
+ trail.contours,
348
+ referencesByContour
349
+ );
350
+
351
+ return fixtureSets.flatMap((fixtures, index) => {
352
+ const merged = buildDerivedInput(fixtures);
353
+ const input = projectInputForSchema(trail.input, merged);
354
+ const validated = trail.input.safeParse(input);
355
+ if (!validated.success) {
356
+ return [];
357
+ }
358
+
359
+ const expected = deriveExpectedValue(trail, fixtures);
360
+ const derived: TrailExample<unknown, unknown> = {
361
+ ...(expected === undefined ? {} : { expected }),
362
+ input,
363
+ name: formatFixtureName(fixtures, index),
364
+ };
365
+ derivedExamples.add(derived);
366
+ return [derived];
367
+ });
368
+ };
369
+
370
+ export const deriveTrailExampleTargets = (
371
+ trail: Trail<unknown, unknown, unknown>
372
+ ): readonly TrailExampleTarget[] => {
373
+ const targets: TrailExampleTarget[] = [];
374
+ const currentExamples = deriveTrailExamples(trail);
375
+ if (currentExamples.length > 0) {
376
+ targets.push({
377
+ composes: trail.composes,
378
+ current: true,
379
+ examples: currentExamples,
380
+ id: trail.id,
381
+ input: trail.input,
382
+ output: trail.output,
383
+ trail,
384
+ });
385
+ }
386
+
387
+ for (const [rawVersion, entry] of Object.entries(
388
+ trail.versions ?? {}
389
+ ).toSorted(([left], [right]) => Number(left) - Number(right))) {
390
+ if (isArchivedTrailVersionEntry(entry)) {
391
+ continue;
392
+ }
393
+ const examples = entry.examples ?? [];
394
+ if (examples.length === 0) {
395
+ continue;
396
+ }
397
+ const kind = getTrailVersionEntryKind(entry);
398
+ targets.push({
399
+ composes:
400
+ kind === 'fork'
401
+ ? (entry.composes ?? []).map(normalizeComposeRef)
402
+ : trail.composes,
403
+ current: false,
404
+ examples,
405
+ id: `${trail.id}@${rawVersion}`,
406
+ input: entry.input,
407
+ output: entry.output,
408
+ trail,
409
+ version: Number(rawVersion),
410
+ });
411
+ }
412
+
413
+ return targets;
414
+ };
package/src/errors.ts ADDED
@@ -0,0 +1,47 @@
1
+ import {
2
+ errorClasses,
3
+ InternalError,
4
+ RetryExhaustedError,
5
+ TrailsError,
6
+ } from '@ontrails/core';
7
+
8
+ type ErrorConstructor = new (...args: never[]) => Error;
9
+ type MessageErrorConstructor = new (message: string) => Error;
10
+
11
+ const ERROR_CLASS_BY_NAME = new Map<string, ErrorConstructor>([
12
+ ...errorClasses.map(
13
+ (entry) => [entry.name, entry.ctor as ErrorConstructor] as const
14
+ ),
15
+ ['TrailsError', TrailsError as unknown as ErrorConstructor],
16
+ ]);
17
+
18
+ /**
19
+ * Resolve an error class name string to the actual constructor.
20
+ * Falls back to generic Error if the name is not in the core taxonomy.
21
+ */
22
+ export const resolveErrorClass = (name: string): ErrorConstructor =>
23
+ ERROR_CLASS_BY_NAME.get(name) ?? (Error as ErrorConstructor);
24
+
25
+ /**
26
+ * Create an error instance for an authored example error name.
27
+ */
28
+ export const createErrorFromName = (name: string): Error => {
29
+ if (name === 'TrailsError') {
30
+ return new InternalError(name);
31
+ }
32
+
33
+ const entry = errorClasses.find((candidate) => candidate.name === name);
34
+ if (entry === undefined) {
35
+ return new Error(name);
36
+ }
37
+
38
+ if (entry.name === 'RetryExhaustedError') {
39
+ return new RetryExhaustedError(new InternalError(name), {
40
+ attempts: 1,
41
+ detour: 'testComposes',
42
+ });
43
+ }
44
+
45
+ const ErrorClass = entry.ctor as unknown as MessageErrorConstructor;
46
+ return new ErrorClass(name);
47
+ };