@ontrails/testing 1.0.0-beta.14 → 1.0.0-beta.16

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 (88) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +12 -12
  3. package/package.json +15 -6
  4. package/src/all.ts +153 -16
  5. package/src/assertions.ts +253 -0
  6. package/src/context.ts +67 -38
  7. package/src/contracts.ts +15 -24
  8. package/src/crosses.ts +93 -51
  9. package/src/detours.ts +155 -18
  10. package/src/effective-examples.ts +350 -0
  11. package/src/examples.ts +139 -63
  12. package/src/harness-cli.ts +19 -11
  13. package/src/harness-mcp.ts +9 -8
  14. package/src/index.ts +14 -4
  15. package/src/logger.ts +3 -1
  16. package/src/scenario.ts +368 -0
  17. package/src/signals.ts +221 -0
  18. package/src/types.ts +64 -6
  19. package/.turbo/turbo-build.log +0 -1
  20. package/.turbo/turbo-lint.log +0 -3
  21. package/.turbo/turbo-typecheck.log +0 -1
  22. package/dist/all.d.ts +0 -31
  23. package/dist/all.d.ts.map +0 -1
  24. package/dist/all.js +0 -47
  25. package/dist/all.js.map +0 -1
  26. package/dist/assertions.d.ts +0 -49
  27. package/dist/assertions.d.ts.map +0 -1
  28. package/dist/assertions.js +0 -84
  29. package/dist/assertions.js.map +0 -1
  30. package/dist/context.d.ts +0 -75
  31. package/dist/context.d.ts.map +0 -1
  32. package/dist/context.js +0 -107
  33. package/dist/context.js.map +0 -1
  34. package/dist/contracts.d.ts +0 -17
  35. package/dist/contracts.d.ts.map +0 -1
  36. package/dist/contracts.js +0 -71
  37. package/dist/contracts.js.map +0 -1
  38. package/dist/crosses.d.ts +0 -38
  39. package/dist/crosses.d.ts.map +0 -1
  40. package/dist/crosses.js +0 -213
  41. package/dist/crosses.js.map +0 -1
  42. package/dist/detours.d.ts +0 -12
  43. package/dist/detours.d.ts.map +0 -1
  44. package/dist/detours.js +0 -30
  45. package/dist/detours.js.map +0 -1
  46. package/dist/examples.d.ts +0 -23
  47. package/dist/examples.d.ts.map +0 -1
  48. package/dist/examples.js +0 -202
  49. package/dist/examples.js.map +0 -1
  50. package/dist/follows.d.ts +0 -38
  51. package/dist/follows.d.ts.map +0 -1
  52. package/dist/follows.js +0 -212
  53. package/dist/follows.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 -200
  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 -53
  61. package/dist/harness-mcp.js.map +0 -1
  62. package/dist/index.d.ts +0 -16
  63. package/dist/index.d.ts.map +0 -1
  64. package/dist/index.js +0 -16
  65. package/dist/index.js.map +0 -1
  66. package/dist/logger.d.ts +0 -15
  67. package/dist/logger.d.ts.map +0 -1
  68. package/dist/logger.js +0 -87
  69. package/dist/logger.js.map +0 -1
  70. package/dist/trail.d.ts +0 -20
  71. package/dist/trail.d.ts.map +0 -1
  72. package/dist/trail.js +0 -80
  73. package/dist/trail.js.map +0 -1
  74. package/dist/types.d.ts +0 -80
  75. package/dist/types.d.ts.map +0 -1
  76. package/dist/types.js +0 -5
  77. package/dist/types.js.map +0 -1
  78. package/src/__tests__/all.test.ts +0 -135
  79. package/src/__tests__/context.test.ts +0 -150
  80. package/src/__tests__/contracts.test.ts +0 -185
  81. package/src/__tests__/crosses.test.ts +0 -587
  82. package/src/__tests__/detours.test.ts +0 -55
  83. package/src/__tests__/examples.test.ts +0 -534
  84. package/src/__tests__/harness-cli.test.ts +0 -66
  85. package/src/__tests__/logger.test.ts +0 -136
  86. package/src/__tests__/trail.test.ts +0 -99
  87. package/tsconfig.json +0 -9
  88. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Multi-step scenario runner for composition testing.
3
+ *
4
+ * Scenarios express multi-trail flows as structured data — arrays of steps
5
+ * with cross-step references via `ref()`. Each step invokes a trail through
6
+ * the normal execution pipeline (validation, layers, blaze, Result).
7
+ */
8
+
9
+ import { describe, test } from 'bun:test';
10
+
11
+ import type {
12
+ AnyTrail,
13
+ CrossBatchOptions,
14
+ CrossFn,
15
+ ResourceOverrideMap,
16
+ Result,
17
+ Topo,
18
+ } from '@ontrails/core';
19
+ import {
20
+ buildCrossValidationSchema,
21
+ claimNextCrossBatchIndex,
22
+ createCrossBatchValidationResults,
23
+ executeTrail,
24
+ InternalError,
25
+ normalizeCrossBatchConcurrency,
26
+ Result as R,
27
+ } from '@ontrails/core';
28
+
29
+ import { assertPartialMatch, expectOk } from './assertions.js';
30
+ import { createTestContext, createMockResources } from './context.js';
31
+ import type { RefToken, ScenarioStep } from './types.js';
32
+
33
+ type ScenarioCrossTarget = string | { readonly id: string };
34
+ type ScenarioCrossCall = readonly [ScenarioCrossTarget, unknown];
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // ref() — cross-step reference marker
38
+ // ---------------------------------------------------------------------------
39
+
40
+ /**
41
+ * Create a reference marker for cross-step data in scenario inputs.
42
+ *
43
+ * `ref('create.id')` resolves to the `id` field of the step aliased as
44
+ * `create`. Dot-paths are supported for nested access.
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * scenario('Fork flow', app, [
49
+ * { cross: createGist, input: { name: 'Hello' }, as: 'original' },
50
+ * { cross: forkGist, input: { id: ref('original.id') } },
51
+ * ]);
52
+ * ```
53
+ */
54
+ export const ref = (path: string): RefToken => ({ __ref: true, path });
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // Internals
58
+ // ---------------------------------------------------------------------------
59
+
60
+ /** Type guard for RefToken. */
61
+ const isRef = (value: unknown): value is RefToken =>
62
+ typeof value === 'object' &&
63
+ value !== null &&
64
+ '__ref' in value &&
65
+ (value as Record<string, unknown>)['__ref'] === true &&
66
+ 'path' in value;
67
+
68
+ /**
69
+ * Resolve a dot-path against the outputs map.
70
+ *
71
+ * `ref('create.id')` splits into step name `create` and field path `id`.
72
+ * The first segment is the step alias; remaining segments are property lookups.
73
+ */
74
+ /**
75
+ * Walk remaining segments of a dot-path, drilling into the step output.
76
+ */
77
+ const drillPath = (
78
+ path: string,
79
+ segments: readonly string[],
80
+ start: unknown
81
+ ): unknown => {
82
+ let current: unknown = start;
83
+ for (let i = 1; i < segments.length; i += 1) {
84
+ const segment = segments[i];
85
+ if (segment === undefined) {
86
+ break;
87
+ }
88
+ if (typeof current !== 'object' || current === null) {
89
+ throw new Error(
90
+ `ref('${path}'): cannot access '${segment}' on ${typeof current}`
91
+ );
92
+ }
93
+ current = (current as Record<string, unknown>)[segment];
94
+ }
95
+ return current;
96
+ };
97
+
98
+ const resolvePath = (path: string, outputs: Map<string, unknown>): unknown => {
99
+ const segments = path.split('.');
100
+ const [stepName] = segments;
101
+ if (stepName === undefined) {
102
+ throw new Error(`ref(): empty path`);
103
+ }
104
+
105
+ const stepOutput = outputs.get(stepName);
106
+ if (stepOutput === undefined) {
107
+ throw new Error(
108
+ `ref('${path}'): no step output found for alias '${stepName}'`
109
+ );
110
+ }
111
+
112
+ return drillPath(path, segments, stepOutput);
113
+ };
114
+
115
+ /**
116
+ * Recursively walk a value, replacing RefToken instances with resolved values.
117
+ */
118
+ export const deriveRefs = (
119
+ value: unknown,
120
+ outputs: Map<string, unknown>
121
+ ): unknown => {
122
+ if (isRef(value)) {
123
+ return resolvePath(value.path, outputs);
124
+ }
125
+
126
+ if (Array.isArray(value)) {
127
+ return value.map((item) => deriveRefs(item, outputs));
128
+ }
129
+
130
+ if (typeof value === 'object' && value !== null) {
131
+ const result: Record<string, unknown> = {};
132
+ for (const [key, val] of Object.entries(value)) {
133
+ result[key] = deriveRefs(val, outputs);
134
+ }
135
+ return result;
136
+ }
137
+
138
+ return value;
139
+ };
140
+
141
+ // ---------------------------------------------------------------------------
142
+ // scenario() — the public API
143
+ // ---------------------------------------------------------------------------
144
+
145
+ /**
146
+ * Define a multi-step scenario test for composition flows.
147
+ *
148
+ * Each step invokes a trail through the normal execution pipeline.
149
+ * Steps can reference prior step outputs via `ref()`. If any step
150
+ * fails, the scenario stops and reports which step failed.
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * scenario('Create and show', app, [
155
+ * { cross: createItem, input: { name: 'Test' }, as: 'created' },
156
+ * { cross: showItem, input: { id: ref('created.id') },
157
+ * expectedMatch: { found: true } },
158
+ * ]);
159
+ * ```
160
+ */
161
+ /** Assert the result of a step against its expectations and record output. */
162
+ const assertStepExpectations = async (
163
+ step: ScenarioStep,
164
+ result: Result<unknown, Error>,
165
+ outputs: Map<string, unknown>
166
+ ): Promise<void> => {
167
+ const value = expectOk(result);
168
+ if (step.expected !== undefined) {
169
+ const { expect } = await import('bun:test');
170
+ expect(value).toEqual(deriveRefs(step.expected, outputs));
171
+ } else if (step.expectedMatch !== undefined) {
172
+ assertPartialMatch(result, deriveRefs(step.expectedMatch, outputs));
173
+ }
174
+ if (step.as !== undefined) {
175
+ outputs.set(step.as, value);
176
+ }
177
+ };
178
+
179
+ const executeUnlimitedCrossBatch = async (
180
+ calls: readonly ScenarioCrossCall[],
181
+ runCall: (
182
+ call: ScenarioCrossCall,
183
+ branchIndex: number
184
+ ) => Promise<Result<unknown, Error>>
185
+ ): Promise<Result<unknown, Error>[]> =>
186
+ await Promise.all(
187
+ calls.map((call, branchIndex) => runCall(call, branchIndex))
188
+ );
189
+
190
+ const executeLimitedCrossBatch = async (
191
+ calls: readonly ScenarioCrossCall[],
192
+ runCall: (
193
+ call: ScenarioCrossCall,
194
+ branchIndex: number
195
+ ) => Promise<Result<unknown, Error>>,
196
+ limit: number
197
+ ): Promise<Result<unknown, Error>[]> => {
198
+ const results = Array.from<Result<unknown, Error>>({ length: calls.length });
199
+ const nextIndex = { value: 0 };
200
+
201
+ const runWorker = async () => {
202
+ while (true) {
203
+ const branchIndex = claimNextCrossBatchIndex(nextIndex, calls);
204
+ if (branchIndex === undefined) {
205
+ return;
206
+ }
207
+
208
+ const call = calls[branchIndex];
209
+ if (call === undefined) {
210
+ // Defensive: `claimNextCrossBatchIndex` only returns indices within
211
+ // bounds, so this slot should always be populated. If it ever isn't,
212
+ // surface a clear InternalError in place of the missing slot and keep
213
+ // the worker loop running so sibling branches still get processed.
214
+ results[branchIndex] = R.err(
215
+ new InternalError(
216
+ `unreachable: concurrent cross batch call missing at index ${branchIndex}`
217
+ )
218
+ );
219
+ continue;
220
+ }
221
+
222
+ results[branchIndex] = await runCall(call, branchIndex);
223
+ }
224
+ };
225
+
226
+ await Promise.all(Array.from({ length: limit }, runWorker));
227
+ return results;
228
+ };
229
+
230
+ /**
231
+ * Build a cross function that resolves trails from the topo and executes
232
+ * them through the standard pipeline. Mirrors the pattern in crosses.ts
233
+ * `executeFromMap` but without recording or injection.
234
+ */
235
+ const createScenarioCross = (
236
+ app: Topo,
237
+ resources?: ResourceOverrideMap
238
+ ): CrossFn => {
239
+ const invokeCross = async (
240
+ idOrTrail: ScenarioCrossTarget,
241
+ input: unknown,
242
+ self: CrossFn
243
+ ) => {
244
+ const id = typeof idOrTrail === 'string' ? idOrTrail : idOrTrail.id;
245
+ const trailDef: AnyTrail | undefined = app.get(id);
246
+ if (trailDef === undefined) {
247
+ return R.err(new InternalError(`cross: trail "${id}" not found in topo`));
248
+ }
249
+ const baseCtx = createTestContext();
250
+ return await executeTrail(trailDef, input, {
251
+ ctx: { ...baseCtx, cross: self },
252
+ resources,
253
+ topo: app,
254
+ validationSchema: buildCrossValidationSchema(trailDef),
255
+ });
256
+ };
257
+
258
+ const executeCrossBatch = async (
259
+ calls: readonly ScenarioCrossCall[],
260
+ self: CrossFn,
261
+ options?: CrossBatchOptions
262
+ ): Promise<Result<unknown, Error>[]> => {
263
+ if (calls.length === 0) {
264
+ return [];
265
+ }
266
+
267
+ const concurrency = normalizeCrossBatchConcurrency(options);
268
+ if (concurrency.isErr()) {
269
+ return createCrossBatchValidationResults(calls, concurrency.error);
270
+ }
271
+
272
+ const runCall = async (
273
+ [target, batchInput]: ScenarioCrossCall,
274
+ _branchIndex: number
275
+ ) => await invokeCross(target, batchInput, self);
276
+
277
+ const limit = concurrency.value ?? calls.length;
278
+ return limit >= calls.length
279
+ ? await executeUnlimitedCrossBatch(calls, runCall)
280
+ : await executeLimitedCrossBatch(calls, runCall, limit);
281
+ };
282
+
283
+ const cross = async function cross(
284
+ idOrTrail: ScenarioCrossTarget | readonly ScenarioCrossCall[],
285
+ inputOrOptions?: unknown
286
+ ) {
287
+ if (Array.isArray(idOrTrail)) {
288
+ return await executeCrossBatch(
289
+ idOrTrail,
290
+ cross as CrossFn,
291
+ inputOrOptions as CrossBatchOptions | undefined
292
+ );
293
+ }
294
+
295
+ return await invokeCross(
296
+ idOrTrail as ScenarioCrossTarget,
297
+ inputOrOptions,
298
+ cross as CrossFn
299
+ );
300
+ } as CrossFn;
301
+
302
+ return cross;
303
+ };
304
+
305
+ /**
306
+ * Execute a single scenario step: run the trail, assert expectations,
307
+ * and record outputs.
308
+ */
309
+ const executeStep = async (
310
+ step: ScenarioStep,
311
+ index: number,
312
+ app: Topo,
313
+ outputs: Map<string, unknown>,
314
+ resources?: ResourceOverrideMap
315
+ ): Promise<void> => {
316
+ if (step.as !== undefined && outputs.has(step.as)) {
317
+ throw new Error(
318
+ `scenario: duplicate step alias "${step.as}" — each alias must be unique`
319
+ );
320
+ }
321
+
322
+ const scenarioCross = createScenarioCross(app, resources);
323
+ const baseCtx = createTestContext();
324
+ const resolvedInput = deriveRefs(step.input, outputs);
325
+ const result = await executeTrail(step.cross, resolvedInput, {
326
+ ctx: { ...baseCtx, cross: scenarioCross },
327
+ resources,
328
+ topo: app,
329
+ });
330
+
331
+ if (result.isErr()) {
332
+ throw new Error(
333
+ `Step ${String(index + 1)} ("${step.as ?? step.cross.id}") failed: ${result.error.message}`
334
+ );
335
+ }
336
+
337
+ await assertStepExpectations(step, result, outputs);
338
+ };
339
+
340
+ /**
341
+ * Execute scenario steps sequentially, resolving mock resources once upfront.
342
+ *
343
+ * Exported for direct use in tests that need to assert on step execution
344
+ * without the describe/test wrapper that `scenario()` provides.
345
+ */
346
+ export const executeScenarioSteps = async (
347
+ app: Topo,
348
+ steps: readonly ScenarioStep[]
349
+ ): Promise<void> => {
350
+ const outputs = new Map<string, unknown>();
351
+ const resources = await createMockResources(app);
352
+
353
+ for (const [index, step] of steps.entries()) {
354
+ await executeStep(step, index, app, outputs, resources);
355
+ }
356
+ };
357
+
358
+ export const scenario = (
359
+ name: string,
360
+ app: Topo,
361
+ steps: readonly ScenarioStep[]
362
+ ): void => {
363
+ describe(name, () => {
364
+ test('executes all steps', async () => {
365
+ await executeScenarioSteps(app, steps);
366
+ });
367
+ });
368
+ };
package/src/signals.ts ADDED
@@ -0,0 +1,221 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+
3
+ import type {
4
+ FireFn,
5
+ TrailContext,
6
+ TrailExample,
7
+ TrailExampleSignalAssertion,
8
+ } from '@ontrails/core';
9
+ import { summarizeSignalPayload } from '@ontrails/core';
10
+
11
+ export interface RecordedSignal {
12
+ readonly payload: unknown;
13
+ readonly signalId: string;
14
+ }
15
+
16
+ export interface SignalAssertionHarness {
17
+ readonly assert: () => void;
18
+ readonly ctx: TrailContext;
19
+ }
20
+
21
+ const noop = (): void => undefined;
22
+
23
+ const resolveSignalId = (signal: unknown): string => {
24
+ if (typeof signal === 'string') {
25
+ return signal;
26
+ }
27
+ if (
28
+ typeof signal === 'object' &&
29
+ signal !== null &&
30
+ 'id' in signal &&
31
+ typeof (signal as { readonly id: unknown }).id === 'string'
32
+ ) {
33
+ return (signal as { readonly id: string }).id;
34
+ }
35
+ return '<unknown signal>';
36
+ };
37
+
38
+ const assertionSignalId = (assertion: TrailExampleSignalAssertion): string =>
39
+ resolveSignalId(assertion.signal);
40
+
41
+ const formatPayloadSummary = (payload: unknown): string => {
42
+ const summary = summarizeSignalPayload(payload);
43
+ const parts = [
44
+ `redacted=${summary.redacted}`,
45
+ `shape=${summary.shape}`,
46
+ `digest=${summary.digest}`,
47
+ ];
48
+ if (summary.topLevelEntryCount !== undefined) {
49
+ parts.push(`topLevelEntryCount=${summary.topLevelEntryCount}`);
50
+ }
51
+ return `{${parts.join(' ')}}`;
52
+ };
53
+
54
+ const formatAssertion = (assertion: TrailExampleSignalAssertion): string => {
55
+ const parts = [`signal=${assertionSignalId(assertion)}`];
56
+ if (assertion.payload !== undefined) {
57
+ parts.push(`payloadSummary=${formatPayloadSummary(assertion.payload)}`);
58
+ }
59
+ if (assertion.payloadMatch !== undefined) {
60
+ parts.push(
61
+ `payloadMatchSummary=${formatPayloadSummary(assertion.payloadMatch)}`
62
+ );
63
+ }
64
+ if (assertion.times !== undefined) {
65
+ parts.push(`times=${assertion.times}`);
66
+ }
67
+ return parts.join(' ');
68
+ };
69
+
70
+ const formatObserved = (observed: readonly RecordedSignal[]): string => {
71
+ if (observed.length === 0) {
72
+ return '<none>';
73
+ }
74
+ return observed
75
+ .map(
76
+ (record) =>
77
+ `${record.signalId} payloadSummary=${formatPayloadSummary(record.payload)}`
78
+ )
79
+ .join('; ');
80
+ };
81
+
82
+ const subsetArrayMatches = (
83
+ actual: readonly unknown[],
84
+ expected: readonly unknown[]
85
+ ): boolean => {
86
+ const consumed = new Set<number>();
87
+ for (const expectedItem of expected) {
88
+ const matchIndex = actual.findIndex(
89
+ (actualItem, index) =>
90
+ !consumed.has(index) &&
91
+ // oxlint-disable-next-line no-use-before-define -- mutual recursion with subsetMatches
92
+ subsetMatches(actualItem, expectedItem)
93
+ );
94
+ if (matchIndex === -1) {
95
+ return false;
96
+ }
97
+ consumed.add(matchIndex);
98
+ }
99
+ return true;
100
+ };
101
+
102
+ const subsetObjectMatches = (
103
+ actual: Record<string, unknown>,
104
+ expected: Record<string, unknown>
105
+ ): boolean =>
106
+ Object.keys(expected).every(
107
+ (key) =>
108
+ key in actual &&
109
+ // oxlint-disable-next-line no-use-before-define -- mutual recursion with subsetMatches
110
+ subsetMatches(actual[key], expected[key])
111
+ );
112
+
113
+ const subsetMatches = (actual: unknown, expected: unknown): boolean => {
114
+ if (Array.isArray(expected)) {
115
+ return Array.isArray(actual) && subsetArrayMatches(actual, expected);
116
+ }
117
+ if (expected !== null && typeof expected === 'object') {
118
+ return (
119
+ actual !== null &&
120
+ typeof actual === 'object' &&
121
+ !Array.isArray(actual) &&
122
+ subsetObjectMatches(
123
+ actual as Record<string, unknown>,
124
+ expected as Record<string, unknown>
125
+ )
126
+ );
127
+ }
128
+ return isDeepStrictEqual(actual, expected);
129
+ };
130
+
131
+ const payloadMatches = (
132
+ payload: unknown,
133
+ assertion: TrailExampleSignalAssertion
134
+ ): boolean => {
135
+ if (
136
+ assertion.payload !== undefined &&
137
+ !isDeepStrictEqual(payload, assertion.payload)
138
+ ) {
139
+ return false;
140
+ }
141
+ if (
142
+ assertion.payloadMatch !== undefined &&
143
+ !subsetMatches(payload, assertion.payloadMatch)
144
+ ) {
145
+ return false;
146
+ }
147
+ return true;
148
+ };
149
+
150
+ const signalMatches = (
151
+ record: RecordedSignal,
152
+ assertion: TrailExampleSignalAssertion
153
+ ): boolean =>
154
+ record.signalId === assertionSignalId(assertion) &&
155
+ payloadMatches(record.payload, assertion);
156
+
157
+ const assertValidTimes = (assertion: TrailExampleSignalAssertion): number => {
158
+ const times = assertion.times ?? 1;
159
+ if (!Number.isInteger(times) || times < 1) {
160
+ throw new Error(
161
+ `Signal assertion has invalid times value: ${formatAssertion(assertion)}`
162
+ );
163
+ }
164
+ return times;
165
+ };
166
+
167
+ const assertSignalAssertion = (
168
+ example: TrailExample<unknown, unknown>,
169
+ assertion: TrailExampleSignalAssertion,
170
+ observed: readonly RecordedSignal[],
171
+ consumed: Set<number>
172
+ ): void => {
173
+ const times = assertValidTimes(assertion);
174
+ for (let count = 0; count < times; count += 1) {
175
+ const matchIndex = observed.findIndex(
176
+ (record, index) =>
177
+ !consumed.has(index) && signalMatches(record, assertion)
178
+ );
179
+ if (matchIndex === -1) {
180
+ throw new Error(
181
+ `Example "${example.name}" expected signal ${formatAssertion(
182
+ assertion
183
+ )}; observed ${formatObserved(observed)}`
184
+ );
185
+ }
186
+ consumed.add(matchIndex);
187
+ }
188
+ };
189
+
190
+ export const assertSignalAssertions = (
191
+ example: TrailExample<unknown, unknown>,
192
+ observed: readonly RecordedSignal[]
193
+ ): void => {
194
+ const consumed = new Set<number>();
195
+ for (const assertion of example.signals ?? []) {
196
+ assertSignalAssertion(example, assertion, observed, consumed);
197
+ }
198
+ };
199
+
200
+ export const withSignalAssertions = (
201
+ ctx: TrailContext,
202
+ example: TrailExample<unknown, unknown>
203
+ ): SignalAssertionHarness => {
204
+ if (example.signals === undefined || example.signals.length === 0) {
205
+ return { assert: noop, ctx };
206
+ }
207
+
208
+ const observed: RecordedSignal[] = [];
209
+ const baseFire = ctx.fire as
210
+ | ((signal: unknown, payload: unknown) => Promise<void>)
211
+ | undefined;
212
+ const fire = (async (signal: unknown, payload: unknown): Promise<void> => {
213
+ observed.push({ payload, signalId: resolveSignalId(signal) });
214
+ await baseFire?.(signal, payload);
215
+ }) as FireFn;
216
+
217
+ return {
218
+ assert: () => assertSignalAssertions(example, observed),
219
+ ctx: { ...ctx, fire },
220
+ };
221
+ };
package/src/types.ts CHANGED
@@ -2,8 +2,16 @@
2
2
  * Shared types for @ontrails/testing.
3
3
  */
4
4
 
5
- import type { Logger, Topo } from '@ontrails/core';
6
- import type { LogLevel, LogRecord } from '@ontrails/logging';
5
+ import type { DeriveCliCommandsOptions } from '@ontrails/cli';
6
+ import type { McpExtra, DeriveMcpToolsOptions } from '@ontrails/mcp';
7
+ import type {
8
+ AnyTrail,
9
+ Logger,
10
+ Topo,
11
+ TraceFn,
12
+ TrailContext,
13
+ } from '@ontrails/core';
14
+ import type { LogLevel, LogRecord } from '@ontrails/observe';
7
15
 
8
16
  // ---------------------------------------------------------------------------
9
17
  // Test Scenario (for testTrail)
@@ -66,6 +74,7 @@ export interface TestTrailContextOptions {
66
74
  readonly logger?: Logger | undefined;
67
75
  readonly requestId?: string | undefined;
68
76
  readonly abortSignal?: AbortSignal | undefined;
77
+ readonly trace?: TraceFn | undefined;
69
78
  }
70
79
 
71
80
  // ---------------------------------------------------------------------------
@@ -73,8 +82,12 @@ export interface TestTrailContextOptions {
73
82
  // ---------------------------------------------------------------------------
74
83
 
75
84
  /** Options for creating a CLI harness. */
76
- export interface CliHarnessOptions {
77
- readonly app: Topo;
85
+ export interface CliHarnessOptions extends Omit<
86
+ DeriveCliCommandsOptions,
87
+ 'onResult' | 'presets' | 'resolveInput'
88
+ > {
89
+ readonly ctx?: Partial<TrailContext> | undefined;
90
+ readonly graph: Topo;
78
91
  }
79
92
 
80
93
  /** A test harness for CLI commands. */
@@ -97,8 +110,9 @@ export interface CliHarnessResult {
97
110
  // ---------------------------------------------------------------------------
98
111
 
99
112
  /** Options for creating an MCP harness. */
100
- export interface McpHarnessOptions {
101
- readonly app: Topo;
113
+ export interface McpHarnessOptions extends DeriveMcpToolsOptions {
114
+ readonly extra?: Partial<McpExtra> | undefined;
115
+ readonly graph: Topo;
102
116
  }
103
117
 
104
118
  /** A test harness for MCP tools. */
@@ -115,3 +129,47 @@ export interface McpHarnessResult {
115
129
  readonly content: unknown;
116
130
  readonly isError: boolean;
117
131
  }
132
+
133
+ // ---------------------------------------------------------------------------
134
+ // Established verification
135
+ // ---------------------------------------------------------------------------
136
+
137
+ export interface TestAllEstablishedOptions {
138
+ readonly cli?: Omit<CliHarnessOptions, 'graph'> | undefined;
139
+ readonly createPermit?:
140
+ | ((trail: {
141
+ readonly permit?:
142
+ | { readonly scopes: readonly string[] }
143
+ | 'public'
144
+ | undefined;
145
+ }) =>
146
+ | {
147
+ readonly id: string;
148
+ readonly scopes: readonly string[];
149
+ }
150
+ | undefined)
151
+ | undefined;
152
+ readonly ctx?: Partial<TrailContext> | undefined;
153
+ readonly mcp?: Omit<McpHarnessOptions, 'graph'> | undefined;
154
+ readonly resources?: Record<string, unknown> | undefined;
155
+ readonly strictPermits?: boolean | undefined;
156
+ }
157
+
158
+ // ---------------------------------------------------------------------------
159
+ // Scenario (for composition testing)
160
+ // ---------------------------------------------------------------------------
161
+
162
+ /** Marker for cross-step references in scenario inputs. */
163
+ export interface RefToken {
164
+ readonly __ref: true;
165
+ readonly path: string;
166
+ }
167
+
168
+ /** A single step in a scenario. */
169
+ export interface ScenarioStep {
170
+ readonly cross: AnyTrail;
171
+ readonly input: Record<string, unknown>;
172
+ readonly as?: string | undefined;
173
+ readonly expected?: unknown | undefined;
174
+ readonly expectedMatch?: unknown | undefined;
175
+ }
@@ -1 +0,0 @@
1
- $ tsc -b
@@ -1,3 +0,0 @@
1
- $ oxlint ./src
2
- Found 0 warnings and 0 errors.
3
- Finished in 29ms on 22 files with 93 rules using 24 threads.
@@ -1 +0,0 @@
1
- $ tsc --noEmit