@lunora/testing 1.0.0-alpha.22 → 1.0.0-alpha.220

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,248 @@
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, LogFields, RegisteredAction, RegisteredMutation, RegisteredQuery, ArgsValidator, InferArgs, ActionCtx, MutationCtx, QueryCtx, 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 export keys 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
+ /**
144
+ * Shared, bundler-inlined builder for the OpenTelemetry `gen_ai.evaluation.*`
145
+ * attributes an AI **evaluation** verdict (a scorer's `{name, score, label?}`)
146
+ * contributes to a **generation span**.
147
+ *
148
+ * This is the emit-time counterpart of the cloud OTLP decoder, which reads
149
+ * `gen_ai.evaluation.<name>.score` (number) and optional
150
+ * `gen_ai.evaluation.<name>.label` (string) attribute pairs back off a generation
151
+ * span (`EVALUATION_PREFIX = "gen_ai.evaluation."`). The framework emits exactly
152
+ * that pair here so a score rides the same trace as the generation it grades.
153
+ *
154
+ * It lives in `shared/` because more than one layer needs the identical wire
155
+ * format with no runtime dependency edge between them: `@lunora/do` builds it into
156
+ * a live `ctx.trace` span's post-hoc attributes (`SpanHandle.recordEvaluation`),
157
+ * and `@lunora/server` mirrors the handle shape structurally. `@lunora/testing`
158
+ * ships a parallel test-time helper (`recordEvaluation` / `evaluationAttributes`)
159
+ * that targets the same `gen_ai.evaluation.*` contract for span-less eval
160
+ * events/metrics. Keep this file genuinely zero-dependency so inlining stays sound.
161
+ */
162
+ /** The primitive an eval contributes to a span: a numeric score or a string label. */
163
+ type EvaluationAttributeValue = number | string;
164
+ /**
165
+ * Structural slice of the post-hoc span handle `ctx.trace` hands its body (see the
166
+ * server `SpanHandle`) — enough to attach an eval's attributes. Declared here
167
+ * rather than imported so `@lunora/testing` takes no dependency on `@lunora/server`
168
+ * or `@lunora/do`; the real handle is assignable to it.
169
+ */
170
+ interface EvaluationSpanHandle {
171
+ setAttributes: (fields: Record<string, EvaluationAttributeValue>) => void;
172
+ }
173
+ /**
174
+ * Structural slice of `ctx.metrics` — enough to record a score as a durable
175
+ * series. Declared here for the same reason as {@link EvaluationSpanHandle}: no
176
+ * dependency on `@lunora/server`, and the real handle is assignable.
177
+ */
178
+ interface EvaluationMetrics {
179
+ gauge: (name: string, value: number, attributes?: Record<string, unknown>) => void;
180
+ }
181
+ /** One eval verdict to emit. */
182
+ interface RecordEvaluationInput {
183
+ /**
184
+ * Optional categorical label (e.g. `"pass"` / `"fail"` / a rubric bucket),
185
+ * emitted as the `.label` attribute. Omitted → no label attribute.
186
+ */
187
+ label?: string;
188
+ /**
189
+ * Optional `ctx.metrics` handle. Passing it ALSO records the score as a
190
+ * `gen_ai.evaluation.<name>.score` gauge, which is what gives an eval a
191
+ * durable history: span attributes live in the shard's bounded in-memory
192
+ * ring and vanish on hibernation, while metrics are persisted in per-minute
193
+ * buckets and can be charted as a trend. Additive — the attributes are
194
+ * emitted either way.
195
+ */
196
+ metrics?: EvaluationMetrics;
197
+ /**
198
+ * The scorer/evaluation name — becomes the key's name segment. Any character
199
+ * outside `[A-Za-z0-9._-]` is replaced with `_` so a scorer name carrying a
200
+ * colon (e.g. `"contains:shipped"`) still yields a well-formed attribute key.
201
+ */
202
+ name: string;
203
+ /** The numeric score (typically `[0, 1]`), emitted as the `.score` attribute. */
204
+ score: number;
205
+ /**
206
+ * Optional generation span to attach the attributes to — the post-hoc
207
+ * `SpanHandle` a `ctx.trace` body receives. Omitted → nothing is attached and
208
+ * the caller uses the returned bag for a standalone event/metric.
209
+ */
210
+ span?: EvaluationSpanHandle;
211
+ }
212
+ /**
213
+ * Build the `gen_ai.evaluation.NAME.*` attribute bag for one eval verdict — the
214
+ * `.score` (number) always, the `.label` (string) when a label is given. Exported
215
+ * so a caller can emit the score as a standalone event/metric without a span.
216
+ *
217
+ * Delegates to the shared `shared/evaluation-attributes.ts` builder so
218
+ * `@lunora/testing`'s scorers and the runtime's own `recordEvaluation` emit the
219
+ * identical wire format — only the thrown error type differs, wrapped here as a
220
+ * `LunoraError` to match this package's public error contract.
221
+ */
222
+ declare const evaluationAttributes: (input: Pick<RecordEvaluationInput, "label" | "name" | "score">) => Record<string, EvaluationAttributeValue>;
223
+ /**
224
+ * Emit one eval verdict as `gen_ai.evaluation.NAME.*` attributes. Attaches them to
225
+ * `input.span` when supplied (the post-hoc generation-span handle), and always
226
+ * returns the attribute bag so a span-less caller can ship it as an eval
227
+ * event/metric. Privacy-safe: only the name, score, and optional label are
228
+ * emitted — never the graded prompt or output.
229
+ */
230
+ declare const recordEvaluation: (input: RecordEvaluationInput) => Record<string, EvaluationAttributeValue>;
3
231
  /** A pending job entry in the fake scheduler queue. */
4
232
  interface FakeScheduledJob extends ScheduledJob {
5
233
  /** The args the job was scheduled with. */
6
234
  args: Record<string, unknown>;
7
235
  }
8
236
  /**
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
- */
237
+ * A single scheduled-job failure that exhausted its retry budget, captured
238
+ * during an `advance()` / `runPending()` sweep. Mirrors `SchedulerDO`'s
239
+ * dead-letter park (`recordRetry()`, `packages/scheduler/src/scheduler-do.ts:875-909`):
240
+ * a job that fails while it still has retries left is silently re-enqueued
241
+ * with backoff and is NOT recorded here. Only once a job's `attempts` exceeds
242
+ * `@lunora/scheduler`'s `MAX_RETRY_ATTEMPTS` does it land here — being a test
243
+ * harness, the fake scheduler never swallows a terminal failure, so tests can
244
+ * still assert on it.
245
+ */
15
246
  interface ScheduledJobFailure {
16
247
  /** The args the job was dispatched with. */
17
248
  args: Record<string, unknown>;
@@ -23,94 +254,119 @@ interface ScheduledJobFailure {
23
254
  id: string;
24
255
  }
25
256
  /**
26
- * Controls exposed on the test harness for the fake in-memory scheduler.
27
- * Access via `harness.scheduler`.
28
- */
257
+ * Controls exposed on the test harness for the fake in-memory scheduler.
258
+ * Access via `harness.scheduler`.
259
+ */
29
260
  interface FakeSchedulerControls {
30
261
  /**
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
- */
262
+ * Advance the virtual clock by `ms` milliseconds, executing all jobs whose
263
+ * `scheduledFor` timestamp is now at or before the new virtual "now". Jobs
264
+ * are dispatched in `scheduledFor` order (oldest first). Newly queued jobs
265
+ * (scheduled by an executed job, or re-enqueued as a retry, during the
266
+ * advance) are NOT re-evaluated in the same advance call — callers should
267
+ * advance again if needed.
268
+ *
269
+ * Per-job failures are isolated (matching production): a job that throws does
270
+ * NOT prevent the remaining due jobs from running. A failure with retries
271
+ * left is silently re-enqueued with exponential backoff on the virtual clock
272
+ * — mirroring `SchedulerDO`'s default retry policy (`MAX_RETRY_ATTEMPTS`
273
+ * retries, `RETRY_BASE_DELAY_MS` base delay, doubling; both imported from
274
+ * `@lunora/scheduler`) — rather than surfaced. Advancing far enough to
275
+ * observe a terminal failure therefore costs the WHOLE backoff schedule
276
+ * (30s + 60s + 120s + 240s + 480s = 930s of virtual clock at today's
277
+ * defaults), not a single tick.
278
+ * Only once a job's retry budget is exhausted is the failure surfaced: it is
279
+ * recorded on {@link FakeSchedulerControls.failures} and, by default,
280
+ * re-thrown so a test still sees the error. A single such failure is
281
+ * re-thrown verbatim; multiple are aggregated into an `AggregateError`. Pass
282
+ * `{ throwOnError: false }` to suppress the re-throw and inspect
283
+ * {@link FakeSchedulerControls.failures} (and the returned count) instead.
284
+ *
285
+ * Returns the number of jobs dispatched this sweep, including ones that
286
+ * failed and were silently retried, and ones that failed terminally.
287
+ */
48
288
  advance: (ms: number, options?: SweepOptions) => Promise<number>;
49
289
  /**
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
- */
290
+ * All scheduled-job failures that exhausted their retry budget, in
291
+ * execution order, across every `advance()` / `runPending()` call on this
292
+ * harness. A failure with retries remaining is NOT recorded here — see
293
+ * {@link ScheduledJobFailure}. Always available, even when
294
+ * `throwOnError: false` suppressed the re-throw. The list is a snapshot —
295
+ * mutating it does not affect the scheduler.
296
+ */
55
297
  failures: () => ScheduledJobFailure[];
56
298
  /**
57
- * List all pending jobs (those not yet executed or cancelled) in the order
58
- * they were enqueued.
59
- */
299
+ * List all pending jobs (those not yet executed or cancelled) in the order
300
+ * they were enqueued. A job currently waiting out its retry backoff is
301
+ * still pending (visible here with its `attempts` count incremented and
302
+ * `scheduledFor` pushed out) until its budget is exhausted.
303
+ */
60
304
  list: () => FakeScheduledJob[];
61
305
  /**
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
- */
306
+ * Execute all currently pending jobs regardless of their `scheduledFor`
307
+ * time. Equivalent to advancing to `Infinity`. Returns the number of jobs
308
+ * dispatched this sweep (including failed ones, retried or terminal).
309
+ *
310
+ * Failure isolation, retry, and surfacing match
311
+ * {@link FakeSchedulerControls.advance}: one failing job does not abort the
312
+ * rest, a failure under the retry budget is silently re-enqueued rather
313
+ * than surfaced, and only a terminal failure is recorded on
314
+ * {@link FakeSchedulerControls.failures} and re-thrown unless
315
+ * `{ throwOnError: false }` is passed.
316
+ */
71
317
  runPending: (options?: SweepOptions) => Promise<number>;
72
318
  }
73
319
  /** Options controlling how an `advance()` / `runPending()` sweep surfaces failures. */
74
320
  interface SweepOptions {
75
321
  /**
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
- */
322
+ * When `true` (the default), failures encountered during the sweep are
323
+ * re-thrown after every due job has run — a single failure verbatim, multiple
324
+ * as an `AggregateError`. When `false`, the sweep resolves normally and
325
+ * failures are observable only via {@link FakeSchedulerControls.failures}.
326
+ */
81
327
  throwOnError?: boolean;
82
328
  }
329
+ /** What a handler attached to the dispatch's span (`ctx.span`) during a harness run. */
330
+ interface RecordedWideEvent {
331
+ /**
332
+ * Attributes accumulated across the run, merged in call order. Values are
333
+ * recorded AS PASSED (not coerced the way the real pipeline normalizes them),
334
+ * so a test asserts on what the handler meant rather than on the wire form.
335
+ */
336
+ attributes: LogFields;
337
+ /** Span events recorded via `ctx.span.addEvent` / `recordException`, in order. */
338
+ events: {
339
+ attributes?: LogFields;
340
+ name: string;
341
+ }[];
342
+ /** Links recorded via `ctx.span.addLink`, in order. */
343
+ links: {
344
+ spanId: string;
345
+ traceId: string;
346
+ }[];
347
+ }
83
348
  /**
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
- */
349
+ * The schema value produced by `@lunora/server`'s `defineSchema`. Accepted
350
+ * structurally; internally it is handed to `@lunora/do`'s `runShardMigrations` /
351
+ * `createShardCtxDb`, whose `SchemaLike` is the same shape declared in the DO
352
+ * package — the two are structurally compatible at runtime (only their
353
+ * independently-declared trigger nesting drifts at the type level), so the
354
+ * boundary cast below is sound.
355
+ */
100
356
  type TestSchema = Schema<Record<string, TableDefinition>>;
101
357
  /**
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
- */
358
+ * A user-supplied identity, surfaced to handlers via `ctx.auth`. `userId` is the
359
+ * subject the handler reads from `ctx.auth.userId`; any additional fields are
360
+ * returned verbatim from `ctx.auth.getIdentity()` (mirroring a decoded JWT).
361
+ */
106
362
  interface TestIdentity extends Record<string, unknown> {
107
363
  userId?: null | string;
108
364
  }
109
365
  /**
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
- */
366
+ * An async iterable/iterator returned by {@link TestHarness.subscribe}.
367
+ * Guarantees `return()` is always defined (unlike the optional `AsyncIterator.return`),
368
+ * so callers can always unsubscribe without a `?.` guard.
369
+ */
114
370
  interface TestSubscription<R> extends AsyncIterable<R> {
115
371
  next: () => Promise<IteratorResult<R, R>>;
116
372
  return: () => Promise<IteratorResult<R, R>>;
@@ -120,75 +376,130 @@ type InlineQueryFunction<R> = (context: QueryCtx) => Promise<R> | R;
120
376
  type InlineMutationFunction<R> = (context: MutationCtx) => Promise<R> | R;
121
377
  type InlineActionFunction<R> = (context: ActionCtx) => Promise<R> | R;
122
378
  /**
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
- */
379
+ * A map from function path strings (e.g. `"messages:send"`) to their
380
+ * registered function objects. Used by the fake scheduler to resolve
381
+ * `ctx.scheduler.runAfter(delay, "messages:send", args)` → handler invocation.
382
+ *
383
+ * Only mutations and actions can be scheduled in production; queries passed
384
+ * here will be accepted but produce a console.warn at dispatch time.
385
+ *
386
+ * The value type uses `any` because `RegisteredFunction` is contravariant in its
387
+ * args type parameter — a `RegisteredMutation` with concrete args is not assignable
388
+ * to `RegisteredMutation` with `ArgsValidator` at the type level even though at
389
+ * runtime it is sound (the fake scheduler passes `Record<string, unknown>` to
390
+ * `handler` and ignores the return value).
391
+ */
136
392
  type FunctionRegistry = Record<string, RegisteredAction<any, any> | RegisteredMutation<any, any> | RegisteredQuery<any, any>>;
137
393
  /**
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
- */
394
+ * Options accepted by {@link lunoraTest}.
395
+ *
396
+ * All options are optional — `lunoraTest(schema)` preserves v1 behaviour with
397
+ * clearly-throwing stubs for unsupported surfaces.
398
+ */
143
399
  interface LunoraTestOptions {
144
400
  /**
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
- */
401
+ * Enforce the secure-by-default RLS guard on the writer registered
402
+ * procedures dispatch through (`query`/`mutation`/`action`, via
403
+ * `reference.handler`) — the same `enforceRls: true` production's generated
404
+ * `buildCtx` always passes. Under a `.rls("required")` schema, a procedure
405
+ * that touches a known, non-`.public()` table without `.use(rls(...))` in
406
+ * its chain rejects with `RlsRequiredError`, exactly as it would on first
407
+ * dispatch in production. Defaults to `true` so a green suite means the
408
+ * deploy is RLS-safe; the harness's other surfaces — `t.run` and any
409
+ * `@lunora/seed` helper built on it — stay on the trusted, UNGUARDED writer
410
+ * regardless of this flag (mirroring production's admin/migration system
411
+ * paths).
412
+ *
413
+ * Set to `false` to opt back into the pre-guard permissive behaviour (every
414
+ * `lunoraTest` release before this option existed): every procedure's
415
+ * `ctx.db` goes unguarded even under a `.rls("required")` schema. This
416
+ * forfeits the "a passing suite means the deploy is safe" guarantee — a
417
+ * procedure that forgot `.use(rls(...))` will pass in tests and throw
418
+ * `RlsRequiredError` on its first production request. No effect when the
419
+ * schema does not declare `.rls("required")` (the guard is a no-op there
420
+ * either way).
421
+ * @default true
422
+ * @example
423
+ * ```ts
424
+ * // Restores the old permissive behavior for a suite not yet migrated.
425
+ * const t = lunoraTest(schema, { enforceRls: false });
426
+ * ```
427
+ */
428
+ enforceRls?: boolean;
429
+ /**
430
+ * Injectable `ctx.env` for every context (query / mutation / action). When
431
+ * provided, handlers that read `ctx.env.SOME_KEY` (the validated `defineEnv`
432
+ * surface) see this object. Left unset it stays `undefined` — matching the
433
+ * optional `ctx.env?` field, so graceful `ctx.env?.KEY` access still yields
434
+ * `undefined` rather than throwing. Not a throwing stub for exactly that
435
+ * reason: `env` is designed to be legitimately absent.
436
+ * @example
437
+ * ```ts
438
+ * const t = lunoraTest(schema, { env: { STRIPE_KEY: "sk_test_…" } });
439
+ * ```
440
+ */
441
+ env?: Record<string, unknown>;
442
+ /**
443
+ * Injectable `fetch` implementation for action contexts. When provided,
444
+ * `ctx.fetch` in every `action` (and `withIdentity` views) resolves to this
445
+ * function rather than throwing the "not available in v1" stub.
446
+ *
447
+ * Pass `vi.fn()` or any `typeof globalThis.fetch` compatible implementation.
448
+ * @example
449
+ * ```ts
450
+ * const fakeFetch = vi.fn(async () => Response.json({ ok: true }));
451
+ * const t = lunoraTest(schema, { fetch: fakeFetch });
452
+ * ```
453
+ */
156
454
  fetch?: typeof globalThis.fetch;
157
455
  /**
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
- */
456
+ * Function registry for the fake in-memory scheduler. Maps a
457
+ * `functionPath` string (the value passed as the second argument to
458
+ * `ctx.scheduler.runAfter` / `ctx.scheduler.runAt`) to the corresponding
459
+ * registered function object.
460
+ *
461
+ * Only required if your handlers schedule work. Scheduled jobs for paths
462
+ * NOT listed here produce a `console.warn` at dispatch time (matching prod
463
+ * behaviour for unknown paths).
464
+ * @example
465
+ * ```ts
466
+ * const t = lunoraTest(schema, {
467
+ * functions: { "messages:send": sendMutation },
468
+ * });
469
+ * ```
470
+ */
173
471
  functions?: FunctionRegistry;
174
472
  /**
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
- */
473
+ * Fixed value for `ctx.now` (epoch ms) in every context. Production captures
474
+ * `Date.now()` once per execution; in tests a fixed `now` makes time-dependent
475
+ * handlers deterministic. Defaults to the wall clock at harness creation.
476
+ * @example
477
+ * ```ts
478
+ * const t = lunoraTest(schema, { now: 1_700_000_000_000 });
479
+ * ```
480
+ */
183
481
  now?: number;
482
+ /**
483
+ * Fakes for `ctx.services` (the `lunora.config` `services` an app calls),
484
+ * keyed like `ctx.services`. Set on action contexts only — queries and
485
+ * mutations have no `ctx.services` at runtime either. A key with no fake
486
+ * throws on use, naming the option to add it to.
487
+ * @example
488
+ * ```ts
489
+ * const t = lunoraTest(schema, {
490
+ * services: { documentParser: { fetch: vi.fn(async () => Response.json({ text: "…" })) } },
491
+ * });
492
+ * ```
493
+ */
494
+ services?: Record<string, object>;
184
495
  }
185
496
  /**
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
- */
497
+ * The in-memory test harness returned by {@link lunoraTest}. Mirrors the first
498
+ * five methods of Convex's `convexTest`: `query` / `mutation` / `action` / `run`
499
+ * / `withIdentity`. All five share one in-memory `node:sqlite` backend, so a
500
+ * write from one method is visible to a read from another (including across a
501
+ * `withIdentity` scope).
502
+ */
192
503
  interface TestHarness {
193
504
  /** Run a registered `action` (or an inline `async (context) => …`) against the harness. */
194
505
  action: {
@@ -207,69 +518,251 @@ interface TestHarness {
207
518
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): Promise<R>;
208
519
  <R>(inline: InlineQueryFunction<R>): Promise<R>;
209
520
  };
210
- /** Direct db access at mutation-level (read + write), mirroring `convexTest`'s `run`. */
521
+ /**
522
+ * Direct db access at mutation-level (read + write), mirroring `convexTest`'s
523
+ * `run`. This is the harness's trusted escape hatch: `ctx.db` here is always
524
+ * the UNGUARDED writer, regardless of `options.enforceRls` or the schema's
525
+ * RLS mode — seeding/asserting against a protected table never trips the
526
+ * secure-by-default guard. A `ctx.runMutation`/`ctx.runQuery` call from
527
+ * inside the body still dispatches the target as a real registered
528
+ * procedure, so it is guarded exactly as `t.mutation`/`t.query` would guard
529
+ * it.
530
+ */
211
531
  run: <R>(function_: InlineMutationFunction<R>) => Promise<R>;
212
532
  /**
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
- */
533
+ * Controls for the fake in-memory scheduler. Always present; scheduler
534
+ * jobs only execute when you call `advance(ms)` or `runPending()`.
535
+ *
536
+ * - `list()` — snapshot of all pending jobs (enqueue order).
537
+ * - `advance(ms)` — tick the virtual clock forward by `ms` ms, executing every job
538
+ * whose `scheduledFor` is now at or below virtual now.
539
+ * - `runPending()` — execute all currently pending jobs regardless of their scheduled time.
540
+ *
541
+ * Scheduled jobs run through the same `runInternal` dispatch as
542
+ * `ctx.runMutation`, so they share the harness SQLite database.
543
+ */
224
544
  scheduler: FakeSchedulerControls;
225
545
  /**
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
- */
546
+ * Subscribe to a registered query (or inline query function) and receive
547
+ * an async iterable of snapshots. The first value is emitted immediately
548
+ * (the current query result). Subsequent values are emitted after each
549
+ * `mutation` / `run` call on this harness completes.
550
+ *
551
+ * Subscriptions are table-agnostic — any mutation triggers a re-evaluation.
552
+ * This matches the harness's single-writer model and keeps the implementation
553
+ * free of DO machinery.
554
+ * @example
555
+ * ```ts
556
+ * const sub = t.subscribe(list, {});
557
+ * const first = await sub.next(); // current result
558
+ * await t.mutation(send, { author: "ada", body: "hi" });
559
+ * const second = await sub.next(); // updated result
560
+ * await sub.return(); // unsubscribe
561
+ * ```
562
+ *
563
+ * The iterable is lazy — it never buffers more than one pending result.
564
+ * If you do not consume fast enough and multiple mutations fire, the next
565
+ * `next()` call will reflect the most-recent state (intermediate snapshots
566
+ * are coalesced).
567
+ */
248
568
  subscribe: {
249
569
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): TestSubscription<R>;
250
570
  <R>(inline: InlineQueryFunction<R>): TestSubscription<R>;
251
571
  };
572
+ /**
573
+ * What handlers attached to `ctx.span` — the **wide event** — during this
574
+ * harness's runs, so a test can assert the instrumentation itself:
575
+ *
576
+ * ```ts
577
+ * await t.mutation(checkout, { items: 3 });
578
+ * expect(t.wideEvent().attributes["cart.items"]).toBe(3);
579
+ * ```
580
+ *
581
+ * Accumulates across calls on this view (it is not reset per run), mirroring
582
+ * the harness's single shared database. Shared with any `withIdentity` view.
583
+ */
584
+ wideEvent: () => RecordedWideEvent;
252
585
  /** Return a harness view that shares this harness's db but reports the given identity on `ctx.auth`. */
253
586
  withIdentity: (identity: TestIdentity) => TestHarness;
254
587
  }
255
588
  /**
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
- */
589
+ * Spin up an in-memory Lunora function harness for `schema`.
590
+ *
591
+ * `lunoraTest(schema)` runs the migrations against a fresh `node:sqlite`
592
+ * database, builds the same `ctx.db` writer the real Durable Object builds (via
593
+ * `@lunora/shard-engine`'s `createShardCtxDb`, with the same `enforceRls: true`
594
+ * production's generated `buildCtx` passes), and returns a harness whose
595
+ * `query` / `mutation` / `action` execute a registered function's `handler`
596
+ * directly — no Durable Object, no `wrangler`, no network. Under a
597
+ * `.rls("required")` schema a procedure missing `.use(rls(...))` therefore
598
+ * rejects here exactly as it would on its first production dispatch — see
599
+ * `LunoraTestOptions.enforceRls` to opt out, and `run`'s doc for the trusted
600
+ * escape hatch (always unguarded).
601
+ *
602
+ * **v1 surfaces now supported:**
603
+ *
604
+ * - `ctx.env` (all contexts): inject the validated env via `options.env`; unset it
605
+ * stays `undefined`, matching the optional `ctx.env?` field.
606
+ * - `ctx.fetch` (actions): inject a custom `fetch` via `options.fetch`.
607
+ * - `ctx.scheduler` (mutations + actions): fully functional fake with virtual clock;
608
+ * control via `harness.scheduler.advance(ms)` / `runPending()` / `list()`. As in
609
+ * production it is transactional inside a mutation: a job scheduled by a mutation
610
+ * that then throws never becomes pending.
611
+ * - `harness.subscribe(query, args)`: async iterable that re-emits after mutations.
612
+ *
613
+ * **v1 stubs (still throwing):** `ctx.storage`, `ctx.vectors`, `ctx.workflows`.
614
+ * These are clearly documented follow-ups.
615
+ */
274
616
  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 };
617
+ /** One sample handed to a {@link Scorer}. */
618
+ interface ScorerSample {
619
+ /** The reference/gold answer, when the scorer compares against one. */
620
+ expected?: string;
621
+ /** The prompt/input that produced the output (for LLM-judge context). */
622
+ input?: string;
623
+ /** Arbitrary per-sample metadata carried through. */
624
+ metadata?: Record<string, unknown>;
625
+ /** The model/agent output under test. */
626
+ output: string;
627
+ }
628
+ /** A scorer's verdict: a `[0, 1]` score and an optional human-readable reason. */
629
+ interface ScoreResult {
630
+ reason?: string;
631
+ score: number;
632
+ }
633
+ /** A named scorer — returns a `[0, 1]` score (or a {@link ScoreResult}) for a sample. */
634
+ interface Scorer {
635
+ name: string;
636
+ score: (sample: ScorerSample) => Promise<ScoreResult | number> | ScoreResult | number;
637
+ }
638
+ /**
639
+ * What a `produce` runner may return: the output text alone, or the text plus
640
+ * metadata describing what the run actually did.
641
+ *
642
+ * The metadata form exists for scorers that judge more than the final string —
643
+ * a retrieval scorer needs the ranked ids the run retrieved, which only the run
644
+ * can know. It is merged OVER the case's own metadata before scoring.
645
+ */
646
+ interface ProducedOutput {
647
+ /** Merged over the case's `metadata`, then handed to every scorer. */
648
+ metadata?: Record<string, unknown>;
649
+ /** The output text under test. */
650
+ output: string;
651
+ }
652
+ /** One dataset case: an input and its optional gold answer/metadata. */
653
+ interface EvalCase {
654
+ expected?: string;
655
+ input: string;
656
+ metadata?: Record<string, unknown>;
657
+ }
658
+ /** The per-case eval result: the produced output plus each scorer's verdict and the mean. */
659
+ interface EvalItemResult {
660
+ average: number;
661
+ input: string;
662
+ output: string;
663
+ scores: Record<string, ScoreResult>;
664
+ }
665
+ /** The whole eval run: per-case results plus the mean of their averages. */
666
+ interface EvalResult {
667
+ average: number;
668
+ items: EvalItemResult[];
669
+ }
670
+ /** Score 1 if the output contains `needle` (case-insensitive unless `caseSensitive`). */
671
+ declare const containsScorer: (needle: string, options?: {
672
+ caseSensitive?: boolean;
673
+ }) => Scorer;
674
+ /** Score 1 when `pattern` matches the output. */
675
+ declare const regexScorer: (pattern: RegExp, name?: string) => Scorer;
676
+ /** Score 1 when the trimmed output exactly equals the trimmed `expected`. */
677
+ declare const exactMatchScorer: () => Scorer;
678
+ /** Score the fraction of `keywords` (case-insensitive) present in the output. */
679
+ declare const keywordScorer: (keywords: ReadonlyArray<string>) => Scorer;
680
+ /**
681
+ * An LLM-as-judge scorer. `judge` is INJECTED — a `(prompt) => Promise<string>`
682
+ * you wire to your model (e.g. via `ctx.ai` / `generateText`), so this module
683
+ * stays model-agnostic and the judge is mockable in tests. It returns the model's
684
+ * numeric verdict (`[0, 1]`) plus its reason.
685
+ */
686
+ declare const llmScorer: (options: {
687
+ criteria: string;
688
+ judge: (prompt: string) => Promise<string>;
689
+ name?: string;
690
+ }) => Scorer;
691
+ /** Run every scorer over one sample (concurrently) → each verdict keyed by name + their mean. */
692
+ declare const scoreSample: (sample: ScorerSample, scorers: ReadonlyArray<Scorer>) => Promise<{
693
+ average: number;
694
+ scores: Record<string, ScoreResult>;
695
+ }>;
696
+ /**
697
+ * Run a dataset through `produce` (e.g. an `agentHarness.run` wrapper returning
698
+ * the output text) and score each output with `scorers`. Cases run concurrently;
699
+ * give each its own thread/key inside `produce` if the producer is stateful.
700
+ * Returns per-case results plus the mean of their averages.
701
+ */
702
+ declare const evaluate: (cases: ReadonlyArray<EvalCase>, produce: (input: string) => Promise<ProducedOutput | string> | ProducedOutput | string, scorers: ReadonlyArray<Scorer>) => Promise<EvalResult>;
703
+ /** Where a retrieval scorer reads its two id lists from. */
704
+ interface RetrievalScorerOptions {
705
+ /** Metadata key holding the gold relevant ids. Default `"relevant"`. */
706
+ relevantKey?: string;
707
+ /** Metadata key holding the run's ranked retrieved ids. Default `"retrieved"`. */
708
+ retrievedKey?: string;
709
+ }
710
+ /**
711
+ * Recall@k scorer — what fraction of the gold passages made it into the top
712
+ * `k`.
713
+ *
714
+ * This is the ceiling on everything downstream: a passage retrieval never
715
+ * returned is one no reranker can promote and no prompt can cite. Omit `k` to
716
+ * score the whole retrieved list.
717
+ */
718
+ declare const recallAtK: (k?: number, options?: RetrievalScorerOptions) => Scorer;
719
+ /**
720
+ * Precision@k scorer — what fraction of the top `k` retrieved passages are
721
+ * gold.
722
+ *
723
+ * This is the counterweight to recall: padding `topK` raises recall for free
724
+ * while burying the answer in noise the model has to read past, and pay for.
725
+ * Omit `k` to score the whole retrieved list.
726
+ */
727
+ declare const precisionAtK: (k?: number, options?: RetrievalScorerOptions) => Scorer;
728
+ /**
729
+ * Mean Reciprocal Rank scorer — `1 / rank` of the first gold passage: 1 if it
730
+ * is first, 0.5 if second, 0 if absent.
731
+ *
732
+ * This is the metric that notices ordering, which recall cannot. A gold passage
733
+ * at rank 20 counts the same as rank 1 for recall@20, but only one of those
734
+ * survives a context-window trim or a model that skims the top of its prompt.
735
+ */
736
+ declare const mrrScorer: (options?: RetrievalScorerOptions) => Scorer;
737
+ /**
738
+ * Normalized Discounted Cumulative Gain scorer — relevance discounted
739
+ * logarithmically by rank, divided by the best achievable arrangement.
740
+ *
741
+ * This is the one to gate on when comparing retrieval strategies. Unlike recall
742
+ * it is sensitive to order, and unlike MRR it credits every gold passage rather
743
+ * than only the first — so it is the metric that can actually say whether a
744
+ * reranker or a hybrid leg helped.
745
+ *
746
+ * Relevance is binary: an id is gold or it is not, which is what a gold-id set
747
+ * expresses. Graded relevance would need per-id weights.
748
+ */
749
+ declare const ndcgAtK: (k?: number, options?: RetrievalScorerOptions) => Scorer;
750
+ /**
751
+ * Groundedness scorer — does the answer assert only what the retrieved context
752
+ * supports?
753
+ *
754
+ * This is the generation-side counterpart to the metrics above: perfect
755
+ * retrieval still fails if the model answers from its own weights. It scores
756
+ * the output against the context via an injected `judge`, the same shape
757
+ * `llmScorer` takes, so this stays model-agnostic and mockable.
758
+ *
759
+ * Reads the context from `metadata.context` by default — the `context` string
760
+ * `retrieve()` already returns. Fails closed: no context means nothing could
761
+ * have grounded the answer.
762
+ */
763
+ declare const groundednessScorer: (options: {
764
+ contextKey?: string;
765
+ judge: (prompt: string) => Promise<string>;
766
+ name?: string;
767
+ }) => Scorer;
768
+ 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 ProducedOutput, type RecordEvaluationInput, type RetrievalScorerOptions, type ScheduledJobFailure, type ScoreResult, type Scorer, type ScorerSample, type SweepOptions, type TestHarness, type TestIdentity, type TestSubscription, agentHarness, containsScorer, evaluate, evaluationAttributes, exactMatchScorer, finalTurn, groundednessScorer, keywordScorer, llmScorer, lunoraTest, mrrScorer, ndcgAtK, precisionAtK, recallAtK, recordEvaluation, regexScorer, scoreSample, toolCallTurn };