@rulvar/cli 1.0.0

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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/cli.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ import { r as runCli, t as processIo } from "./io-DUfUn6KG.js";
3
+ //#region src/cli.ts
4
+ /**
5
+ * The `rulvar` bin entry: thin wrapper over runCli with process io.
6
+ */
7
+ runCli(process.argv.slice(2), {
8
+ cwd: process.cwd(),
9
+ io: processIo()
10
+ }).then((code) => {
11
+ process.exitCode = code;
12
+ }, (thrown) => {
13
+ process.stderr.write(`${thrown instanceof Error ? thrown.stack : String(thrown)}\n`);
14
+ process.exitCode = 1;
15
+ });
16
+ //#endregion
17
+ export {};
@@ -0,0 +1,474 @@
1
+ import { KnowledgeCasError, claimExpiry, defineWorkflow } from "@rulvar/core";
2
+ import { createHash } from "node:crypto";
3
+ //#region ../evals/dist/index.js
4
+ /**
5
+ * @rulvar/evals (M9-T02): EvalCase, the grader contract, and the case and
6
+ * suite runners. A separate quality-measurement package built strictly on
7
+ * the public APIs (L6).
8
+ *
9
+ * Owning spec: docs/09-observability-testing-spec.md, section
10
+ * "@rulvar/evals"; determinism rules in docs/11-testing-strategy.md,
11
+ * section "Eval CI": judge graders run THROUGH the engine, so judge calls
12
+ * are journaled, budgeted, and VCR-recordable, and an eval suite replays
13
+ * deterministically from cassettes with zero live calls.
14
+ */
15
+ /** Thrown when a judge run does not settle ok. */
16
+ var EvalJudgeError = class extends Error {
17
+ judgeRun;
18
+ status;
19
+ constructor(judgeRun, status, detail) {
20
+ super(`eval judge run '${judgeRun}' settled '${status}'${detail === void 0 ? "" : `: ${detail}`}`);
21
+ this.name = "EvalJudgeError";
22
+ this.judgeRun = judgeRun;
23
+ this.status = status;
24
+ }
25
+ };
26
+ /**
27
+ * Runs one EvalCase on the given engine: the target workflow as its own
28
+ * run, pure graders host-side over the outcome, judge graders through the
29
+ * engine via GraderContext.judge. Grader thrown errors are not absorbed:
30
+ * a grader that cannot grade is a defect of the suite, not a failed case.
31
+ */
32
+ async function runEvalCase(engine, evalCase, options = {}) {
33
+ const name = options.name ?? evalCase.workflow.name;
34
+ const timing = {};
35
+ const handle = engine.run(evalCase.workflow, evalCase.args, {
36
+ name: `eval:${name}`,
37
+ ...options.budgetUsd === void 0 ? {} : { budgetUsd: options.budgetUsd }
38
+ });
39
+ const offStart = handle.on("run:start", (event) => {
40
+ timing.start ??= event.ts;
41
+ });
42
+ const offEnd = handle.on("run:end", (event) => {
43
+ timing.end ??= event.ts;
44
+ });
45
+ const outcome = await handle.result;
46
+ offStart();
47
+ offEnd();
48
+ let judgeCostUsd = 0;
49
+ let judgeOrdinal = 0;
50
+ const context = {
51
+ value: outcome.value,
52
+ outcome,
53
+ async judge(spec) {
54
+ const ordinal = judgeOrdinal;
55
+ judgeOrdinal += 1;
56
+ const judged = await runJudge(engine, `${name}:${ordinal}`, spec, options.judgeBudgetUsd);
57
+ judgeCostUsd += judged.costUsd;
58
+ return judged.output;
59
+ }
60
+ };
61
+ const verdicts = [];
62
+ for (const grader of evalCase.graders) verdicts.push(await grader.grade(context));
63
+ const latencyMs = timing.start !== void 0 && timing.end !== void 0 ? Math.max(0, Date.parse(timing.end) - Date.parse(timing.start)) : 0;
64
+ return {
65
+ name,
66
+ status: outcome.status,
67
+ passed: outcome.status === "ok" && verdicts.every((verdict) => verdict.passed),
68
+ verdicts,
69
+ costUsd: outcome.cost.totalUsd + judgeCostUsd,
70
+ judgeCostUsd,
71
+ latencyMs,
72
+ usage: outcome.usage,
73
+ ...outcome.error === void 0 ? {} : { error: outcome.error }
74
+ };
75
+ }
76
+ async function runJudge(engine, judgeName, spec, budgetUsd) {
77
+ const workflowName = `eval-judge:${judgeName}`;
78
+ const judgeWorkflow = defineWorkflow({ name: workflowName }, async (ctx) => {
79
+ return await ctx.agent(spec.prompt, {
80
+ model: spec.model,
81
+ schema: spec.schema,
82
+ label: "eval-judge",
83
+ onError: "throw"
84
+ });
85
+ });
86
+ const outcome = await engine.run(judgeWorkflow, null, {
87
+ name: workflowName,
88
+ ...budgetUsd === void 0 ? {} : { budgetUsd }
89
+ }).result;
90
+ if (outcome.status !== "ok") throw new EvalJudgeError(workflowName, outcome.status, outcome.error?.message);
91
+ return {
92
+ output: outcome.value ?? null,
93
+ costUsd: outcome.cost.totalUsd
94
+ };
95
+ }
96
+ /**
97
+ * Runs cases sequentially (deterministic journal and cassette order) and
98
+ * aggregates. Duplicate workflow names get '#<ordinal>' suffixes so every
99
+ * result row and judge journal is unambiguous.
100
+ */
101
+ async function runEvalSuite(engine, cases, options = {}) {
102
+ const seen = /* @__PURE__ */ new Map();
103
+ const results = [];
104
+ for (const evalCase of cases) {
105
+ const base = evalCase.workflow.name;
106
+ const ordinal = seen.get(base) ?? 0;
107
+ seen.set(base, ordinal + 1);
108
+ const name = ordinal === 0 ? base : `${base}#${ordinal}`;
109
+ results.push(await runEvalCase(engine, evalCase, {
110
+ name,
111
+ ...options.budgetUsd === void 0 ? {} : { budgetUsd: options.budgetUsd },
112
+ ...options.judgeBudgetUsd === void 0 ? {} : { judgeBudgetUsd: options.judgeBudgetUsd }
113
+ }));
114
+ }
115
+ return {
116
+ results,
117
+ passRate: results.length === 0 ? 0 : results.filter((r) => r.passed).length / results.length,
118
+ totalCostUsd: results.reduce((sum, r) => sum + r.costUsd, 0),
119
+ meanLatencyMs: results.length === 0 ? 0 : results.reduce((sum, r) => sum + r.latencyMs, 0) / results.length
120
+ };
121
+ }
122
+ /**
123
+ * Runs the same case list against every cell's engine, sequentially and
124
+ * in declaration order (deterministic cassette consumption), and reports
125
+ * per-cell aggregates for side-by-side comparison.
126
+ */
127
+ async function runEvalMatrix(cells, cases, options = {}) {
128
+ const reports = [];
129
+ for (const cell of cells) {
130
+ const suite = await runEvalSuite(await cell.engine(), cases, options);
131
+ reports.push({
132
+ cell: cell.name,
133
+ passRate: suite.passRate,
134
+ totalCostUsd: suite.totalCostUsd,
135
+ meanLatencyMs: suite.meanLatencyMs,
136
+ results: suite.results
137
+ });
138
+ }
139
+ return { cells: reports };
140
+ }
141
+ function deepEqual(a, b) {
142
+ if (a === b) return true;
143
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
144
+ if (Array.isArray(a) || Array.isArray(b)) {
145
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
146
+ return a.every((item, index) => deepEqual(item, b[index]));
147
+ }
148
+ if (typeof a === "object" && typeof b === "object") {
149
+ const aKeys = Object.keys(a).sort();
150
+ const bKeys = Object.keys(b).sort();
151
+ if (aKeys.length !== bKeys.length || aKeys.some((key, index) => key !== bKeys[index])) return false;
152
+ return aKeys.every((key) => deepEqual(a[key], b[key]));
153
+ }
154
+ return false;
155
+ }
156
+ function goldenGrader(expected, options = {}) {
157
+ const name = options.name ?? "golden";
158
+ return {
159
+ name,
160
+ grade(context) {
161
+ const passed = deepEqual(context.value, expected);
162
+ return {
163
+ grader: name,
164
+ passed,
165
+ ...passed ? {} : { details: {
166
+ expected,
167
+ actual: context.value ?? null
168
+ } }
169
+ };
170
+ }
171
+ };
172
+ }
173
+ function rubricGrader(criteria, options = {}) {
174
+ const name = options.name ?? "rubric";
175
+ const threshold = options.passThreshold ?? 1;
176
+ return {
177
+ name,
178
+ grade(context) {
179
+ const rows = criteria.map((criterion) => ({
180
+ name: criterion.name,
181
+ passed: criterion.check(context.value)
182
+ }));
183
+ const score = criteria.length === 0 ? 1 : rows.filter((row) => row.passed).length / rows.length;
184
+ return {
185
+ grader: name,
186
+ passed: score >= threshold,
187
+ score,
188
+ details: { criteria: rows }
189
+ };
190
+ }
191
+ };
192
+ }
193
+ /** The default judge verdict shape. */
194
+ const JUDGE_VERDICT_SCHEMA = {
195
+ type: "object",
196
+ properties: {
197
+ passed: { type: "boolean" },
198
+ reasoning: { type: "string" }
199
+ },
200
+ required: ["passed"],
201
+ additionalProperties: false
202
+ };
203
+ function defaultToVerdict(output) {
204
+ return { passed: typeof output === "object" && output !== null && !Array.isArray(output) && output.passed === true };
205
+ }
206
+ function judgePrompt(instruction, value) {
207
+ return [
208
+ "You are an evaluation judge. Judge the candidate output below against the instruction.",
209
+ "",
210
+ `Instruction: ${instruction}`,
211
+ "",
212
+ "Candidate output (JSON):",
213
+ JSON.stringify(value ?? null),
214
+ "",
215
+ "Return a verdict object matching the response schema."
216
+ ].join("\n");
217
+ }
218
+ function judgeGrader(options) {
219
+ const name = options.name ?? "judge";
220
+ if (options.schema !== void 0 && options.toVerdict === void 0) throw new Error(`judgeGrader '${name}': a custom schema requires toVerdict`);
221
+ const toVerdict = options.toVerdict ?? defaultToVerdict;
222
+ const schema = options.schema ?? JUDGE_VERDICT_SCHEMA;
223
+ return {
224
+ name,
225
+ async grade(context) {
226
+ if (context.outcome.status !== "ok") return {
227
+ grader: name,
228
+ passed: false,
229
+ details: { skipped: `target run settled '${context.outcome.status}'` }
230
+ };
231
+ const output = await context.judge({
232
+ model: options.model,
233
+ prompt: judgePrompt(options.instruction, context.value),
234
+ schema
235
+ });
236
+ const verdict = toVerdict(output);
237
+ return {
238
+ grader: name,
239
+ passed: verdict.passed,
240
+ ...verdict.score === void 0 ? {} : { score: verdict.score },
241
+ details: { output }
242
+ };
243
+ }
244
+ };
245
+ }
246
+ /**
247
+ * The eval-committer identity (M11-T01; docs/05, sections "Data model"
248
+ * and "Commit discipline"). The pipeline-side commit path: builds
249
+ * eval-committer-gated ops (the coherence square: class eval-measured,
250
+ * author eval-pipeline, metrics present) and commits them with the
251
+ * documented CAS-rebase recipe. Humans never call this; their path is
252
+ * the human gate and it structurally cannot carry metrics.
253
+ */
254
+ /** One measured claim, TTL applied per the docs/05 decay table. */
255
+ function evalMeasuredClaim(input, committerId) {
256
+ return {
257
+ id: input.id,
258
+ subject: input.subject,
259
+ taskClass: input.taskClass,
260
+ polarity: input.polarity,
261
+ statement: input.statement,
262
+ class: "eval-measured",
263
+ status: "active",
264
+ evidence: input.evidence,
265
+ metrics: input.metrics,
266
+ confidence: input.confidence,
267
+ observedAt: input.observedAt,
268
+ expiresAt: claimExpiry("eval-measured", input.polarity, input.observedAt),
269
+ ...input.modelEpoch === void 0 ? {} : { modelEpoch: input.modelEpoch },
270
+ author: {
271
+ kind: "eval-pipeline",
272
+ id: committerId
273
+ }
274
+ };
275
+ }
276
+ /**
277
+ * Commits measured claims through the eval-committer gate with the
278
+ * documented rebase recipe: on a CAS rejection, re-read current() and
279
+ * retry against the fresh version. Returns the committed version.
280
+ */
281
+ async function commitEvalMeasured(store, claims, options) {
282
+ const gate = {
283
+ kind: "eval-committer",
284
+ committerId: options.committerId,
285
+ reportId: options.reportId
286
+ };
287
+ const ops = claims.map((input) => ({
288
+ op: "add",
289
+ claim: evalMeasuredClaim(input, options.committerId),
290
+ gate
291
+ }));
292
+ const attempts = options.attempts ?? 3;
293
+ let lastCas;
294
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
295
+ const snapshot = await store.current();
296
+ try {
297
+ return await store.commit(ops, snapshot.version);
298
+ } catch (thrown) {
299
+ if (thrown instanceof KnowledgeCasError) {
300
+ lastCas = thrown;
301
+ continue;
302
+ }
303
+ throw thrown;
304
+ }
305
+ }
306
+ throw lastCas ?? /* @__PURE__ */ new Error("commitEvalMeasured: unreachable");
307
+ }
308
+ /**
309
+ * The canary fingerprint (M11-T04; docs/05, section "Grounding and
310
+ * decay"; OQ-06). The optional compensation for silent alias
311
+ * re-pointing that modelEpoch honestly cannot catch: a FIXED probe set
312
+ * at temperature 0, run through the ordinary engine (journaled,
313
+ * budgeted, VCR-recordable), hashed over normalized outputs. A
314
+ * fingerprint change flips the model's eval claims to stale in one
315
+ * command.
316
+ *
317
+ * The committed v1 design (closing OQ-06): the probe set is CALLER
318
+ * data (fixed, versioned alongside the store); normalization is NFC,
319
+ * trim, and whitespace collapse per output; the fingerprint is the
320
+ * sha256 of the JCS-serialized normalized output array, prefixed with
321
+ * the probe count so a probe-set edit never collides with drift.
322
+ */
323
+ /** The committed v1 normalization (OQ-06): NFC, trim, collapse whitespace. */
324
+ function normalizeCanaryOutput(output) {
325
+ return (typeof output === "string" ? output : JSON.stringify(output ?? null)).normalize("NFC").trim().replace(/\s+/gu, " ");
326
+ }
327
+ /**
328
+ * Runs the fixed probe set through the ordinary engine and returns the
329
+ * fingerprint. Probes run sequentially in declaration order, one run
330
+ * per probe, so recordings replay deterministically.
331
+ */
332
+ async function canaryFingerprint(engine, probes) {
333
+ const outputs = [];
334
+ for (const [index, prompt] of probes.prompts.entries()) {
335
+ const workflow = defineWorkflow({ name: `kb-canary:${String(index)}` }, async (ctx) => await ctx.agent(prompt, { agentType: probes.agentType }));
336
+ const outcome = await engine.run(workflow, null).result;
337
+ outputs.push(outcome.status === "ok" ? normalizeCanaryOutput(outcome.value) : `!${outcome.status}`);
338
+ }
339
+ const body = JSON.stringify([probes.prompts.length, outputs]);
340
+ return createHash("sha256").update(body, "utf8").digest("hex");
341
+ }
342
+ /**
343
+ * Flips the model's ACTIVE eval-measured claims to stale when their
344
+ * recorded canary fingerprint differs from the fresh one (docs/05:
345
+ * "a fingerprint change immediately flips the model's eval claims to
346
+ * stale"). Claims without a recorded fingerprint have no baseline and
347
+ * stay untouched (the documented no-probe posture); a second run is
348
+ * an idempotent noop. CAS-rebased like every maintenance commit.
349
+ */
350
+ async function flipStaleOnCanaryDrift(store, model, freshFingerprint, options) {
351
+ const attempts = options?.attempts ?? 3;
352
+ let lastCas;
353
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
354
+ const snapshot = await store.current();
355
+ const drifted = snapshot.claims.filter((claim) => claim.status === "active" && claim.class === "eval-measured" && claim.subject.model === model && claim.modelEpoch?.canaryFingerprint !== void 0 && claim.modelEpoch.canaryFingerprint !== freshFingerprint);
356
+ if (drifted.length === 0) return {
357
+ model,
358
+ freshFingerprint,
359
+ flipped: []
360
+ };
361
+ const ops = drifted.map((claim) => ({
362
+ op: "mark_stale",
363
+ claimId: claim.id,
364
+ reason: "canary-drift"
365
+ }));
366
+ try {
367
+ const version = await store.commit(ops, snapshot.version);
368
+ return {
369
+ model,
370
+ freshFingerprint,
371
+ flipped: drifted.map((claim) => claim.id),
372
+ version
373
+ };
374
+ } catch (thrown) {
375
+ if (thrown instanceof KnowledgeCasError) {
376
+ lastCas = thrown;
377
+ continue;
378
+ }
379
+ throw thrown;
380
+ }
381
+ }
382
+ throw lastCas ?? /* @__PURE__ */ new Error("flipStaleOnCanaryDrift: unreachable");
383
+ }
384
+ const SWEEP_THRESHOLD_DEFAULTS = {
385
+ strength: .9,
386
+ weakness: .5
387
+ };
388
+ /** Deterministic claim id: report-scoped, readable, collision-free. */
389
+ function claimIdOf(reportId, member, taskClass) {
390
+ const effort = member.effort === void 0 ? "" : `@${member.effort}`;
391
+ return `${reportId}/${member.model}${effort}/${taskClass}`;
392
+ }
393
+ /** The typed statement template: never a quote from tool output. */
394
+ function statementOf(cell, polarity) {
395
+ const rate = cell.passRate.toFixed(2);
396
+ const band = polarity === "strength" ? "at or above the strength band" : "in the weakness band";
397
+ return `sweep passRate ${rate} over ${String(cell.n)} ${cell.taskClass} case${cell.n === 1 ? "" : "s"}: ${band}`;
398
+ }
399
+ /**
400
+ * Runs the fixed matrix sequentially in declaration order
401
+ * (deterministic cassette consumption), aggregates per (model,
402
+ * taskClass) cell, emits threshold-crossing claims, and commits them
403
+ * through the eval-committer identity when a store is given.
404
+ */
405
+ async function runSweepMatrix(pool, options) {
406
+ const thresholds = {
407
+ ...SWEEP_THRESHOLD_DEFAULTS,
408
+ ...options.thresholds
409
+ };
410
+ const byTaskClass = /* @__PURE__ */ new Map();
411
+ for (const entry of pool.cases) {
412
+ const bucket = byTaskClass.get(entry.taskClass) ?? [];
413
+ bucket.push(entry);
414
+ byTaskClass.set(entry.taskClass, bucket);
415
+ }
416
+ const cells = [];
417
+ const claims = [];
418
+ for (const member of pool.models) {
419
+ const engine = await options.engineFor(member);
420
+ for (const [taskClass, bucket] of byTaskClass) {
421
+ const suite = await runEvalSuite(engine, bucket.map((entry) => entry.case), options.suite ?? {});
422
+ const cell = {
423
+ model: member.model,
424
+ ...member.effort === void 0 ? {} : { effort: member.effort },
425
+ taskClass,
426
+ passRate: suite.passRate,
427
+ n: suite.results.length,
428
+ totalCostUsd: suite.totalCostUsd,
429
+ caseNames: suite.results.map((result) => result.name)
430
+ };
431
+ cells.push(cell);
432
+ const polarity = cell.passRate >= thresholds.strength ? "strength" : cell.passRate <= thresholds.weakness ? "weakness" : void 0;
433
+ if (polarity !== void 0 && cell.n > 0) {
434
+ const epoch = options.modelEpochFor?.(member);
435
+ claims.push({
436
+ id: claimIdOf(options.reportId, member, taskClass),
437
+ subject: {
438
+ model: member.model,
439
+ ...member.effort === void 0 ? {} : { effort: member.effort }
440
+ },
441
+ taskClass,
442
+ polarity,
443
+ statement: statementOf(cell, polarity),
444
+ metrics: {
445
+ passRate: cell.passRate,
446
+ n: cell.n,
447
+ graderId: "eval-suite"
448
+ },
449
+ confidence: cell.n >= 20 ? "high" : cell.n >= 5 ? "medium" : "low",
450
+ observedAt: options.observedAt,
451
+ evidence: [{
452
+ kind: "eval",
453
+ reportId: options.reportId,
454
+ caseIds: cell.caseNames
455
+ }],
456
+ ...epoch === void 0 ? {} : { modelEpoch: epoch }
457
+ });
458
+ }
459
+ }
460
+ }
461
+ const report = {
462
+ reportId: options.reportId,
463
+ observedAt: options.observedAt,
464
+ cells,
465
+ claims
466
+ };
467
+ if (options.store !== void 0 && claims.length > 0) report.committedVersion = await commitEvalMeasured(options.store, claims, {
468
+ committerId: options.committerId,
469
+ reportId: options.reportId
470
+ });
471
+ return report;
472
+ }
473
+ //#endregion
474
+ export { EvalJudgeError, JUDGE_VERDICT_SCHEMA, SWEEP_THRESHOLD_DEFAULTS, canaryFingerprint, commitEvalMeasured, evalMeasuredClaim, flipStaleOnCanaryDrift, goldenGrader, judgeGrader, normalizeCanaryOutput, rubricGrader, runEvalCase, runEvalMatrix, runEvalSuite, runSweepMatrix };