@lunora/testing 1.0.0-alpha.11 → 1.0.0-alpha.111

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.
package/dist/index.d.mts CHANGED
@@ -1,17 +1,221 @@
1
- import { ScheduledJob, RegisteredAction, RegisteredMutation, RegisteredQuery, ArgsValidator, InferArgs, ActionCtx, MutationCtx, QueryCtx, TableDefinition, Schema } from '@lunora/server';
2
- export { type InboxOptions, type WaitForMailOptions, extractLink, listCapturedMail, waitForMail } from '@lunora/mail/testing';
1
+ import { AgentMessageRow, AgentRunInput, AgentGenerateResult, AgentRunResult, AgentDefinition } from '@lunora/agent';
2
+ import { ScheduledJob, RegisteredAction, RegisteredMutation, RegisteredQuery, ArgsValidator, InferArgs, ActionCtx, MutationCtx, QueryCtx, LogFields, TableDefinition, Schema } from '@lunora/server';
3
+ export {
4
+ /**
5
+ * `@lunora/testing` — the user-facing toolkit for end-to-end testing a Lunora app.
6
+ *
7
+ * Today it surfaces the dev mail-catcher helpers from `@lunora/mail/testing`: in
8
+ * `lunora dev` every outbound email (sign-up verification, forgot-password, magic
9
+ * links) is captured into the studio's root-shard inbox instead of hitting a real
10
+ * provider, and these helpers read that inbox over the admin RPC so a Playwright
11
+ * test can drive "request reset → read the email → follow the link → set a new
12
+ * password" deterministically.
13
+ *
14
+ * This is the home for E2E fixtures to grow into — auth helpers and more — so
15
+ * tests import one package (`@lunora/testing`) rather than reaching into each
16
+ * sub-package's `/testing` entry.
17
+ */
18
+ type InboxOptions,
19
+ /**
20
+ * `@lunora/testing` — the user-facing toolkit for end-to-end testing a Lunora app.
21
+ *
22
+ * Today it surfaces the dev mail-catcher helpers from `@lunora/mail/testing`: in
23
+ * `lunora dev` every outbound email (sign-up verification, forgot-password, magic
24
+ * links) is captured into the studio's root-shard inbox instead of hitting a real
25
+ * provider, and these helpers read that inbox over the admin RPC so a Playwright
26
+ * test can drive "request reset → read the email → follow the link → set a new
27
+ * password" deterministically.
28
+ *
29
+ * This is the home for E2E fixtures to grow into — auth helpers and more — so
30
+ * tests import one package (`@lunora/testing`) rather than reaching into each
31
+ * sub-package's `/testing` entry.
32
+ */
33
+ type WaitForMailOptions, extractLink, listCapturedMail, waitForMail } from '@lunora/mail/testing';
34
+ /** A thread message as the in-memory runtime stores it (superset of {@link AgentMessageRow}). */
35
+ interface HarnessMessage extends AgentMessageRow {
36
+ messageKey: string;
37
+ threadKey: string;
38
+ }
39
+ /** A thread record as the in-memory runtime stores it. */
40
+ interface HarnessThread {
41
+ agent: string;
42
+ error?: string;
43
+ instanceId?: string;
44
+ key: string;
45
+ messageCount: number;
46
+ owner?: string;
47
+ status: string;
48
+ title?: string;
49
+ usage?: unknown;
50
+ }
51
+ /** One recorded function dispatch the loop made through `ctx.run`. */
52
+ interface HarnessDispatch {
53
+ args: Record<string, unknown> | undefined;
54
+ path: string;
55
+ }
56
+ /** Extra function-dispatch handler layered over the built-in `agents:*` runtime double. */
57
+ type HarnessFunction = (args?: Record<string, unknown>) => unknown;
58
+ interface AgentHarnessOptions {
59
+ /**
60
+ * Worker `env` bindings visible to tool `execute` and a dynamic
61
+ * `instructions` thunk. Default `{ LUNORA_TEST: true }`.
62
+ */
63
+ env?: Record<string, unknown>;
64
+ /**
65
+ * The agent's `lunora/agents.ts` export name — used for thread attribution
66
+ * and to derive the child-agent `AGENT_*` bindings a sub-agent tool targets.
67
+ * Default `"agent"`.
68
+ */
69
+ exportName?: string;
70
+ /**
71
+ * Stub the app functions a tool's `execute` (or the agent's `memory.source`)
72
+ * dispatches through `ctx.run`, keyed by function path (`"weather:lookup"`).
73
+ * A handler layered here shadows the built-in `agents:*` runtime double for
74
+ * that path. An unstubbed non-`agents:*` dispatch throws, so a missing stub
75
+ * fails loudly rather than silently returning `undefined`.
76
+ */
77
+ functions?: Record<string, HarnessFunction>;
78
+ /**
79
+ * Scripted model decisions, one {@link AgentGenerateResult} per LLM turn —
80
+ * the default script for {@link AgentHarness.run}. A terminal turn has an
81
+ * empty `toolCalls`; a tool-calling turn lists the calls the loop then runs
82
+ * against the agent's own tools. Override per run via `run(..., { script })`.
83
+ */
84
+ script: AgentGenerateResult[];
85
+ }
86
+ /** Per-run overrides for {@link AgentHarness.run}. */
87
+ interface AgentRunOverrides {
88
+ /** The workflow instance id for this run (default: an auto-incrementing `wf-N`). */
89
+ instanceId?: string;
90
+ /** The model script for THIS run, replacing the harness default. */
91
+ script?: AgentGenerateResult[];
92
+ }
93
+ interface AgentHarness {
94
+ /**
95
+ * Every function dispatch the loop has made through `ctx.run`, in order —
96
+ * both the `agents:*` runtime calls and the tool/memory app dispatches. Use
97
+ * it to assert a tool called the function you expected with the args you
98
+ * expected.
99
+ */
100
+ readonly dispatches: ReadonlyArray<HarnessDispatch>;
101
+ /** The persisted messages of a thread, ordered by `seq`. */
102
+ messages: (threadKey: string) => AgentMessageRow[];
103
+ /**
104
+ * Drive one durable agent run to completion against the in-memory journal +
105
+ * runtime double, returning the loop's {@link AgentRunResult}. Reuse the same
106
+ * `threadKey` across calls to continue a conversation (the persisted history
107
+ * carries over); each call runs under a fresh instance id, modelling a
108
+ * distinct workflow instance.
109
+ */
110
+ run: (params: AgentRunInput, overrides?: AgentRunOverrides) => Promise<AgentRunResult>;
111
+ /** The stored thread record (status, error, instanceId, usage, …), or `undefined` before its first run. */
112
+ thread: (threadKey: string) => HarnessThread | undefined;
113
+ }
114
+ /**
115
+ * A unit-test harness for a `defineAgent` tool-loop that runs WITHOUT a real
116
+ * model or network. It drives {@link runAgentLoop} over the agent's own
117
+ * `AgentGenerate` seam — the model is a script of per-turn decisions, tool calls
118
+ * run the agent's real `execute` functions inside an in-memory durable-step
119
+ * journal, and thread/message persistence goes through an in-memory `agents:*`
120
+ * runtime double. Mock any function a tool (or the agent's memory) dispatches
121
+ * through the `functions` option.
122
+ *
123
+ * ```ts
124
+ * const harness = agentHarness(support, {
125
+ * script: [toolCallTurn("c1", "lookup", { id: "o_1" }), finalTurn("It shipped.")],
126
+ * functions: { "orders:lookup": () => ({ status: "shipped" }) },
127
+ * });
128
+ * const result = await harness.run({ input: "where is my order?", threadKey: "t1" });
129
+ * expect(result.text).toBe("It shipped.");
130
+ * expect(harness.messages("t1").at(-1)?.content).toBe("It shipped.");
131
+ * ```
132
+ *
133
+ * The harness deliberately does NOT model the concurrency guard or a
134
+ * human-in-the-loop approval pause — it is for exercising an agent's tools and
135
+ * turn logic, not the durable orchestration itself (that is covered inside
136
+ * `@lunora/agent`).
137
+ */
138
+ declare const agentHarness: (agent: AgentDefinition, options: AgentHarnessOptions) => AgentHarness;
139
+ /** A terminal (final-answer) turn — no tool calls. */
140
+ declare const finalTurn: (text: string, extra?: Partial<AgentGenerateResult>) => AgentGenerateResult;
141
+ /** A single-tool-call turn: the loop runs the named tool with `input`. */
142
+ declare const toolCallTurn: (id: string, name: string, input: unknown, text?: string) => AgentGenerateResult;
143
+ /** The primitive an eval attaches to a span: a numeric score or a string label. */
144
+ type EvaluationAttributeValue = number | string;
145
+ /**
146
+ * Structural slice of the post-hoc span handle `ctx.trace` hands its body (see the
147
+ * server `SpanHandle`) — enough to attach an eval's attributes. Declared here
148
+ * rather than imported so `@lunora/testing` takes no dependency on `@lunora/server`
149
+ * or `@lunora/do`; the real handle is assignable to it.
150
+ */
151
+ interface EvaluationSpanHandle {
152
+ setAttributes: (fields: Record<string, EvaluationAttributeValue>) => void;
153
+ }
154
+ /**
155
+ * Structural slice of `ctx.metrics` — enough to record a score as a durable
156
+ * series. Declared here for the same reason as {@link EvaluationSpanHandle}: no
157
+ * dependency on `@lunora/server`, and the real handle is assignable.
158
+ */
159
+ interface EvaluationMetrics {
160
+ gauge: (name: string, value: number, attributes?: Record<string, unknown>) => void;
161
+ }
162
+ /** One eval verdict to emit. */
163
+ interface RecordEvaluationInput {
164
+ /**
165
+ * Optional categorical label (e.g. `"pass"` / `"fail"` / a rubric bucket),
166
+ * emitted as the `.label` attribute. Omitted → no label attribute.
167
+ */
168
+ label?: string;
169
+ /**
170
+ * Optional `ctx.metrics` handle. Passing it ALSO records the score as a
171
+ * `gen_ai.evaluation.<name>.score` gauge, which is what gives an eval a
172
+ * durable history: span attributes live in the shard's bounded in-memory
173
+ * ring and vanish on hibernation, while metrics are persisted in per-minute
174
+ * buckets and can be charted as a trend. Additive — the attributes are
175
+ * emitted either way.
176
+ */
177
+ metrics?: EvaluationMetrics;
178
+ /**
179
+ * The scorer/evaluation name — becomes the key's name segment. Any character
180
+ * outside `[A-Za-z0-9._-]` is replaced with `_` so a scorer name carrying a
181
+ * colon (e.g. `"contains:shipped"`) still yields a well-formed attribute key.
182
+ */
183
+ name: string;
184
+ /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
185
+ score: number;
186
+ /**
187
+ * Optional generation span to attach the attributes to — the post-hoc
188
+ * `SpanHandle` a `ctx.trace` body receives. Omitted → nothing is attached and
189
+ * the caller uses the returned bag for a standalone event/metric.
190
+ */
191
+ span?: EvaluationSpanHandle;
192
+ }
193
+ /**
194
+ * Build the `gen_ai.evaluation.NAME.*` attribute bag for one eval verdict — the
195
+ * `.score` (number) always, the `.label` (string) when a label is given. Exported
196
+ * so a caller can emit the score as a standalone event/metric without a span.
197
+ */
198
+ declare const evaluationAttributes: (input: Pick<RecordEvaluationInput, "label" | "name" | "score">) => Record<string, EvaluationAttributeValue>;
199
+ /**
200
+ * Emit one eval verdict as `gen_ai.evaluation.NAME.*` attributes. Attaches them to
201
+ * `input.span` when supplied (the post-hoc generation-span handle), and always
202
+ * returns the attribute bag so a span-less caller can ship it as an eval
203
+ * event/metric. Privacy-safe: only the name, score, and optional label are
204
+ * emitted — never the graded prompt or output.
205
+ */
206
+ declare const recordEvaluation: (input: RecordEvaluationInput) => Record<string, EvaluationAttributeValue>;
3
207
  /** A pending job entry in the fake scheduler queue. */
4
208
  interface FakeScheduledJob extends ScheduledJob {
5
209
  /** The args the job was scheduled with. */
6
210
  args: Record<string, unknown>;
7
211
  }
8
212
  /**
9
- * A single scheduled-job failure captured during an `advance()` / `runPending()`
10
- * sweep. Production's scheduler isolates per-job failures (one bad job does not
11
- * abort the rest), so the fake scheduler does the same — but, being a test
12
- * harness, it never swallows the error: every failure is recorded here so tests
13
- * can still assert on it.
14
- */
213
+ * A single scheduled-job failure captured during an `advance()` / `runPending()`
214
+ * sweep. Production's scheduler isolates per-job failures (one bad job does not
215
+ * abort the rest), so the fake scheduler does the same — but, being a test
216
+ * harness, it never swallows the error: every failure is recorded here so tests
217
+ * can still assert on it.
218
+ */
15
219
  interface ScheduledJobFailure {
16
220
  /** The args the job was dispatched with. */
17
221
  args: Record<string, unknown>;
@@ -23,94 +227,85 @@ interface ScheduledJobFailure {
23
227
  id: string;
24
228
  }
25
229
  /**
26
- * Controls exposed on the test harness for the fake in-memory scheduler.
27
- * Access via `harness.scheduler`.
28
- */
230
+ * Controls exposed on the test harness for the fake in-memory scheduler.
231
+ * Access via `harness.scheduler`.
232
+ */
29
233
  interface FakeSchedulerControls {
30
234
  /**
31
- * Advance the virtual clock by `ms` milliseconds, executing all jobs whose
32
- * `scheduledFor` timestamp is now at or before the new virtual "now". Jobs
33
- * are dispatched in `scheduledFor` order (oldest first). Newly queued jobs
34
- * (scheduled by an executed job during the advance) are NOT re-evaluated in
35
- * the same advance call — callers should advance again if needed.
36
- *
37
- * Per-job failures are isolated (matching production): a job that throws does
38
- * NOT prevent the remaining due jobs from running. After every due job has
39
- * run, the failures are surfaced — they are recorded on
40
- * {@link FakeSchedulerControls.failures} and, by default, re-thrown so a test
41
- * still sees the error. A single failure is re-thrown verbatim; multiple
42
- * failures are aggregated into an `AggregateError`. Pass
43
- * `{ throwOnError: false }` to suppress the re-throw and inspect
44
- * {@link FakeSchedulerControls.failures} (and the returned count) instead.
45
- *
46
- * Returns the number of jobs that were executed (including failed ones).
47
- */
235
+ * Advance the virtual clock by `ms` milliseconds, executing all jobs whose
236
+ * `scheduledFor` timestamp is now at or before the new virtual "now". Jobs
237
+ * are dispatched in `scheduledFor` order (oldest first). Newly queued jobs
238
+ * (scheduled by an executed job during the advance) are NOT re-evaluated in
239
+ * the same advance call — callers should advance again if needed.
240
+ *
241
+ * Per-job failures are isolated (matching production): a job that throws does
242
+ * NOT prevent the remaining due jobs from running. After every due job has
243
+ * run, the failures are surfaced — they are recorded on
244
+ * {@link FakeSchedulerControls.failures} and, by default, re-thrown so a test
245
+ * still sees the error. A single failure is re-thrown verbatim; multiple
246
+ * failures are aggregated into an `AggregateError`. Pass
247
+ * `{ throwOnError: false }` to suppress the re-throw and inspect
248
+ * {@link FakeSchedulerControls.failures} (and the returned count) instead.
249
+ *
250
+ * Returns the number of jobs that were executed (including failed ones).
251
+ */
48
252
  advance: (ms: number, options?: SweepOptions) => Promise<number>;
49
253
  /**
50
- * All scheduled-job failures captured so far, in execution order, across
51
- * every `advance()` / `runPending()` call on this harness. Always available,
52
- * even when `throwOnError: false` suppressed the re-throw. The list is a
53
- * snapshot — mutating it does not affect the scheduler.
54
- */
254
+ * All scheduled-job failures captured so far, in execution order, across
255
+ * every `advance()` / `runPending()` call on this harness. Always available,
256
+ * even when `throwOnError: false` suppressed the re-throw. The list is a
257
+ * snapshot — mutating it does not affect the scheduler.
258
+ */
55
259
  failures: () => ScheduledJobFailure[];
56
260
  /**
57
- * List all pending jobs (those not yet executed or cancelled) in the order
58
- * they were enqueued.
59
- */
261
+ * List all pending jobs (those not yet executed or cancelled) in the order
262
+ * they were enqueued.
263
+ */
60
264
  list: () => FakeScheduledJob[];
61
265
  /**
62
- * Execute all currently pending jobs regardless of their `scheduledFor`
63
- * time. Equivalent to advancing to `Infinity`. Returns the number of jobs
64
- * executed (including failed ones).
65
- *
66
- * Failure isolation and surfacing match {@link FakeSchedulerControls.advance}:
67
- * one failing job does not abort the rest, and failures are recorded on
68
- * {@link FakeSchedulerControls.failures} and re-thrown unless
69
- * `{ throwOnError: false }` is passed.
70
- */
266
+ * Execute all currently pending jobs regardless of their `scheduledFor`
267
+ * time. Equivalent to advancing to `Infinity`. Returns the number of jobs
268
+ * executed (including failed ones).
269
+ *
270
+ * Failure isolation and surfacing match {@link FakeSchedulerControls.advance}:
271
+ * one failing job does not abort the rest, and failures are recorded on
272
+ * {@link FakeSchedulerControls.failures} and re-thrown unless
273
+ * `{ throwOnError: false }` is passed.
274
+ */
71
275
  runPending: (options?: SweepOptions) => Promise<number>;
72
276
  }
73
277
  /** Options controlling how an `advance()` / `runPending()` sweep surfaces failures. */
74
278
  interface SweepOptions {
75
279
  /**
76
- * When `true` (the default), failures encountered during the sweep are
77
- * re-thrown after every due job has run — a single failure verbatim, multiple
78
- * as an `AggregateError`. When `false`, the sweep resolves normally and
79
- * failures are observable only via {@link FakeSchedulerControls.failures}.
80
- */
280
+ * When `true` (the default), failures encountered during the sweep are
281
+ * re-thrown after every due job has run — a single failure verbatim, multiple
282
+ * as an `AggregateError`. When `false`, the sweep resolves normally and
283
+ * failures are observable only via {@link FakeSchedulerControls.failures}.
284
+ */
81
285
  throwOnError?: boolean;
82
286
  }
83
287
  /**
84
- * Top-level dispatch for a scheduled job — wired by the harness. Unlike the
85
- * `runInternal` closure used by `ctx.run*` composition (which rides whatever
86
- * transaction span is already open), a scheduled job is a fresh top-level entry:
87
- * production dispatches it back to the Worker as its own RPC, so a scheduled
88
- * `mutation` runs inside its own BEGIN/COMMIT span and notifies subscription
89
- * listeners on success. The harness supplies a callback that reproduces those
90
- * semantics (mutations wrapped + notified; actions run unwrapped).
91
- */
92
- /**
93
- * The schema value produced by `@lunora/server`'s `defineSchema`. Accepted
94
- * structurally; internally it is handed to `@lunora/do`'s `runShardMigrations` /
95
- * `createShardCtxDb`, whose `SchemaLike` is the same shape declared in the DO
96
- * package — the two are structurally compatible at runtime (only their
97
- * independently-declared trigger nesting drifts at the type level), so the
98
- * boundary cast below is sound.
99
- */
288
+ * The schema value produced by `@lunora/server`'s `defineSchema`. Accepted
289
+ * structurally; internally it is handed to `@lunora/do`'s `runShardMigrations` /
290
+ * `createShardCtxDb`, whose `SchemaLike` is the same shape declared in the DO
291
+ * package the two are structurally compatible at runtime (only their
292
+ * independently-declared trigger nesting drifts at the type level), so the
293
+ * boundary cast below is sound.
294
+ */
100
295
  type TestSchema = Schema<Record<string, TableDefinition>>;
101
296
  /**
102
- * A user-supplied identity, surfaced to handlers via `ctx.auth`. `userId` is the
103
- * subject the handler reads from `ctx.auth.userId`; any additional fields are
104
- * returned verbatim from `ctx.auth.getIdentity()` (mirroring a decoded JWT).
105
- */
297
+ * A user-supplied identity, surfaced to handlers via `ctx.auth`. `userId` is the
298
+ * subject the handler reads from `ctx.auth.userId`; any additional fields are
299
+ * returned verbatim from `ctx.auth.getIdentity()` (mirroring a decoded JWT).
300
+ */
106
301
  interface TestIdentity extends Record<string, unknown> {
107
302
  userId?: null | string;
108
303
  }
109
304
  /**
110
- * An async iterable/iterator returned by {@link TestHarness.subscribe}.
111
- * Guarantees `return()` is always defined (unlike the optional `AsyncIterator.return`),
112
- * so callers can always unsubscribe without a `?.` guard.
113
- */
305
+ * An async iterable/iterator returned by {@link TestHarness.subscribe}.
306
+ * Guarantees `return()` is always defined (unlike the optional `AsyncIterator.return`),
307
+ * so callers can always unsubscribe without a `?.` guard.
308
+ */
114
309
  interface TestSubscription<R> extends AsyncIterable<R> {
115
310
  next: () => Promise<IteratorResult<R, R>>;
116
311
  return: () => Promise<IteratorResult<R, R>>;
@@ -120,75 +315,117 @@ type InlineQueryFunction<R> = (context: QueryCtx) => Promise<R> | R;
120
315
  type InlineMutationFunction<R> = (context: MutationCtx) => Promise<R> | R;
121
316
  type InlineActionFunction<R> = (context: ActionCtx) => Promise<R> | R;
122
317
  /**
123
- * A map from function path strings (e.g. `"messages:send"`) to their
124
- * registered function objects. Used by the fake scheduler to resolve
125
- * `ctx.scheduler.runAfter(delay, "messages:send", args)` → handler invocation.
126
- *
127
- * Only mutations and actions can be scheduled in production; queries passed
128
- * here will be accepted but produce a console.warn at dispatch time.
129
- *
130
- * The value type uses `any` because `RegisteredFunction` is contravariant in its
131
- * args type parameter — a `RegisteredMutation` with concrete args is not assignable
132
- * to `RegisteredMutation` with `ArgsValidator` at the type level even though at
133
- * runtime it is sound (the fake scheduler passes `Record&lt;string, unknown>` to
134
- * `handler` and ignores the return value).
135
- */
318
+ * A map from function path strings (e.g. `"messages:send"`) to their
319
+ * registered function objects. Used by the fake scheduler to resolve
320
+ * `ctx.scheduler.runAfter(delay, "messages:send", args)` → handler invocation.
321
+ *
322
+ * Only mutations and actions can be scheduled in production; queries passed
323
+ * here will be accepted but produce a console.warn at dispatch time.
324
+ *
325
+ * The value type uses `any` because `RegisteredFunction` is contravariant in its
326
+ * args type parameter — a `RegisteredMutation` with concrete args is not assignable
327
+ * to `RegisteredMutation` with `ArgsValidator` at the type level even though at
328
+ * runtime it is sound (the fake scheduler passes `Record<string, unknown>` to
329
+ * `handler` and ignores the return value).
330
+ */
136
331
  type FunctionRegistry = Record<string, RegisteredAction<any, any> | RegisteredMutation<any, any> | RegisteredQuery<any, any>>;
137
332
  /**
138
- * Options accepted by {@link lunoraTest}.
139
- *
140
- * All options are optional — `lunoraTest(schema)` preserves v1 behaviour with
141
- * clearly-throwing stubs for unsupported surfaces.
142
- */
333
+ * Options accepted by {@link lunoraTest}.
334
+ *
335
+ * All options are optional — `lunoraTest(schema)` preserves v1 behaviour with
336
+ * clearly-throwing stubs for unsupported surfaces.
337
+ */
143
338
  interface LunoraTestOptions {
144
339
  /**
145
- * Injectable `fetch` implementation for action contexts. When provided,
146
- * `ctx.fetch` in every `action` (and `withIdentity` views) resolves to this
147
- * function rather than throwing the "not available in v1" stub.
148
- *
149
- * Pass `vi.fn()` or any `typeof globalThis.fetch` compatible implementation.
150
- * @example
151
- * ```ts
152
- * const fakeFetch = vi.fn().mockResolvedValue(Response.json({ ok: true }));
153
- * const t = lunoraTest(schema, { fetch: fakeFetch });
154
- * ```
155
- */
340
+ * Enforce the secure-by-default RLS guard on the writer registered
341
+ * procedures dispatch through (`query`/`mutation`/`action`, via
342
+ * `reference.handler`) the same `enforceRls: true` production's generated
343
+ * `buildCtx` always passes. Under a `.rls("required")` schema, a procedure
344
+ * that touches a known, non-`.public()` table without `.use(rls(...))` in
345
+ * its chain rejects with `RlsRequiredError`, exactly as it would on first
346
+ * dispatch in production. Defaults to `true` so a green suite means the
347
+ * deploy is RLS-safe; the harness's other surfaces — `t.run` and any
348
+ * `@lunora/seed` helper built on it stay on the trusted, UNGUARDED writer
349
+ * regardless of this flag (mirroring production's admin/migration system
350
+ * paths).
351
+ *
352
+ * Set to `false` to opt back into the pre-guard permissive behaviour (every
353
+ * `lunoraTest` release before this option existed): every procedure's
354
+ * `ctx.db` goes unguarded even under a `.rls("required")` schema. This
355
+ * forfeits the "a passing suite means the deploy is safe" guarantee — a
356
+ * procedure that forgot `.use(rls(...))` will pass in tests and throw
357
+ * `RlsRequiredError` on its first production request. No effect when the
358
+ * schema does not declare `.rls("required")` (the guard is a no-op there
359
+ * either way).
360
+ * @default true
361
+ * @example
362
+ * ```ts
363
+ * // Restores the old permissive behavior for a suite not yet migrated.
364
+ * const t = lunoraTest(schema, { enforceRls: false });
365
+ * ```
366
+ */
367
+ enforceRls?: boolean;
368
+ /**
369
+ * Injectable `ctx.env` for every context (query / mutation / action). When
370
+ * provided, handlers that read `ctx.env.SOME_KEY` (the validated `defineEnv`
371
+ * surface) see this object. Left unset it stays `undefined` — matching the
372
+ * optional `ctx.env?` field, so graceful `ctx.env?.KEY` access still yields
373
+ * `undefined` rather than throwing. Not a throwing stub for exactly that
374
+ * reason: `env` is designed to be legitimately absent.
375
+ * @example
376
+ * ```ts
377
+ * const t = lunoraTest(schema, { env: { STRIPE_KEY: "sk_test_…" } });
378
+ * ```
379
+ */
380
+ env?: Record<string, unknown>;
381
+ /**
382
+ * Injectable `fetch` implementation for action contexts. When provided,
383
+ * `ctx.fetch` in every `action` (and `withIdentity` views) resolves to this
384
+ * function rather than throwing the "not available in v1" stub.
385
+ *
386
+ * Pass `vi.fn()` or any `typeof globalThis.fetch` compatible implementation.
387
+ * @example
388
+ * ```ts
389
+ * const fakeFetch = vi.fn().mockResolvedValue(Response.json({ ok: true }));
390
+ * const t = lunoraTest(schema, { fetch: fakeFetch });
391
+ * ```
392
+ */
156
393
  fetch?: typeof globalThis.fetch;
157
394
  /**
158
- * Function registry for the fake in-memory scheduler. Maps a
159
- * `functionPath` string (the value passed as the second argument to
160
- * `ctx.scheduler.runAfter` / `ctx.scheduler.runAt`) to the corresponding
161
- * registered function object.
162
- *
163
- * Only required if your handlers schedule work. Scheduled jobs for paths
164
- * NOT listed here produce a `console.warn` at dispatch time (matching prod
165
- * behaviour for unknown paths).
166
- * @example
167
- * ```ts
168
- * const t = lunoraTest(schema, {
169
- * functions: { "messages:send": sendMutation },
170
- * });
171
- * ```
172
- */
395
+ * Function registry for the fake in-memory scheduler. Maps a
396
+ * `functionPath` string (the value passed as the second argument to
397
+ * `ctx.scheduler.runAfter` / `ctx.scheduler.runAt`) to the corresponding
398
+ * registered function object.
399
+ *
400
+ * Only required if your handlers schedule work. Scheduled jobs for paths
401
+ * NOT listed here produce a `console.warn` at dispatch time (matching prod
402
+ * behaviour for unknown paths).
403
+ * @example
404
+ * ```ts
405
+ * const t = lunoraTest(schema, {
406
+ * functions: { "messages:send": sendMutation },
407
+ * });
408
+ * ```
409
+ */
173
410
  functions?: FunctionRegistry;
174
411
  /**
175
- * Fixed value for `ctx.now` (epoch ms) in every context. Production captures
176
- * `Date.now()` once per execution; in tests a fixed `now` makes time-dependent
177
- * handlers deterministic. Defaults to the wall clock at harness creation.
178
- * @example
179
- * ```ts
180
- * const t = lunoraTest(schema, { now: 1_700_000_000_000 });
181
- * ```
182
- */
412
+ * Fixed value for `ctx.now` (epoch ms) in every context. Production captures
413
+ * `Date.now()` once per execution; in tests a fixed `now` makes time-dependent
414
+ * handlers deterministic. Defaults to the wall clock at harness creation.
415
+ * @example
416
+ * ```ts
417
+ * const t = lunoraTest(schema, { now: 1_700_000_000_000 });
418
+ * ```
419
+ */
183
420
  now?: number;
184
421
  }
185
422
  /**
186
- * The in-memory test harness returned by {@link lunoraTest}. Mirrors the first
187
- * five methods of Convex's `convexTest`: `query` / `mutation` / `action` / `run`
188
- * / `withIdentity`. All five share one in-memory `node:sqlite` backend, so a
189
- * write from one method is visible to a read from another (including across a
190
- * `withIdentity` scope).
191
- */
423
+ * The in-memory test harness returned by {@link lunoraTest}. Mirrors the first
424
+ * five methods of Convex's `convexTest`: `query` / `mutation` / `action` / `run`
425
+ * / `withIdentity`. All five share one in-memory `node:sqlite` backend, so a
426
+ * write from one method is visible to a read from another (including across a
427
+ * `withIdentity` scope).
428
+ */
192
429
  interface TestHarness {
193
430
  /** Run a registered `action` (or an inline `async (context) => …`) against the harness. */
194
431
  action: {
@@ -207,69 +444,189 @@ interface TestHarness {
207
444
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): Promise<R>;
208
445
  <R>(inline: InlineQueryFunction<R>): Promise<R>;
209
446
  };
210
- /** Direct db access at mutation-level (read + write), mirroring `convexTest`'s `run`. */
447
+ /**
448
+ * Direct db access at mutation-level (read + write), mirroring `convexTest`'s
449
+ * `run`. This is the harness's trusted escape hatch: `ctx.db` here is always
450
+ * the UNGUARDED writer, regardless of `options.enforceRls` or the schema's
451
+ * RLS mode — seeding/asserting against a protected table never trips the
452
+ * secure-by-default guard. A `ctx.runMutation`/`ctx.runQuery` call from
453
+ * inside the body still dispatches the target as a real registered
454
+ * procedure, so it is guarded exactly as `t.mutation`/`t.query` would guard
455
+ * it.
456
+ */
211
457
  run: <R>(function_: InlineMutationFunction<R>) => Promise<R>;
212
458
  /**
213
- * Controls for the fake in-memory scheduler. Always present; scheduler
214
- * jobs only execute when you call `advance(ms)` or `runPending()`.
215
- *
216
- * - `list()` — snapshot of all pending jobs (enqueue order).
217
- * - `advance(ms)` — tick the virtual clock forward by `ms` ms, executing every job
218
- * whose `scheduledFor` is now at or below virtual now.
219
- * - `runPending()` — execute all currently pending jobs regardless of their scheduled time.
220
- *
221
- * Scheduled jobs run through the same `runInternal` dispatch as
222
- * `ctx.runMutation`, so they share the harness SQLite database.
223
- */
459
+ * Controls for the fake in-memory scheduler. Always present; scheduler
460
+ * jobs only execute when you call `advance(ms)` or `runPending()`.
461
+ *
462
+ * - `list()` — snapshot of all pending jobs (enqueue order).
463
+ * - `advance(ms)` — tick the virtual clock forward by `ms` ms, executing every job
464
+ * whose `scheduledFor` is now at or below virtual now.
465
+ * - `runPending()` — execute all currently pending jobs regardless of their scheduled time.
466
+ *
467
+ * Scheduled jobs run through the same `runInternal` dispatch as
468
+ * `ctx.runMutation`, so they share the harness SQLite database.
469
+ */
224
470
  scheduler: FakeSchedulerControls;
225
471
  /**
226
- * Subscribe to a registered query (or inline query function) and receive
227
- * an async iterable of snapshots. The first value is emitted immediately
228
- * (the current query result). Subsequent values are emitted after each
229
- * `mutation` / `run` call on this harness completes.
230
- *
231
- * Subscriptions are table-agnostic — any mutation triggers a re-evaluation.
232
- * This matches the harness's single-writer model and keeps the implementation
233
- * free of DO machinery.
234
- * @example
235
- * ```ts
236
- * const sub = t.subscribe(list, {});
237
- * const first = await sub.next(); // current result
238
- * await t.mutation(send, { author: "ada", body: "hi" });
239
- * const second = await sub.next(); // updated result
240
- * await sub.return(); // unsubscribe
241
- * ```
242
- *
243
- * The iterable is lazy — it never buffers more than one pending result.
244
- * If you do not consume fast enough and multiple mutations fire, the next
245
- * `next()` call will reflect the most-recent state (intermediate snapshots
246
- * are coalesced).
247
- */
472
+ * Subscribe to a registered query (or inline query function) and receive
473
+ * an async iterable of snapshots. The first value is emitted immediately
474
+ * (the current query result). Subsequent values are emitted after each
475
+ * `mutation` / `run` call on this harness completes.
476
+ *
477
+ * Subscriptions are table-agnostic — any mutation triggers a re-evaluation.
478
+ * This matches the harness's single-writer model and keeps the implementation
479
+ * free of DO machinery.
480
+ * @example
481
+ * ```ts
482
+ * const sub = t.subscribe(list, {});
483
+ * const first = await sub.next(); // current result
484
+ * await t.mutation(send, { author: "ada", body: "hi" });
485
+ * const second = await sub.next(); // updated result
486
+ * await sub.return(); // unsubscribe
487
+ * ```
488
+ *
489
+ * The iterable is lazy — it never buffers more than one pending result.
490
+ * If you do not consume fast enough and multiple mutations fire, the next
491
+ * `next()` call will reflect the most-recent state (intermediate snapshots
492
+ * are coalesced).
493
+ */
248
494
  subscribe: {
249
495
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): TestSubscription<R>;
250
496
  <R>(inline: InlineQueryFunction<R>): TestSubscription<R>;
251
497
  };
498
+ /**
499
+ * What handlers attached to `ctx.span` — the **wide event** — during this
500
+ * harness's runs, so a test can assert the instrumentation itself:
501
+ *
502
+ * ```ts
503
+ * await t.mutation(checkout, { items: 3 });
504
+ * expect(t.wideEvent().attributes["cart.items"]).toBe(3);
505
+ * ```
506
+ *
507
+ * Accumulates across calls on this view (it is not reset per run), mirroring
508
+ * the harness's single shared database. Shared with any `withIdentity` view.
509
+ */
510
+ wideEvent: () => RecordedWideEvent;
252
511
  /** Return a harness view that shares this harness's db but reports the given identity on `ctx.auth`. */
253
512
  withIdentity: (identity: TestIdentity) => TestHarness;
254
513
  }
514
+ /** What a handler attached to the dispatch's span (`ctx.span`) during a harness run. */
515
+ interface RecordedWideEvent {
516
+ /**
517
+ * Attributes accumulated across the run, merged in call order. Values are
518
+ * recorded AS PASSED (not coerced the way the real pipeline normalizes them),
519
+ * so a test asserts on what the handler meant rather than on the wire form.
520
+ */
521
+ attributes: LogFields;
522
+ /** Span events recorded via `ctx.span.addEvent` / `recordException`, in order. */
523
+ events: {
524
+ attributes?: LogFields;
525
+ name: string;
526
+ }[];
527
+ /** Links recorded via `ctx.span.addLink`, in order. */
528
+ links: {
529
+ spanId: string;
530
+ traceId: string;
531
+ }[];
532
+ }
255
533
  /**
256
- * Spin up an in-memory Lunora function harness for `schema`.
257
- *
258
- * `lunoraTest(schema)` runs the migrations against a fresh `node:sqlite`
259
- * database, builds the same `ctx.db` writer the real Durable Object builds (via
260
- * `@lunora/do`'s `createShardCtxDb`), and returns a harness whose `query` /
261
- * `mutation` / `action` / `run` execute a registered function's `handler`
262
- * directly no Durable Object, no `wrangler`, no network.
263
- *
264
- * **v1 surfaces now supported:**
265
- *
266
- * - `ctx.fetch` (actions): inject a custom `fetch` via `options.fetch`.
267
- * - `ctx.scheduler` (mutations + actions): fully functional fake with virtual clock;
268
- * control via `harness.scheduler.advance(ms)` / `runPending()` / `list()`.
269
- * - `harness.subscribe(query, args)`: async iterable that re-emits after mutations.
270
- *
271
- * **v1 stubs (still throwing):** `ctx.storage`, `ctx.vectors`, `ctx.workflows`.
272
- * These are clearly documented follow-ups.
273
- */
534
+ * Spin up an in-memory Lunora function harness for `schema`.
535
+ *
536
+ * `lunoraTest(schema)` runs the migrations against a fresh `node:sqlite`
537
+ * database, builds the same `ctx.db` writer the real Durable Object builds (via
538
+ * `@lunora/shard-engine`'s `createShardCtxDb`, with the same `enforceRls: true`
539
+ * production's generated `buildCtx` passes), and returns a harness whose
540
+ * `query` / `mutation` / `action` execute a registered function's `handler`
541
+ * directly — no Durable Object, no `wrangler`, no network. Under a
542
+ * `.rls("required")` schema a procedure missing `.use(rls(...))` therefore
543
+ * rejects here exactly as it would on its first production dispatch — see
544
+ * `LunoraTestOptions.enforceRls` to opt out, and `run`'s doc for the trusted
545
+ * escape hatch (always unguarded).
546
+ *
547
+ * **v1 surfaces now supported:**
548
+ *
549
+ * - `ctx.env` (all contexts): inject the validated env via `options.env`; unset it
550
+ * stays `undefined`, matching the optional `ctx.env?` field.
551
+ * - `ctx.fetch` (actions): inject a custom `fetch` via `options.fetch`.
552
+ * - `ctx.scheduler` (mutations + actions): fully functional fake with virtual clock;
553
+ * control via `harness.scheduler.advance(ms)` / `runPending()` / `list()`.
554
+ * - `harness.subscribe(query, args)`: async iterable that re-emits after mutations.
555
+ *
556
+ * **v1 stubs (still throwing):** `ctx.storage`, `ctx.vectors`, `ctx.workflows`.
557
+ * These are clearly documented follow-ups.
558
+ */
274
559
  declare const lunoraTest: (schema: TestSchema, options?: LunoraTestOptions) => TestHarness;
275
- export { type FakeScheduledJob, type FakeSchedulerControls, type FunctionRegistry, type LunoraTestOptions, type ScheduledJobFailure, type SweepOptions, type TestHarness, type TestIdentity, type TestSubscription, lunoraTest };
560
+ /** One sample handed to a {@link Scorer}. */
561
+ interface ScorerSample {
562
+ /** The reference/gold answer, when the scorer compares against one. */
563
+ expected?: string;
564
+ /** The prompt/input that produced the output (for LLM-judge context). */
565
+ input?: string;
566
+ /** Arbitrary per-sample metadata carried through. */
567
+ metadata?: Record<string, unknown>;
568
+ /** The model/agent output under test. */
569
+ output: string;
570
+ }
571
+ /** A scorer's verdict: a `[0, 1]` score and an optional human-readable reason. */
572
+ interface ScoreResult {
573
+ reason?: string;
574
+ score: number;
575
+ }
576
+ /** A named scorer — returns a `[0, 1]` score (or a {@link ScoreResult}) for a sample. */
577
+ interface Scorer {
578
+ name: string;
579
+ score: (sample: ScorerSample) => Promise<ScoreResult | number> | ScoreResult | number;
580
+ }
581
+ /** One dataset case: an input and its optional gold answer/metadata. */
582
+ interface EvalCase {
583
+ expected?: string;
584
+ input: string;
585
+ metadata?: Record<string, unknown>;
586
+ }
587
+ /** The per-case eval result: the produced output plus each scorer's verdict and the mean. */
588
+ interface EvalItemResult {
589
+ average: number;
590
+ input: string;
591
+ output: string;
592
+ scores: Record<string, ScoreResult>;
593
+ }
594
+ /** The whole eval run: per-case results plus the mean of their averages. */
595
+ interface EvalResult {
596
+ average: number;
597
+ items: EvalItemResult[];
598
+ }
599
+ /** Score 1 if the output contains `needle` (case-insensitive unless `caseSensitive`). */
600
+ declare const containsScorer: (needle: string, options?: {
601
+ caseSensitive?: boolean;
602
+ }) => Scorer;
603
+ /** Score 1 when `pattern` matches the output. */
604
+ declare const regexScorer: (pattern: RegExp, name?: string) => Scorer;
605
+ /** Score 1 when the trimmed output exactly equals the trimmed `expected`. */
606
+ declare const exactMatchScorer: () => Scorer;
607
+ /** Score the fraction of `keywords` (case-insensitive) present in the output. */
608
+ declare const keywordScorer: (keywords: ReadonlyArray<string>) => Scorer;
609
+ /**
610
+ * An LLM-as-judge scorer. `judge` is INJECTED — a `(prompt) => Promise<string>`
611
+ * you wire to your model (e.g. via `ctx.ai` / `generateText`), so this module
612
+ * stays model-agnostic and the judge is mockable in tests. It returns the model's
613
+ * numeric verdict (`[0, 1]`) plus its reason.
614
+ */
615
+ declare const llmScorer: (options: {
616
+ criteria: string;
617
+ judge: (prompt: string) => Promise<string>;
618
+ name?: string;
619
+ }) => Scorer;
620
+ /** Run every scorer over one sample (concurrently) → each verdict keyed by name + their mean. */
621
+ declare const scoreSample: (sample: ScorerSample, scorers: ReadonlyArray<Scorer>) => Promise<{
622
+ average: number;
623
+ scores: Record<string, ScoreResult>;
624
+ }>;
625
+ /**
626
+ * Run a dataset through `produce` (e.g. an `agentHarness.run` wrapper returning
627
+ * the output text) and score each output with `scorers`. Cases run concurrently;
628
+ * give each its own thread/key inside `produce` if the producer is stateful.
629
+ * Returns per-case results plus the mean of their averages.
630
+ */
631
+ declare const evaluate: (cases: ReadonlyArray<EvalCase>, produce: (input: string) => Promise<string> | string, scorers: ReadonlyArray<Scorer>) => Promise<EvalResult>;
632
+ export { type AgentHarness, type AgentHarnessOptions, type AgentRunOverrides, type EvalCase, type EvalItemResult, type EvalResult, type EvaluationAttributeValue, type EvaluationMetrics, type EvaluationSpanHandle, type FakeScheduledJob, type FakeSchedulerControls, type FunctionRegistry, type HarnessDispatch, type HarnessMessage, type HarnessThread, type LunoraTestOptions, type RecordEvaluationInput, type ScheduledJobFailure, type ScoreResult, type Scorer, type ScorerSample, type SweepOptions, type TestHarness, type TestIdentity, type TestSubscription, agentHarness, containsScorer, evaluate, evaluationAttributes, exactMatchScorer, finalTurn, keywordScorer, llmScorer, lunoraTest, recordEvaluation, regexScorer, scoreSample, toolCallTurn };