@lunora/testing 1.0.0-alpha.13 → 1.0.0-alpha.131
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/LICENSE.md +6 -0
- package/dist/index.d.mts +663 -185
- package/dist/index.d.ts +663 -185
- package/dist/index.mjs +1 -2
- package/dist/packem_shared/agentHarness-DA9onGVO.mjs +1 -0
- package/dist/packem_shared/containsScorer-gv0Sdd86.mjs +2 -0
- package/dist/packem_shared/evaluationAttributes-CYLgTP1P.mjs +1 -0
- package/dist/packem_shared/groundednessScorer-CznJBIjn.mjs +3 -0
- package/dist/packem_shared/lunoraTest-UV1TxREP.mjs +1 -0
- package/dist/playwright.d.mts +126 -0
- package/dist/playwright.d.ts +126 -0
- package/dist/playwright.mjs +1 -0
- package/package.json +19 -4
- package/dist/packem_shared/lunoraTest-Dm9lhBEx.mjs +0 -422
package/dist/index.d.mts
CHANGED
|
@@ -1,17 +1,248 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
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
|
+
/**
|
|
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
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
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,100 @@ 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
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
|
|
58
|
-
|
|
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
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
}
|
|
83
329
|
/**
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
|
|
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
|
-
*/
|
|
330
|
+
* The schema value produced by `@lunora/server`'s `defineSchema`. Accepted
|
|
331
|
+
* structurally; internally it is handed to `@lunora/do`'s `runShardMigrations` /
|
|
332
|
+
* `createShardCtxDb`, whose `SchemaLike` is the same shape declared in the DO
|
|
333
|
+
* package — the two are structurally compatible at runtime (only their
|
|
334
|
+
* independently-declared trigger nesting drifts at the type level), so the
|
|
335
|
+
* boundary cast below is sound.
|
|
336
|
+
*/
|
|
100
337
|
type TestSchema = Schema<Record<string, TableDefinition>>;
|
|
101
338
|
/**
|
|
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
|
-
*/
|
|
339
|
+
* A user-supplied identity, surfaced to handlers via `ctx.auth`. `userId` is the
|
|
340
|
+
* subject the handler reads from `ctx.auth.userId`; any additional fields are
|
|
341
|
+
* returned verbatim from `ctx.auth.getIdentity()` (mirroring a decoded JWT).
|
|
342
|
+
*/
|
|
106
343
|
interface TestIdentity extends Record<string, unknown> {
|
|
107
344
|
userId?: null | string;
|
|
108
345
|
}
|
|
109
346
|
/**
|
|
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
|
-
*/
|
|
347
|
+
* An async iterable/iterator returned by {@link TestHarness.subscribe}.
|
|
348
|
+
* Guarantees `return()` is always defined (unlike the optional `AsyncIterator.return`),
|
|
349
|
+
* so callers can always unsubscribe without a `?.` guard.
|
|
350
|
+
*/
|
|
114
351
|
interface TestSubscription<R> extends AsyncIterable<R> {
|
|
115
352
|
next: () => Promise<IteratorResult<R, R>>;
|
|
116
353
|
return: () => Promise<IteratorResult<R, R>>;
|
|
@@ -120,75 +357,117 @@ type InlineQueryFunction<R> = (context: QueryCtx) => Promise<R> | R;
|
|
|
120
357
|
type InlineMutationFunction<R> = (context: MutationCtx) => Promise<R> | R;
|
|
121
358
|
type InlineActionFunction<R> = (context: ActionCtx) => Promise<R> | R;
|
|
122
359
|
/**
|
|
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
|
|
134
|
-
* `handler` and ignores the return value).
|
|
135
|
-
*/
|
|
360
|
+
* A map from function path strings (e.g. `"messages:send"`) to their
|
|
361
|
+
* registered function objects. Used by the fake scheduler to resolve
|
|
362
|
+
* `ctx.scheduler.runAfter(delay, "messages:send", args)` → handler invocation.
|
|
363
|
+
*
|
|
364
|
+
* Only mutations and actions can be scheduled in production; queries passed
|
|
365
|
+
* here will be accepted but produce a console.warn at dispatch time.
|
|
366
|
+
*
|
|
367
|
+
* The value type uses `any` because `RegisteredFunction` is contravariant in its
|
|
368
|
+
* args type parameter — a `RegisteredMutation` with concrete args is not assignable
|
|
369
|
+
* to `RegisteredMutation` with `ArgsValidator` at the type level even though at
|
|
370
|
+
* runtime it is sound (the fake scheduler passes `Record<string, unknown>` to
|
|
371
|
+
* `handler` and ignores the return value).
|
|
372
|
+
*/
|
|
136
373
|
type FunctionRegistry = Record<string, RegisteredAction<any, any> | RegisteredMutation<any, any> | RegisteredQuery<any, any>>;
|
|
137
374
|
/**
|
|
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
|
-
*/
|
|
375
|
+
* Options accepted by {@link lunoraTest}.
|
|
376
|
+
*
|
|
377
|
+
* All options are optional — `lunoraTest(schema)` preserves v1 behaviour with
|
|
378
|
+
* clearly-throwing stubs for unsupported surfaces.
|
|
379
|
+
*/
|
|
143
380
|
interface LunoraTestOptions {
|
|
144
381
|
/**
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
382
|
+
* Enforce the secure-by-default RLS guard on the writer registered
|
|
383
|
+
* procedures dispatch through (`query`/`mutation`/`action`, via
|
|
384
|
+
* `reference.handler`) — the same `enforceRls: true` production's generated
|
|
385
|
+
* `buildCtx` always passes. Under a `.rls("required")` schema, a procedure
|
|
386
|
+
* that touches a known, non-`.public()` table without `.use(rls(...))` in
|
|
387
|
+
* its chain rejects with `RlsRequiredError`, exactly as it would on first
|
|
388
|
+
* dispatch in production. Defaults to `true` so a green suite means the
|
|
389
|
+
* deploy is RLS-safe; the harness's other surfaces — `t.run` and any
|
|
390
|
+
* `@lunora/seed` helper built on it — stay on the trusted, UNGUARDED writer
|
|
391
|
+
* regardless of this flag (mirroring production's admin/migration system
|
|
392
|
+
* paths).
|
|
393
|
+
*
|
|
394
|
+
* Set to `false` to opt back into the pre-guard permissive behaviour (every
|
|
395
|
+
* `lunoraTest` release before this option existed): every procedure's
|
|
396
|
+
* `ctx.db` goes unguarded even under a `.rls("required")` schema. This
|
|
397
|
+
* forfeits the "a passing suite means the deploy is safe" guarantee — a
|
|
398
|
+
* procedure that forgot `.use(rls(...))` will pass in tests and throw
|
|
399
|
+
* `RlsRequiredError` on its first production request. No effect when the
|
|
400
|
+
* schema does not declare `.rls("required")` (the guard is a no-op there
|
|
401
|
+
* either way).
|
|
402
|
+
* @default true
|
|
403
|
+
* @example
|
|
404
|
+
* ```ts
|
|
405
|
+
* // Restores the old permissive behavior for a suite not yet migrated.
|
|
406
|
+
* const t = lunoraTest(schema, { enforceRls: false });
|
|
407
|
+
* ```
|
|
408
|
+
*/
|
|
409
|
+
enforceRls?: boolean;
|
|
410
|
+
/**
|
|
411
|
+
* Injectable `ctx.env` for every context (query / mutation / action). When
|
|
412
|
+
* provided, handlers that read `ctx.env.SOME_KEY` (the validated `defineEnv`
|
|
413
|
+
* surface) see this object. Left unset it stays `undefined` — matching the
|
|
414
|
+
* optional `ctx.env?` field, so graceful `ctx.env?.KEY` access still yields
|
|
415
|
+
* `undefined` rather than throwing. Not a throwing stub for exactly that
|
|
416
|
+
* reason: `env` is designed to be legitimately absent.
|
|
417
|
+
* @example
|
|
418
|
+
* ```ts
|
|
419
|
+
* const t = lunoraTest(schema, { env: { STRIPE_KEY: "sk_test_…" } });
|
|
420
|
+
* ```
|
|
421
|
+
*/
|
|
422
|
+
env?: Record<string, unknown>;
|
|
423
|
+
/**
|
|
424
|
+
* Injectable `fetch` implementation for action contexts. When provided,
|
|
425
|
+
* `ctx.fetch` in every `action` (and `withIdentity` views) resolves to this
|
|
426
|
+
* function rather than throwing the "not available in v1" stub.
|
|
427
|
+
*
|
|
428
|
+
* Pass `vi.fn()` or any `typeof globalThis.fetch` compatible implementation.
|
|
429
|
+
* @example
|
|
430
|
+
* ```ts
|
|
431
|
+
* const fakeFetch = vi.fn().mockResolvedValue(Response.json({ ok: true }));
|
|
432
|
+
* const t = lunoraTest(schema, { fetch: fakeFetch });
|
|
433
|
+
* ```
|
|
434
|
+
*/
|
|
156
435
|
fetch?: typeof globalThis.fetch;
|
|
157
436
|
/**
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
437
|
+
* Function registry for the fake in-memory scheduler. Maps a
|
|
438
|
+
* `functionPath` string (the value passed as the second argument to
|
|
439
|
+
* `ctx.scheduler.runAfter` / `ctx.scheduler.runAt`) to the corresponding
|
|
440
|
+
* registered function object.
|
|
441
|
+
*
|
|
442
|
+
* Only required if your handlers schedule work. Scheduled jobs for paths
|
|
443
|
+
* NOT listed here produce a `console.warn` at dispatch time (matching prod
|
|
444
|
+
* behaviour for unknown paths).
|
|
445
|
+
* @example
|
|
446
|
+
* ```ts
|
|
447
|
+
* const t = lunoraTest(schema, {
|
|
448
|
+
* functions: { "messages:send": sendMutation },
|
|
449
|
+
* });
|
|
450
|
+
* ```
|
|
451
|
+
*/
|
|
173
452
|
functions?: FunctionRegistry;
|
|
174
453
|
/**
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
454
|
+
* Fixed value for `ctx.now` (epoch ms) in every context. Production captures
|
|
455
|
+
* `Date.now()` once per execution; in tests a fixed `now` makes time-dependent
|
|
456
|
+
* handlers deterministic. Defaults to the wall clock at harness creation.
|
|
457
|
+
* @example
|
|
458
|
+
* ```ts
|
|
459
|
+
* const t = lunoraTest(schema, { now: 1_700_000_000_000 });
|
|
460
|
+
* ```
|
|
461
|
+
*/
|
|
183
462
|
now?: number;
|
|
184
463
|
}
|
|
185
464
|
/**
|
|
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
|
-
*/
|
|
465
|
+
* The in-memory test harness returned by {@link lunoraTest}. Mirrors the first
|
|
466
|
+
* five methods of Convex's `convexTest`: `query` / `mutation` / `action` / `run`
|
|
467
|
+
* / `withIdentity`. All five share one in-memory `node:sqlite` backend, so a
|
|
468
|
+
* write from one method is visible to a read from another (including across a
|
|
469
|
+
* `withIdentity` scope).
|
|
470
|
+
*/
|
|
192
471
|
interface TestHarness {
|
|
193
472
|
/** Run a registered `action` (or an inline `async (context) => …`) against the harness. */
|
|
194
473
|
action: {
|
|
@@ -207,69 +486,268 @@ interface TestHarness {
|
|
|
207
486
|
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): Promise<R>;
|
|
208
487
|
<R>(inline: InlineQueryFunction<R>): Promise<R>;
|
|
209
488
|
};
|
|
210
|
-
/**
|
|
489
|
+
/**
|
|
490
|
+
* Direct db access at mutation-level (read + write), mirroring `convexTest`'s
|
|
491
|
+
* `run`. This is the harness's trusted escape hatch: `ctx.db` here is always
|
|
492
|
+
* the UNGUARDED writer, regardless of `options.enforceRls` or the schema's
|
|
493
|
+
* RLS mode — seeding/asserting against a protected table never trips the
|
|
494
|
+
* secure-by-default guard. A `ctx.runMutation`/`ctx.runQuery` call from
|
|
495
|
+
* inside the body still dispatches the target as a real registered
|
|
496
|
+
* procedure, so it is guarded exactly as `t.mutation`/`t.query` would guard
|
|
497
|
+
* it.
|
|
498
|
+
*/
|
|
211
499
|
run: <R>(function_: InlineMutationFunction<R>) => Promise<R>;
|
|
212
500
|
/**
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
501
|
+
* Controls for the fake in-memory scheduler. Always present; scheduler
|
|
502
|
+
* jobs only execute when you call `advance(ms)` or `runPending()`.
|
|
503
|
+
*
|
|
504
|
+
* - `list()` — snapshot of all pending jobs (enqueue order).
|
|
505
|
+
* - `advance(ms)` — tick the virtual clock forward by `ms` ms, executing every job
|
|
506
|
+
* whose `scheduledFor` is now at or below virtual now.
|
|
507
|
+
* - `runPending()` — execute all currently pending jobs regardless of their scheduled time.
|
|
508
|
+
*
|
|
509
|
+
* Scheduled jobs run through the same `runInternal` dispatch as
|
|
510
|
+
* `ctx.runMutation`, so they share the harness SQLite database.
|
|
511
|
+
*/
|
|
224
512
|
scheduler: FakeSchedulerControls;
|
|
225
513
|
/**
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
514
|
+
* Subscribe to a registered query (or inline query function) and receive
|
|
515
|
+
* an async iterable of snapshots. The first value is emitted immediately
|
|
516
|
+
* (the current query result). Subsequent values are emitted after each
|
|
517
|
+
* `mutation` / `run` call on this harness completes.
|
|
518
|
+
*
|
|
519
|
+
* Subscriptions are table-agnostic — any mutation triggers a re-evaluation.
|
|
520
|
+
* This matches the harness's single-writer model and keeps the implementation
|
|
521
|
+
* free of DO machinery.
|
|
522
|
+
* @example
|
|
523
|
+
* ```ts
|
|
524
|
+
* const sub = t.subscribe(list, {});
|
|
525
|
+
* const first = await sub.next(); // current result
|
|
526
|
+
* await t.mutation(send, { author: "ada", body: "hi" });
|
|
527
|
+
* const second = await sub.next(); // updated result
|
|
528
|
+
* await sub.return(); // unsubscribe
|
|
529
|
+
* ```
|
|
530
|
+
*
|
|
531
|
+
* The iterable is lazy — it never buffers more than one pending result.
|
|
532
|
+
* If you do not consume fast enough and multiple mutations fire, the next
|
|
533
|
+
* `next()` call will reflect the most-recent state (intermediate snapshots
|
|
534
|
+
* are coalesced).
|
|
535
|
+
*/
|
|
248
536
|
subscribe: {
|
|
249
537
|
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): TestSubscription<R>;
|
|
250
538
|
<R>(inline: InlineQueryFunction<R>): TestSubscription<R>;
|
|
251
539
|
};
|
|
540
|
+
/**
|
|
541
|
+
* What handlers attached to `ctx.span` — the **wide event** — during this
|
|
542
|
+
* harness's runs, so a test can assert the instrumentation itself:
|
|
543
|
+
*
|
|
544
|
+
* ```ts
|
|
545
|
+
* await t.mutation(checkout, { items: 3 });
|
|
546
|
+
* expect(t.wideEvent().attributes["cart.items"]).toBe(3);
|
|
547
|
+
* ```
|
|
548
|
+
*
|
|
549
|
+
* Accumulates across calls on this view (it is not reset per run), mirroring
|
|
550
|
+
* the harness's single shared database. Shared with any `withIdentity` view.
|
|
551
|
+
*/
|
|
552
|
+
wideEvent: () => RecordedWideEvent;
|
|
252
553
|
/** Return a harness view that shares this harness's db but reports the given identity on `ctx.auth`. */
|
|
253
554
|
withIdentity: (identity: TestIdentity) => TestHarness;
|
|
254
555
|
}
|
|
556
|
+
/** What a handler attached to the dispatch's span (`ctx.span`) during a harness run. */
|
|
557
|
+
interface RecordedWideEvent {
|
|
558
|
+
/**
|
|
559
|
+
* Attributes accumulated across the run, merged in call order. Values are
|
|
560
|
+
* recorded AS PASSED (not coerced the way the real pipeline normalizes them),
|
|
561
|
+
* so a test asserts on what the handler meant rather than on the wire form.
|
|
562
|
+
*/
|
|
563
|
+
attributes: LogFields;
|
|
564
|
+
/** Span events recorded via `ctx.span.addEvent` / `recordException`, in order. */
|
|
565
|
+
events: {
|
|
566
|
+
attributes?: LogFields;
|
|
567
|
+
name: string;
|
|
568
|
+
}[];
|
|
569
|
+
/** Links recorded via `ctx.span.addLink`, in order. */
|
|
570
|
+
links: {
|
|
571
|
+
spanId: string;
|
|
572
|
+
traceId: string;
|
|
573
|
+
}[];
|
|
574
|
+
}
|
|
255
575
|
/**
|
|
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/
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
266
|
-
*
|
|
267
|
-
*
|
|
268
|
-
*
|
|
269
|
-
*
|
|
270
|
-
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
273
|
-
|
|
576
|
+
* Spin up an in-memory Lunora function harness for `schema`.
|
|
577
|
+
*
|
|
578
|
+
* `lunoraTest(schema)` runs the migrations against a fresh `node:sqlite`
|
|
579
|
+
* database, builds the same `ctx.db` writer the real Durable Object builds (via
|
|
580
|
+
* `@lunora/shard-engine`'s `createShardCtxDb`, with the same `enforceRls: true`
|
|
581
|
+
* production's generated `buildCtx` passes), and returns a harness whose
|
|
582
|
+
* `query` / `mutation` / `action` execute a registered function's `handler`
|
|
583
|
+
* directly — no Durable Object, no `wrangler`, no network. Under a
|
|
584
|
+
* `.rls("required")` schema a procedure missing `.use(rls(...))` therefore
|
|
585
|
+
* rejects here exactly as it would on its first production dispatch — see
|
|
586
|
+
* `LunoraTestOptions.enforceRls` to opt out, and `run`'s doc for the trusted
|
|
587
|
+
* escape hatch (always unguarded).
|
|
588
|
+
*
|
|
589
|
+
* **v1 surfaces now supported:**
|
|
590
|
+
*
|
|
591
|
+
* - `ctx.env` (all contexts): inject the validated env via `options.env`; unset it
|
|
592
|
+
* stays `undefined`, matching the optional `ctx.env?` field.
|
|
593
|
+
* - `ctx.fetch` (actions): inject a custom `fetch` via `options.fetch`.
|
|
594
|
+
* - `ctx.scheduler` (mutations + actions): fully functional fake with virtual clock;
|
|
595
|
+
* control via `harness.scheduler.advance(ms)` / `runPending()` / `list()`.
|
|
596
|
+
* - `harness.subscribe(query, args)`: async iterable that re-emits after mutations.
|
|
597
|
+
*
|
|
598
|
+
* **v1 stubs (still throwing):** `ctx.storage`, `ctx.vectors`, `ctx.workflows`.
|
|
599
|
+
* These are clearly documented follow-ups.
|
|
600
|
+
*/
|
|
274
601
|
declare const lunoraTest: (schema: TestSchema, options?: LunoraTestOptions) => TestHarness;
|
|
275
|
-
|
|
602
|
+
/** One sample handed to a {@link Scorer}. */
|
|
603
|
+
interface ScorerSample {
|
|
604
|
+
/** The reference/gold answer, when the scorer compares against one. */
|
|
605
|
+
expected?: string;
|
|
606
|
+
/** The prompt/input that produced the output (for LLM-judge context). */
|
|
607
|
+
input?: string;
|
|
608
|
+
/** Arbitrary per-sample metadata carried through. */
|
|
609
|
+
metadata?: Record<string, unknown>;
|
|
610
|
+
/** The model/agent output under test. */
|
|
611
|
+
output: string;
|
|
612
|
+
}
|
|
613
|
+
/** A scorer's verdict: a `[0, 1]` score and an optional human-readable reason. */
|
|
614
|
+
interface ScoreResult {
|
|
615
|
+
reason?: string;
|
|
616
|
+
score: number;
|
|
617
|
+
}
|
|
618
|
+
/** A named scorer — returns a `[0, 1]` score (or a {@link ScoreResult}) for a sample. */
|
|
619
|
+
interface Scorer {
|
|
620
|
+
name: string;
|
|
621
|
+
score: (sample: ScorerSample) => Promise<ScoreResult | number> | ScoreResult | number;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* What a `produce` runner may return: the output text alone, or the text plus
|
|
625
|
+
* metadata describing what the run actually did.
|
|
626
|
+
*
|
|
627
|
+
* The metadata form exists for scorers that judge more than the final string —
|
|
628
|
+
* a retrieval scorer needs the ranked ids the run retrieved, which only the run
|
|
629
|
+
* can know. It is merged OVER the case's own metadata before scoring.
|
|
630
|
+
*/
|
|
631
|
+
interface ProducedOutput {
|
|
632
|
+
/** Merged over the case's `metadata`, then handed to every scorer. */
|
|
633
|
+
metadata?: Record<string, unknown>;
|
|
634
|
+
/** The output text under test. */
|
|
635
|
+
output: string;
|
|
636
|
+
}
|
|
637
|
+
/** One dataset case: an input and its optional gold answer/metadata. */
|
|
638
|
+
interface EvalCase {
|
|
639
|
+
expected?: string;
|
|
640
|
+
input: string;
|
|
641
|
+
metadata?: Record<string, unknown>;
|
|
642
|
+
}
|
|
643
|
+
/** The per-case eval result: the produced output plus each scorer's verdict and the mean. */
|
|
644
|
+
interface EvalItemResult {
|
|
645
|
+
average: number;
|
|
646
|
+
input: string;
|
|
647
|
+
output: string;
|
|
648
|
+
scores: Record<string, ScoreResult>;
|
|
649
|
+
}
|
|
650
|
+
/** The whole eval run: per-case results plus the mean of their averages. */
|
|
651
|
+
interface EvalResult {
|
|
652
|
+
average: number;
|
|
653
|
+
items: EvalItemResult[];
|
|
654
|
+
}
|
|
655
|
+
/** Score 1 if the output contains `needle` (case-insensitive unless `caseSensitive`). */
|
|
656
|
+
declare const containsScorer: (needle: string, options?: {
|
|
657
|
+
caseSensitive?: boolean;
|
|
658
|
+
}) => Scorer;
|
|
659
|
+
/** Score 1 when `pattern` matches the output. */
|
|
660
|
+
declare const regexScorer: (pattern: RegExp, name?: string) => Scorer;
|
|
661
|
+
/** Score 1 when the trimmed output exactly equals the trimmed `expected`. */
|
|
662
|
+
declare const exactMatchScorer: () => Scorer;
|
|
663
|
+
/** Score the fraction of `keywords` (case-insensitive) present in the output. */
|
|
664
|
+
declare const keywordScorer: (keywords: ReadonlyArray<string>) => Scorer;
|
|
665
|
+
/**
|
|
666
|
+
* An LLM-as-judge scorer. `judge` is INJECTED — a `(prompt) => Promise<string>`
|
|
667
|
+
* you wire to your model (e.g. via `ctx.ai` / `generateText`), so this module
|
|
668
|
+
* stays model-agnostic and the judge is mockable in tests. It returns the model's
|
|
669
|
+
* numeric verdict (`[0, 1]`) plus its reason.
|
|
670
|
+
*/
|
|
671
|
+
declare const llmScorer: (options: {
|
|
672
|
+
criteria: string;
|
|
673
|
+
judge: (prompt: string) => Promise<string>;
|
|
674
|
+
name?: string;
|
|
675
|
+
}) => Scorer;
|
|
676
|
+
/** Run every scorer over one sample (concurrently) → each verdict keyed by name + their mean. */
|
|
677
|
+
declare const scoreSample: (sample: ScorerSample, scorers: ReadonlyArray<Scorer>) => Promise<{
|
|
678
|
+
average: number;
|
|
679
|
+
scores: Record<string, ScoreResult>;
|
|
680
|
+
}>;
|
|
681
|
+
/**
|
|
682
|
+
* Run a dataset through `produce` (e.g. an `agentHarness.run` wrapper returning
|
|
683
|
+
* the output text) and score each output with `scorers`. Cases run concurrently;
|
|
684
|
+
* give each its own thread/key inside `produce` if the producer is stateful.
|
|
685
|
+
* Returns per-case results plus the mean of their averages.
|
|
686
|
+
*/
|
|
687
|
+
declare const evaluate: (cases: ReadonlyArray<EvalCase>, produce: (input: string) => Promise<ProducedOutput | string> | ProducedOutput | string, scorers: ReadonlyArray<Scorer>) => Promise<EvalResult>;
|
|
688
|
+
/** Where a retrieval scorer reads its two id lists from. */
|
|
689
|
+
interface RetrievalScorerOptions {
|
|
690
|
+
/** Metadata key holding the gold relevant ids. Default `"relevant"`. */
|
|
691
|
+
relevantKey?: string;
|
|
692
|
+
/** Metadata key holding the run's ranked retrieved ids. Default `"retrieved"`. */
|
|
693
|
+
retrievedKey?: string;
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Recall@k scorer — what fraction of the gold passages made it into the top
|
|
697
|
+
* `k`.
|
|
698
|
+
*
|
|
699
|
+
* This is the ceiling on everything downstream: a passage retrieval never
|
|
700
|
+
* returned is one no reranker can promote and no prompt can cite. Omit `k` to
|
|
701
|
+
* score the whole retrieved list.
|
|
702
|
+
*/
|
|
703
|
+
declare const recallAtK: (k?: number, options?: RetrievalScorerOptions) => Scorer;
|
|
704
|
+
/**
|
|
705
|
+
* Precision@k scorer — what fraction of the top `k` retrieved passages are
|
|
706
|
+
* gold.
|
|
707
|
+
*
|
|
708
|
+
* This is the counterweight to recall: padding `topK` raises recall for free
|
|
709
|
+
* while burying the answer in noise the model has to read past, and pay for.
|
|
710
|
+
* Omit `k` to score the whole retrieved list.
|
|
711
|
+
*/
|
|
712
|
+
declare const precisionAtK: (k?: number, options?: RetrievalScorerOptions) => Scorer;
|
|
713
|
+
/**
|
|
714
|
+
* Mean Reciprocal Rank scorer — `1 / rank` of the first gold passage: 1 if it
|
|
715
|
+
* is first, 0.5 if second, 0 if absent.
|
|
716
|
+
*
|
|
717
|
+
* This is the metric that notices ordering, which recall cannot. A gold passage
|
|
718
|
+
* at rank 20 counts the same as rank 1 for recall@20, but only one of those
|
|
719
|
+
* survives a context-window trim or a model that skims the top of its prompt.
|
|
720
|
+
*/
|
|
721
|
+
declare const mrrScorer: (options?: RetrievalScorerOptions) => Scorer;
|
|
722
|
+
/**
|
|
723
|
+
* Normalized Discounted Cumulative Gain scorer — relevance discounted
|
|
724
|
+
* logarithmically by rank, divided by the best achievable arrangement.
|
|
725
|
+
*
|
|
726
|
+
* This is the one to gate on when comparing retrieval strategies. Unlike recall
|
|
727
|
+
* it is sensitive to order, and unlike MRR it credits every gold passage rather
|
|
728
|
+
* than only the first — so it is the metric that can actually say whether a
|
|
729
|
+
* reranker or a hybrid leg helped.
|
|
730
|
+
*
|
|
731
|
+
* Relevance is binary: an id is gold or it is not, which is what a gold-id set
|
|
732
|
+
* expresses. Graded relevance would need per-id weights.
|
|
733
|
+
*/
|
|
734
|
+
declare const ndcgAtK: (k?: number, options?: RetrievalScorerOptions) => Scorer;
|
|
735
|
+
/**
|
|
736
|
+
* Groundedness scorer — does the answer assert only what the retrieved context
|
|
737
|
+
* supports?
|
|
738
|
+
*
|
|
739
|
+
* This is the generation-side counterpart to the metrics above: perfect
|
|
740
|
+
* retrieval still fails if the model answers from its own weights. It scores
|
|
741
|
+
* the output against the context via an injected `judge`, the same shape
|
|
742
|
+
* `llmScorer` takes, so this stays model-agnostic and mockable.
|
|
743
|
+
*
|
|
744
|
+
* Reads the context from `metadata.context` by default — the `context` string
|
|
745
|
+
* `retrieve()` already returns. Fails closed: no context means nothing could
|
|
746
|
+
* have grounded the answer.
|
|
747
|
+
*/
|
|
748
|
+
declare const groundednessScorer: (options: {
|
|
749
|
+
contextKey?: string;
|
|
750
|
+
judge: (prompt: string) => Promise<string>;
|
|
751
|
+
name?: string;
|
|
752
|
+
}) => Scorer;
|
|
753
|
+
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 };
|