@ai-changeguard/replay 0.0.0-stage → 0.1.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/README.md +6 -2
- package/dist/fallback.d.ts +56 -0
- package/dist/fallback.js +133 -0
- package/dist/golden.d.ts +22 -0
- package/dist/golden.js +111 -0
- package/dist/importer.d.ts +39 -0
- package/dist/importer.js +606 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +16 -0
- package/dist/job.d.ts +30 -0
- package/dist/job.js +33 -0
- package/dist/openai-evals.d.ts +40 -0
- package/dist/openai-evals.js +182 -0
- package/dist/repair.d.ts +58 -0
- package/dist/repair.js +154 -0
- package/dist/report.d.ts +60 -0
- package/dist/report.js +165 -0
- package/dist/run.d.ts +36 -0
- package/dist/run.js +62 -0
- package/dist/savings.d.ts +85 -0
- package/dist/savings.js +220 -0
- package/dist/schema.d.ts +21 -0
- package/dist/schema.js +73 -0
- package/dist/similarity.d.ts +1 -0
- package/dist/similarity.js +23 -0
- package/dist/slim.d.ts +85 -0
- package/dist/slim.js +279 -0
- package/dist/starter.d.ts +34 -0
- package/dist/starter.js +78 -0
- package/dist/verdict.d.ts +36 -0
- package/dist/verdict.js +143 -0
- package/dist/watch.d.ts +86 -0
- package/dist/watch.js +198 -0
- package/package.json +49 -4
package/dist/verdict.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { extractJson, validateSchema } from "./schema.js";
|
|
2
|
+
import { similarity } from "./similarity.js";
|
|
3
|
+
const average = (values) => (values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0);
|
|
4
|
+
const atLeast = (n, fraction) => Math.max(1, Math.ceil(n * fraction));
|
|
5
|
+
const count = (responses, test) => responses.filter(test).length;
|
|
6
|
+
function sideStats(records) {
|
|
7
|
+
const ok = records.flatMap((r) => (r.response ? [r.response] : []));
|
|
8
|
+
return {
|
|
9
|
+
runs: records.length,
|
|
10
|
+
errors: records.length - ok.length,
|
|
11
|
+
avgInputTokens: average(ok.map((r) => r.inputTokens)),
|
|
12
|
+
avgOutputTokens: average(ok.map((r) => r.outputTokens)),
|
|
13
|
+
avgLatencyMs: average(ok.map((r) => r.latencyMs)),
|
|
14
|
+
avgChars: average(ok.map((r) => r.text.length)),
|
|
15
|
+
servedModels: [...new Set(ok.flatMap((r) => (r.servedModel ? [r.servedModel] : [])))],
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function mostCommon(values) {
|
|
19
|
+
const counts = new Map();
|
|
20
|
+
for (const v of values)
|
|
21
|
+
counts.set(v, (counts.get(v) ?? 0) + 1);
|
|
22
|
+
let best = { value: "", share: 0 };
|
|
23
|
+
for (const [value, n] of counts)
|
|
24
|
+
if (n / values.length > best.share)
|
|
25
|
+
best = { value, share: n / values.length };
|
|
26
|
+
return best;
|
|
27
|
+
}
|
|
28
|
+
function missingRequiredArg(item, call) {
|
|
29
|
+
const required = item.tools?.find((t) => t.name === call.name)?.parameters.required;
|
|
30
|
+
if (!Array.isArray(required))
|
|
31
|
+
return false;
|
|
32
|
+
return required.some((key) => typeof key === "string" && !(key in call.arguments));
|
|
33
|
+
}
|
|
34
|
+
function firstError(records) {
|
|
35
|
+
return records.find((r) => r.error)?.error ?? "no runs";
|
|
36
|
+
}
|
|
37
|
+
export function judgeItem(item, records, options = {}) {
|
|
38
|
+
const share = options.share ?? 0.4;
|
|
39
|
+
const oldRecords = records.filter((r) => r.itemId === item.id && r.side === "old");
|
|
40
|
+
const newRecords = records.filter((r) => r.itemId === item.id && r.side === "new");
|
|
41
|
+
const oldOk = oldRecords.flatMap((r) => (r.response ? [r.response] : []));
|
|
42
|
+
const newOk = newRecords.flatMap((r) => (r.response ? [r.response] : []));
|
|
43
|
+
const result = { id: item.id, verdict: "same", reasons: [], old: sideStats(oldRecords), new: sideStats(newRecords) };
|
|
44
|
+
if (oldOk[0])
|
|
45
|
+
result.sampleOld = oldOk[0].text;
|
|
46
|
+
if (newOk[0])
|
|
47
|
+
result.sampleNew = newOk[0].text;
|
|
48
|
+
const add = (code, severity, detail) => result.reasons.push({ code, severity, detail });
|
|
49
|
+
if (oldOk.length === 0) {
|
|
50
|
+
result.verdict = "error";
|
|
51
|
+
const oldError = firstError(oldRecords);
|
|
52
|
+
const newStatus = newOk.length > 0
|
|
53
|
+
? `The new model answered ${newOk.length} of ${newRecords.length} times.`
|
|
54
|
+
: firstError(newRecords) === oldError
|
|
55
|
+
? "The new model failed the same way."
|
|
56
|
+
: `The new model failed too: ${firstError(newRecords)}`;
|
|
57
|
+
result.error = `The old model never answered: ${oldError} — ${newStatus}`;
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
if (newOk.length === 0) {
|
|
61
|
+
add("calls-failing", "broken", `All ${newRecords.length} calls to the new model failed: ${firstError(newRecords)}`);
|
|
62
|
+
result.verdict = "broken";
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
const newErrors = newRecords.length - newOk.length;
|
|
66
|
+
if (newErrors >= atLeast(newRecords.length, share)) {
|
|
67
|
+
add("calls-failing", "broken", `${newErrors} of ${newRecords.length} calls to the new model failed: ${firstError(newRecords)}`);
|
|
68
|
+
}
|
|
69
|
+
const threshold = atLeast(newOk.length, share);
|
|
70
|
+
const expect = item.expect;
|
|
71
|
+
if (expect?.json || expect?.schema) {
|
|
72
|
+
const problem = (r) => {
|
|
73
|
+
const parsed = extractJson(r.text);
|
|
74
|
+
if (!parsed.ok)
|
|
75
|
+
return "not valid JSON";
|
|
76
|
+
return expect.schema ? (validateSchema(parsed.value, expect.schema)[0] ?? null) : null;
|
|
77
|
+
};
|
|
78
|
+
const newBad = count(newOk, (r) => problem(r) !== null);
|
|
79
|
+
const oldBad = count(oldOk, (r) => problem(r) !== null);
|
|
80
|
+
if (newBad >= threshold && newBad > oldBad) {
|
|
81
|
+
const example = newOk.map(problem).find((p) => p !== null);
|
|
82
|
+
add("format-broken", "broken", `${newBad} of ${newOk.length} new answers fail the expected ${expect.schema ? "JSON schema" : "JSON format"} (old: ${oldBad} of ${oldOk.length}). First problem: ${example}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (expect?.tool) {
|
|
86
|
+
const wrong = (r) => !r.toolCalls.some((c) => c.name === expect.tool);
|
|
87
|
+
const newWrong = count(newOk, wrong);
|
|
88
|
+
const oldWrong = count(oldOk, wrong);
|
|
89
|
+
if (newWrong >= threshold && newWrong > oldWrong) {
|
|
90
|
+
add("tool-change", "broken", `${newWrong} of ${newOk.length} new answers don't call ${expect.tool} (old: ${oldWrong} of ${oldOk.length})`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
else if (item.tools?.length) {
|
|
94
|
+
const firstTool = (r) => r.toolCalls[0]?.name ?? "no tool";
|
|
95
|
+
const oldMode = mostCommon(oldOk.map(firstTool));
|
|
96
|
+
const newMode = mostCommon(newOk.map(firstTool));
|
|
97
|
+
if (oldMode.share >= 0.6 && newMode.share >= 0.6 && oldMode.value !== newMode.value) {
|
|
98
|
+
add("tool-change", "broken", `The old model called ${oldMode.value}; the new one calls ${newMode.value}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (item.tools?.length) {
|
|
102
|
+
const missing = (r) => r.toolCalls.some((c) => missingRequiredArg(item, c));
|
|
103
|
+
const newMissing = count(newOk, missing);
|
|
104
|
+
const oldMissing = count(oldOk, missing);
|
|
105
|
+
if (newMissing >= threshold && newMissing > oldMissing) {
|
|
106
|
+
add("tool-args-missing", "broken", `${newMissing} of ${newOk.length} new tool calls miss a required argument (old: ${oldMissing} of ${oldOk.length})`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (expect?.contains?.length) {
|
|
110
|
+
const wanted = expect.contains;
|
|
111
|
+
const lacks = (r) => wanted.some((s) => !r.text.toLowerCase().includes(s.toLowerCase()));
|
|
112
|
+
const newLacks = count(newOk, lacks);
|
|
113
|
+
const oldLacks = count(oldOk, lacks);
|
|
114
|
+
if (newLacks >= threshold && newLacks > oldLacks) {
|
|
115
|
+
add("missing-text", "broken", `${newLacks} of ${newOk.length} new answers miss required text: ${wanted.join(", ")} (old: ${oldLacks} of ${oldOk.length})`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const newRefusals = count(newOk, (r) => r.refused);
|
|
119
|
+
const oldRefusals = count(oldOk, (r) => r.refused);
|
|
120
|
+
const refusalChange = newRefusals >= atLeast(newOk.length, 0.6) && oldRefusals <= Math.floor(oldOk.length * 0.2);
|
|
121
|
+
if (refusalChange) {
|
|
122
|
+
add("new-refusal", "changed", `The new model refused ${newRefusals} of ${newOk.length} times (old: ${oldRefusals} of ${oldOk.length})`);
|
|
123
|
+
}
|
|
124
|
+
const oldTexts = oldOk.map((r) => r.text).filter((t) => t.trim());
|
|
125
|
+
const newTexts = newOk.map((r) => r.text).filter((t) => t.trim());
|
|
126
|
+
// Drift needs at least two old answers: they show how much the old model varies by itself.
|
|
127
|
+
// With one, any rewording would look like drift.
|
|
128
|
+
if (!refusalChange && oldTexts.length > 1 && newTexts.length > 0) {
|
|
129
|
+
const pairs = [];
|
|
130
|
+
for (let i = 0; i < oldTexts.length; i++) {
|
|
131
|
+
for (let j = i + 1; j < oldTexts.length; j++)
|
|
132
|
+
pairs.push(similarity(oldTexts[i], oldTexts[j]));
|
|
133
|
+
}
|
|
134
|
+
const oldSelf = average(pairs);
|
|
135
|
+
const cross = newTexts.map((t) => Math.max(...oldTexts.map((o) => similarity(t, o))));
|
|
136
|
+
const drifted = cross.filter((c) => c < oldSelf * 0.7).length;
|
|
137
|
+
if (drifted >= atLeast(newTexts.length, 0.6)) {
|
|
138
|
+
add("answer-drift", "changed", `${drifted} of ${newTexts.length} new answers read differently from the old ones (word overlap ${average(cross).toFixed(2)} vs ${oldSelf.toFixed(2)} between old answers; approximate)`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
result.verdict = result.reasons.some((r) => r.severity === "broken") ? "broken" : result.reasons.length > 0 ? "changed" : "same";
|
|
142
|
+
return result;
|
|
143
|
+
}
|
package/dist/watch.d.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { LlmClient, LlmResponse } from "@ai-changeguard/llm";
|
|
2
|
+
import type { GoldenItem } from "./golden.js";
|
|
3
|
+
import { type ReplayReport } from "./report.js";
|
|
4
|
+
/**
|
|
5
|
+
* Nightly watch: is the model you already use still answering your prompts the way it did?
|
|
6
|
+
* A baseline stores N answers per prompt from one run. Each watch run asks the same model again
|
|
7
|
+
* and judges the fresh answers against the stored ones with the replay's verdict rules, at a
|
|
8
|
+
* stricter threshold (3 of 5) so one odd answer never raises an alarm. It also notices when the
|
|
9
|
+
* provider serves a different model than the one requested, or a different snapshot than before.
|
|
10
|
+
*/
|
|
11
|
+
export declare const BASELINE_VERSION = 1;
|
|
12
|
+
export declare const WATCH_SHARE = 0.6;
|
|
13
|
+
export interface BaselineRecord {
|
|
14
|
+
itemId: string;
|
|
15
|
+
run: number;
|
|
16
|
+
response?: LlmResponse;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface Baseline {
|
|
20
|
+
version: number;
|
|
21
|
+
model: string;
|
|
22
|
+
createdAt: string;
|
|
23
|
+
runs: number;
|
|
24
|
+
/** One entry per prompt, with a hash of its request, so an edited prompt is not compared to old answers. */
|
|
25
|
+
items: {
|
|
26
|
+
id: string;
|
|
27
|
+
hash: string;
|
|
28
|
+
}[];
|
|
29
|
+
records: BaselineRecord[];
|
|
30
|
+
}
|
|
31
|
+
export interface WatchReport {
|
|
32
|
+
model: string;
|
|
33
|
+
baselineCreatedAt: string;
|
|
34
|
+
report: ReplayReport;
|
|
35
|
+
/** The provider served another model than the one requested. */
|
|
36
|
+
reroutes: {
|
|
37
|
+
requested: string;
|
|
38
|
+
served: string;
|
|
39
|
+
}[];
|
|
40
|
+
/** Model versions the API reported, at baseline time and now (a changed snapshot behind an alias). */
|
|
41
|
+
servedBefore: string[];
|
|
42
|
+
servedNow: string[];
|
|
43
|
+
/** The API now reports a model version it did not report at baseline time. */
|
|
44
|
+
snapshotChanged: boolean;
|
|
45
|
+
/** Prompts with no usable baseline: new, or edited since the baseline was made. */
|
|
46
|
+
notInBaseline: string[];
|
|
47
|
+
/** Something changed that deserves a person's attention. */
|
|
48
|
+
alert: boolean;
|
|
49
|
+
}
|
|
50
|
+
/** Fingerprint of what is sent to the model (not the id or the checks). */
|
|
51
|
+
export declare function itemHash(item: GoldenItem): string;
|
|
52
|
+
export interface BaselineOptions {
|
|
53
|
+
items: GoldenItem[];
|
|
54
|
+
model: string;
|
|
55
|
+
client: LlmClient;
|
|
56
|
+
runs?: number;
|
|
57
|
+
concurrency?: number;
|
|
58
|
+
maxCalls?: number;
|
|
59
|
+
now?: Date;
|
|
60
|
+
signal?: AbortSignal;
|
|
61
|
+
onProgress?: (done: number, total: number) => void;
|
|
62
|
+
}
|
|
63
|
+
/** Runs every prompt `runs` times on `model` and keeps the answers as the reference. */
|
|
64
|
+
export declare function createBaseline(options: BaselineOptions): Promise<Baseline>;
|
|
65
|
+
export declare function parseBaseline(text: string): Baseline;
|
|
66
|
+
export interface WatchOptions {
|
|
67
|
+
items: GoldenItem[];
|
|
68
|
+
baseline: Baseline;
|
|
69
|
+
client: LlmClient;
|
|
70
|
+
runs?: number;
|
|
71
|
+
concurrency?: number;
|
|
72
|
+
maxCalls?: number;
|
|
73
|
+
signal?: AbortSignal;
|
|
74
|
+
onProgress?: (done: number, total: number) => void;
|
|
75
|
+
}
|
|
76
|
+
export declare function runWatch(options: WatchOptions): Promise<WatchReport>;
|
|
77
|
+
export declare function formatWatchText(w: WatchReport): string;
|
|
78
|
+
export declare function formatWatchMarkdown(w: WatchReport): string;
|
|
79
|
+
/** Slack incoming-webhook message: counts and prompt ids only, never prompt or answer text. */
|
|
80
|
+
export declare function slackMessage(w: WatchReport, link?: string): {
|
|
81
|
+
text: string;
|
|
82
|
+
};
|
|
83
|
+
/** Posts to a Slack incoming webhook. Only https URLs; the URL is a secret and is never logged. */
|
|
84
|
+
export declare function postSlack(webhookUrl: string, message: {
|
|
85
|
+
text: string;
|
|
86
|
+
}, fetchImpl?: typeof fetch): Promise<void>;
|
package/dist/watch.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { buildReplayReport, isReroute, modelName } from "./report.js";
|
|
3
|
+
import { runReplay } from "./run.js";
|
|
4
|
+
/**
|
|
5
|
+
* Nightly watch: is the model you already use still answering your prompts the way it did?
|
|
6
|
+
* A baseline stores N answers per prompt from one run. Each watch run asks the same model again
|
|
7
|
+
* and judges the fresh answers against the stored ones with the replay's verdict rules, at a
|
|
8
|
+
* stricter threshold (3 of 5) so one odd answer never raises an alarm. It also notices when the
|
|
9
|
+
* provider serves a different model than the one requested, or a different snapshot than before.
|
|
10
|
+
*/
|
|
11
|
+
export const BASELINE_VERSION = 1;
|
|
12
|
+
/** Answers longer than this are cut, on both sides alike, so a long JSON answer is judged fairly. */
|
|
13
|
+
const MAX_TEXT = 32_000;
|
|
14
|
+
export const WATCH_SHARE = 0.6;
|
|
15
|
+
/** JSON with sorted keys, so re-saving a golden set with keys in another order changes nothing. */
|
|
16
|
+
function stable(value) {
|
|
17
|
+
if (Array.isArray(value))
|
|
18
|
+
return `[${value.map(stable).join(",")}]`;
|
|
19
|
+
if (value && typeof value === "object") {
|
|
20
|
+
return `{${Object.keys(value)
|
|
21
|
+
.sort()
|
|
22
|
+
.map((k) => `${JSON.stringify(k)}:${stable(value[k])}`)
|
|
23
|
+
.join(",")}}`;
|
|
24
|
+
}
|
|
25
|
+
return JSON.stringify(value) ?? "null";
|
|
26
|
+
}
|
|
27
|
+
/** Fingerprint of what is sent to the model (not the id or the checks). */
|
|
28
|
+
export function itemHash(item) {
|
|
29
|
+
const request = { system: item.system, messages: item.messages, tools: item.tools, maxTokens: item.maxTokens, temperature: item.temperature, jsonMode: item.jsonMode };
|
|
30
|
+
return createHash("sha256").update(stable(request)).digest("hex").slice(0, 16);
|
|
31
|
+
}
|
|
32
|
+
function trimmed(response) {
|
|
33
|
+
return response.text.length > MAX_TEXT ? { ...response, text: response.text.slice(0, MAX_TEXT) } : response;
|
|
34
|
+
}
|
|
35
|
+
/** Runs every prompt `runs` times on `model` and keeps the answers as the reference. */
|
|
36
|
+
export async function createBaseline(options) {
|
|
37
|
+
const runs = options.runs ?? 5;
|
|
38
|
+
const records = await runReplay({
|
|
39
|
+
items: options.items,
|
|
40
|
+
oldModel: options.model,
|
|
41
|
+
newModel: options.model,
|
|
42
|
+
runs,
|
|
43
|
+
client: options.client,
|
|
44
|
+
sides: ["new"],
|
|
45
|
+
...(options.concurrency ? { concurrency: options.concurrency } : {}),
|
|
46
|
+
...(options.maxCalls ? { maxCalls: options.maxCalls } : {}),
|
|
47
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
48
|
+
...(options.onProgress ? { onProgress: options.onProgress } : {}),
|
|
49
|
+
});
|
|
50
|
+
// Every prompt needs answers, or it could never be watched.
|
|
51
|
+
const empty = options.items.filter((i) => !records.some((r) => r.itemId === i.id && r.response)).map((i) => i.id);
|
|
52
|
+
if (empty.length > 0) {
|
|
53
|
+
const error = records.find((r) => empty.includes(r.itemId))?.error ?? "";
|
|
54
|
+
throw new Error(`No answers for ${empty.join(", ")} (${error}). If this is a rate limit, try again with a lower --concurrency.`);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
version: BASELINE_VERSION,
|
|
58
|
+
model: options.model,
|
|
59
|
+
createdAt: (options.now ?? new Date()).toISOString(),
|
|
60
|
+
runs,
|
|
61
|
+
items: options.items.map((i) => ({ id: i.id, hash: itemHash(i) })),
|
|
62
|
+
records: records.map((r) => ({ itemId: r.itemId, run: r.run, ...(r.response ? { response: trimmed(r.response) } : { error: r.error ?? "failed" }) })),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
export function parseBaseline(text) {
|
|
66
|
+
let data;
|
|
67
|
+
try {
|
|
68
|
+
data = JSON.parse(text);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
throw new Error("The baseline file is not valid JSON.");
|
|
72
|
+
}
|
|
73
|
+
if (data?.version !== BASELINE_VERSION || typeof data.model !== "string" || !Array.isArray(data.records) || !Array.isArray(data.items)) {
|
|
74
|
+
throw new Error("This is not an AI Change Guard baseline file (or it was made by a newer version).");
|
|
75
|
+
}
|
|
76
|
+
return data;
|
|
77
|
+
}
|
|
78
|
+
export async function runWatch(options) {
|
|
79
|
+
const { baseline } = options;
|
|
80
|
+
const known = new Map(baseline.items.map((i) => [i.id, i.hash]));
|
|
81
|
+
const watched = options.items.filter((i) => known.get(i.id) === itemHash(i));
|
|
82
|
+
const notInBaseline = options.items.filter((i) => known.get(i.id) !== itemHash(i)).map((i) => i.id);
|
|
83
|
+
if (watched.length === 0)
|
|
84
|
+
throw new Error("None of these prompts match the baseline. Make a new baseline for this golden set.");
|
|
85
|
+
const runs = options.runs ?? baseline.runs;
|
|
86
|
+
const live = await runReplay({
|
|
87
|
+
items: watched,
|
|
88
|
+
oldModel: baseline.model,
|
|
89
|
+
newModel: baseline.model,
|
|
90
|
+
runs,
|
|
91
|
+
client: options.client,
|
|
92
|
+
sides: ["new"],
|
|
93
|
+
...(options.concurrency ? { concurrency: options.concurrency } : {}),
|
|
94
|
+
...(options.maxCalls ? { maxCalls: options.maxCalls } : {}),
|
|
95
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
96
|
+
...(options.onProgress ? { onProgress: options.onProgress } : {}),
|
|
97
|
+
});
|
|
98
|
+
// Cut fresh answers exactly like the stored ones, so both sides are judged alike.
|
|
99
|
+
for (const r of live)
|
|
100
|
+
if (r.response)
|
|
101
|
+
r.response = trimmed(r.response);
|
|
102
|
+
const ids = new Set(watched.map((i) => i.id));
|
|
103
|
+
const stored = baseline.records
|
|
104
|
+
.filter((r) => ids.has(r.itemId))
|
|
105
|
+
.map((r) => ({ itemId: r.itemId, side: "old", run: r.run, ...(r.response ? { response: r.response } : { error: r.error ?? "failed" }) }));
|
|
106
|
+
const report = buildReplayReport(watched, [...stored, ...live], { oldModel: baseline.model, newModel: baseline.model, runs, judge: { share: WATCH_SHARE } });
|
|
107
|
+
const served = (records) => [...new Set(records.flatMap((r) => (r.response?.servedModel ? [r.response.servedModel] : [])))].sort();
|
|
108
|
+
const servedBefore = served(stored);
|
|
109
|
+
const servedNow = served(live);
|
|
110
|
+
const requested = modelName(baseline.model);
|
|
111
|
+
// Only what is new since the baseline counts: an alias the provider always served under another
|
|
112
|
+
// name (claude-...-latest, gemini-flash-latest) is not a change.
|
|
113
|
+
const isNew = (s) => !servedBefore.includes(s);
|
|
114
|
+
const reroutes = servedNow.filter((s) => isNew(s) && isReroute(requested, s)).map((s) => ({ requested, served: s }));
|
|
115
|
+
const snapshotChanged = servedBefore.length > 0 && servedNow.some(isNew);
|
|
116
|
+
// "error" means a prompt could not be compared at all; an unwatched prompt must not stay silent.
|
|
117
|
+
const alert = report.totals.broken + report.totals.changed + report.totals.error > 0 || reroutes.length > 0 || snapshotChanged;
|
|
118
|
+
return { model: baseline.model, baselineCreatedAt: baseline.createdAt, report, reroutes, servedBefore, servedNow, snapshotChanged, notInBaseline, alert };
|
|
119
|
+
}
|
|
120
|
+
function headline(w) {
|
|
121
|
+
const t = w.report.totals;
|
|
122
|
+
const n = w.report.items.length;
|
|
123
|
+
if (!w.alert)
|
|
124
|
+
return `No change: ${n} prompt${n === 1 ? "" : "s"} on ${w.model} still answer like the baseline of ${w.baselineCreatedAt.slice(0, 10)}.`;
|
|
125
|
+
const parts = [];
|
|
126
|
+
if (t.broken)
|
|
127
|
+
parts.push(`${t.broken} broken`);
|
|
128
|
+
if (t.changed)
|
|
129
|
+
parts.push(`${t.changed} changed`);
|
|
130
|
+
if (t.error)
|
|
131
|
+
parts.push(`${t.error} could not be compared`);
|
|
132
|
+
if (w.reroutes.length)
|
|
133
|
+
parts.push(`rerouted to ${w.reroutes.map((r) => r.served).join(", ")}`);
|
|
134
|
+
if (w.snapshotChanged)
|
|
135
|
+
parts.push(`now served by ${w.servedNow.join(", ")} (was ${w.servedBefore.join(", ")})`);
|
|
136
|
+
return `${w.model} changed since the baseline of ${w.baselineCreatedAt.slice(0, 10)}: ${parts.join(", ")}.`;
|
|
137
|
+
}
|
|
138
|
+
export function formatWatchText(w) {
|
|
139
|
+
const lines = [`AI Change Guard watch · ${w.model}`, headline(w)];
|
|
140
|
+
for (const item of w.report.items) {
|
|
141
|
+
if (item.verdict === "same")
|
|
142
|
+
continue;
|
|
143
|
+
lines.push(` ${item.verdict.toUpperCase()} ${item.id}`);
|
|
144
|
+
for (const r of item.reasons)
|
|
145
|
+
lines.push(` ${r.code}: ${r.detail}`);
|
|
146
|
+
if (item.error)
|
|
147
|
+
lines.push(` ${item.error}`);
|
|
148
|
+
}
|
|
149
|
+
if (w.notInBaseline.length)
|
|
150
|
+
lines.push(`Not watched (new or edited since the baseline; make a new baseline to include them): ${w.notInBaseline.join(", ")}`);
|
|
151
|
+
return lines.join("\n");
|
|
152
|
+
}
|
|
153
|
+
export function formatWatchMarkdown(w) {
|
|
154
|
+
const t = w.report.totals;
|
|
155
|
+
const lines = [
|
|
156
|
+
`## ${w.alert ? "AI model watch: change detected" : "AI model watch: no change"}`,
|
|
157
|
+
"",
|
|
158
|
+
headline(w),
|
|
159
|
+
"",
|
|
160
|
+
"| Same | Changed | Broken | Could not compare |",
|
|
161
|
+
"| ---: | ---: | ---: | ---: |",
|
|
162
|
+
`| ${t.same} | ${t.changed} | ${t.broken} | ${t.error} |`,
|
|
163
|
+
];
|
|
164
|
+
const changed = w.report.items.filter((i) => i.verdict !== "same");
|
|
165
|
+
if (changed.length) {
|
|
166
|
+
lines.push("", "| Prompt | Verdict | Why |", "| --- | --- | --- |");
|
|
167
|
+
for (const i of changed) {
|
|
168
|
+
const why = (i.reasons.map((r) => r.detail).join("; ") || i.error || "").replace(/\s+/g, " ").replace(/\|/g, "\\|");
|
|
169
|
+
lines.push(`| ${i.id.replace(/\|/g, "\\|")} | ${i.verdict} | ${why} |`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (w.servedNow.length)
|
|
173
|
+
lines.push("", `Served by: ${w.servedNow.join(", ")}${w.servedBefore.length ? ` (at baseline: ${w.servedBefore.join(", ")})` : ""}.`);
|
|
174
|
+
if (w.notInBaseline.length)
|
|
175
|
+
lines.push("", `Not watched (new or edited since the baseline): ${w.notInBaseline.join(", ")}.`);
|
|
176
|
+
return lines.join("\n");
|
|
177
|
+
}
|
|
178
|
+
/** Slack incoming-webhook message: counts and prompt ids only, never prompt or answer text. */
|
|
179
|
+
export function slackMessage(w, link) {
|
|
180
|
+
const ids = w.report.items.filter((i) => i.verdict === "broken" || i.verdict === "changed").map((i) => `${i.id} (${i.verdict})`);
|
|
181
|
+
const text = [`:rotating_light: ${headline(w)}`, ids.length ? `Prompts: ${ids.slice(0, 20).join(", ")}${ids.length > 20 ? ", …" : ""}` : "", link ? `Details: ${link}` : ""]
|
|
182
|
+
.filter(Boolean)
|
|
183
|
+
.join("\n");
|
|
184
|
+
return { text };
|
|
185
|
+
}
|
|
186
|
+
/** Posts to a Slack incoming webhook. Only https URLs; the URL is a secret and is never logged. */
|
|
187
|
+
export async function postSlack(webhookUrl, message, fetchImpl = fetch) {
|
|
188
|
+
if (!/^https:\/\//.test(webhookUrl))
|
|
189
|
+
throw new Error("The Slack webhook must be an https URL.");
|
|
190
|
+
const res = await fetchImpl(webhookUrl, {
|
|
191
|
+
method: "POST",
|
|
192
|
+
headers: { "Content-Type": "application/json" },
|
|
193
|
+
body: JSON.stringify(message),
|
|
194
|
+
signal: AbortSignal.timeout(10_000),
|
|
195
|
+
});
|
|
196
|
+
if (!res.ok)
|
|
197
|
+
throw new Error(`Slack answered ${res.status}.`);
|
|
198
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-changeguard/replay",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Replays real prompts on an old and a new AI model and reports what changed.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"ai",
|
|
8
|
+
"llm",
|
|
9
|
+
"openai",
|
|
10
|
+
"anthropic",
|
|
11
|
+
"gemini",
|
|
12
|
+
"model-deprecation",
|
|
13
|
+
"migration"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/Navin-kumar0007/ai-change-guard-cli#readme",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/Navin-kumar0007/ai-change-guard-cli.git",
|
|
19
|
+
"directory": "packages/replay"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/Navin-kumar0007/ai-change-guard-cli/issues"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=20"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"type": "module",
|
|
31
|
+
"main": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"exports": {
|
|
34
|
+
".": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"default": "./dist/index.js"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"!dist/.tsbuildinfo"
|
|
42
|
+
],
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsc -b",
|
|
45
|
+
"prepublishOnly": "npm run build"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@ai-changeguard/llm": "0.1.0",
|
|
49
|
+
"@ai-changeguard/catalog": "0.1.0"
|
|
50
|
+
}
|
|
51
|
+
}
|