Scripts and docs
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
1 parent
9b5f7776a6
commit
8923ba95f9
5 files changed
+1121
No files matched your search
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Seeded semantic-conflict fixtures: hand-made pairs of concurrent edits whose correct outcome
|
||||
* is known. The detection half is deterministic and is asserted here directly. The resolution
|
||||
* half needs a model, so it runs in two steps that work with any model, with or without an API key:
|
||||
*
|
||||
* tsx scripts/fixtures.ts render DIR write the exact prompts the app would send, as DIR/<name>.prompt.txt
|
||||
* tsx scripts/fixtures.ts check DIR read DIR/<name>.response.json, apply it through the app's
|
||||
* own code path, and check the result against what is known
|
||||
*/
|
||||
import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { Doc, setPeerSource, type NodeId } from "../src/core/model";
|
||||
import { mergeBranch, verifyHistory, type MergeReport } from "../src/core/repo";
|
||||
import { resolveConflicts, scanContradictions } from "../src/llm/tasks";
|
||||
import type { JsonReq, LLM } from "../src/llm/types";
|
||||
|
||||
interface Fixture {
|
||||
name: string;
|
||||
about: string;
|
||||
build(): { doc: Doc; other: Doc; ids: Record<string, NodeId> };
|
||||
/** What the structural merge must report, before any model is involved. */
|
||||
detect(report: MergeReport, doc: Doc): string[];
|
||||
/** What must be true once the model's answer has been applied. Returns failures. */
|
||||
check(doc: Doc, ids: Record<string, NodeId>): string[];
|
||||
}
|
||||
|
||||
function base() {
|
||||
const doc = Doc.create("alice", "Infinispand", "A document that expands without limit.");
|
||||
const root = doc.snap().root;
|
||||
const { created } = doc.apply(
|
||||
[
|
||||
{ op: "create", parent: root, title: "Latency budget", body: "Pre-generated expansions must paint within 50 ms of the keypress. Generated expansions must show a first token within one second." },
|
||||
{ op: "create", parent: root, title: "Undo", body: "Every edit is a commit and can be undone." },
|
||||
{ op: "create", parent: root, title: "Sidenotes", body: "A note of one to three sentences is shown in the margin beside the line it is about." },
|
||||
{ op: "create", parent: root, title: "Speculation", body: "With speculation on, the expansion of the focused sentence starts before it is asked for." },
|
||||
{ op: "create", parent: root, title: "Hoisting", body: "Any node can be hoisted to fill the page." },
|
||||
{ op: "bless", id: root },
|
||||
],
|
||||
"Base",
|
||||
{ actor: "llm" },
|
||||
);
|
||||
const [latency, undo, sidenotes, speculation, hoisting] = created;
|
||||
return { doc, ids: { root, latency, undo, sidenotes, speculation, hoisting } };
|
||||
}
|
||||
|
||||
const has = (text: string, ...needles: (string | RegExp)[]) => needles.every((n) => (typeof n === "string" ? text.toLowerCase().includes(n.toLowerCase()) : n.test(text)));
|
||||
|
||||
const fixtures: Fixture[] = [
|
||||
{
|
||||
name: "compatible-additions",
|
||||
about: "Both sides added a different, compatible clause to the same sentence. The right answer keeps both.",
|
||||
build() {
|
||||
const { doc, ids } = base();
|
||||
const other = doc.fork("bob");
|
||||
doc.apply([{ op: "update", id: ids.sidenotes, body: "A note of one to three sentences is shown in the margin beside the line it is about, and is pushed down if it would overlap the note above it." }], "A: overlap rule");
|
||||
other.apply([{ op: "update", id: ids.sidenotes, body: "A note of one to three sentences is shown in the margin beside the line it is about; on screens too narrow for a margin it is set into the column instead." }], "B: narrow screens");
|
||||
return { doc, other, ids };
|
||||
},
|
||||
detect: (r) => (r.conflicts.length === 1 && r.conflicts[0].type === "edit-edit" ? [] : [`expected one edit-edit conflict, got ${JSON.stringify(r.conflicts.map((c) => c.type))}`]),
|
||||
check(doc, ids) {
|
||||
const body = doc.snap().nodes[ids.sidenotes].body;
|
||||
const out: string[] = [];
|
||||
if (!has(body, "overlap")) out.push("lost side A's overlap rule");
|
||||
if (!has(body, "narrow")) out.push("lost side B's narrow-screen rule");
|
||||
if (!has(body, "margin")) out.push("lost the original claim");
|
||||
return out;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "incompatible-numbers",
|
||||
about: "The two sides give different numbers for the same budget. They cannot be blended; the rest of the document says 50 ms.",
|
||||
build() {
|
||||
const { doc, ids } = base();
|
||||
// Elsewhere in the document, the 50 ms figure is relied on. This is what should decide it.
|
||||
doc.apply([{ op: "create", parent: ids.root, title: "How we know it works", body: "A scripted keyboard run measures keypress to paint and fails if the 95th percentile exceeds the 50 ms budget." }], "Verification", { actor: "llm" });
|
||||
const other = doc.fork("bob");
|
||||
doc.apply([{ op: "update", id: ids.latency, body: "Pre-generated expansions must paint within 50 ms of the keypress, measured at the 95th percentile. Generated expansions must show a first token within one second." }], "A: percentile");
|
||||
other.apply([{ op: "update", id: ids.latency, body: "Pre-generated expansions must paint within 200 ms of the keypress. Generated expansions must show a first token within one second." }], "B: relax to 200");
|
||||
return { doc, other, ids };
|
||||
},
|
||||
detect: (r) => (r.conflicts.length === 1 && r.conflicts[0].type === "edit-edit" ? [] : ["expected one edit-edit conflict"]),
|
||||
check(doc, ids) {
|
||||
const body = doc.snap().nodes[ids.latency].body;
|
||||
const c = doc.conflicts()[0];
|
||||
const out: string[] = [];
|
||||
if (!has(body, "50 ms")) out.push("did not keep the 50 ms budget the rest of the document relies on");
|
||||
if (has(body, "200")) out.push("kept or blended in the contradicting 200 ms figure");
|
||||
if (/(\d+)\s*[-–]\s*(\d+)\s*ms|between 50 and 200/i.test(body)) out.push("blended the two numbers into a range neither side wrote");
|
||||
if (!c.rationale || c.rationale.length < 20) out.push("gave no usable rationale for a human to overrule");
|
||||
return out;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "edit-vs-delete",
|
||||
about: "One side deleted a section; the other had just rewritten it with substantial new content. The edit should come back.",
|
||||
build() {
|
||||
const { doc, ids } = base();
|
||||
const other = doc.fork("bob");
|
||||
doc.apply([{ op: "delete", id: ids.speculation }], "A: delete speculation");
|
||||
other.apply([{ op: "update", id: ids.speculation, body: "With speculation on, the expansion of the focused sentence starts 350 ms after focus settles, before it is asked for. If the reader then presses e, the stream already in flight is adopted, so the first words appear at once. It is off by default because it spends tokens on expansions that may never be read." }], "B: explain speculation");
|
||||
return { doc, other, ids };
|
||||
},
|
||||
detect: (r, doc) => {
|
||||
const out: string[] = [];
|
||||
if (r.conflicts.length !== 1 || r.conflicts[0].type !== "edit-delete") out.push("expected one edit-delete conflict");
|
||||
if (Object.values(doc.snap().nodes).some((n) => n.title === "Speculation")) out.push("the structural merge should let the deletion win");
|
||||
return out;
|
||||
},
|
||||
check(doc) {
|
||||
const restored = Object.values(doc.snap().nodes).find((n) => n.title === "Speculation");
|
||||
if (!restored) return ["let the deletion stand, discarding the other side's new work"];
|
||||
return has(restored.body, "350") ? [] : ["restored the section but lost the new content"];
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "cross-node-contradiction",
|
||||
about: "The edits touch different nodes, so the merge is clean, but one side's new claim contradicts the other's. A second pair of edits is unrelated and must not be reported.",
|
||||
build() {
|
||||
const { doc, ids } = base();
|
||||
const other = doc.fork("bob");
|
||||
doc.apply([{ op: "update", id: ids.undo, body: "Every edit is a commit and can be undone. Undo history is unlimited: every step back to the creation of the document is kept." }], "A: unlimited undo");
|
||||
doc.apply([{ op: "update", id: ids.hoisting, body: "Any node can be hoisted to fill the page, and a breadcrumb leads back up." }], "A: breadcrumb");
|
||||
other.apply([{ op: "create", parent: ids.root, title: "Memory limits", body: "To bound memory, the editor keeps only the last 20 undo steps; older steps are discarded and cannot be undone." }], "B: undo cap");
|
||||
other.apply([{ op: "update", id: ids.sidenotes, body: "A note of one to three sentences is shown in the right margin beside the line it is about." }], "B: right margin");
|
||||
return { doc, other, ids };
|
||||
},
|
||||
detect: (r) => (r.kind === "merge" && r.conflicts.length === 0 ? [] : ["expected a clean structural merge with no conflicts"]),
|
||||
check(doc, ids) {
|
||||
const found = doc.conflicts().filter((c) => c.type === "contradiction");
|
||||
const out: string[] = [];
|
||||
if (found.length !== 1) return [`expected exactly one contradiction, got ${found.length}`];
|
||||
const snap = doc.snap();
|
||||
const titles = [found[0].node, found[0].other!].map((id) => snap.nodes[id]?.title).sort();
|
||||
if (titles.join("|") !== "Memory limits|Undo") out.push(`reported the wrong pair: ${titles.join(" / ")}`);
|
||||
const undo = snap.nodes[ids.undo].body;
|
||||
const limits = Object.values(snap.nodes).find((n) => n.title === "Memory limits")!.body;
|
||||
if (has(undo, "unlimited") && has(limits, "last 20")) out.push("the two nodes still contradict after the resolution");
|
||||
if (!has(snap.nodes[ids.hoisting].body, "breadcrumb") || !has(snap.nodes[ids.sidenotes].body, "right margin")) out.push("disturbed the unrelated edits");
|
||||
return out;
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** A provider that records the request, or answers from a file. */
|
||||
function scripted(dir: string, name: string, mode: "render" | "check"): LLM {
|
||||
const refuse = () => Promise.reject(new Error("not used"));
|
||||
return {
|
||||
kind: "mock",
|
||||
stream: refuse,
|
||||
turn: refuse,
|
||||
async json<T>(req: JsonReq): Promise<T> {
|
||||
const file = join(dir, `${name}.response.json`);
|
||||
if (mode === "render") {
|
||||
const shape =
|
||||
req.schema === "resolve"
|
||||
? '{"resolutions": [{"id": "<conflict id>", "text": "<the text the node should have>", "rationale": "<one or two sentences>"}]}'
|
||||
: '{"contradictions": [{"node": "<id of the first node>", "other": "<id of the second node>", "explanation": "<one sentence>", "text": "<revised body for the second node>"}]}';
|
||||
writeFileSync(
|
||||
join(dir, `${name}.prompt.txt`),
|
||||
`=== SYSTEM ===\n${req.system}\n\n=== USER (context) ===\n${req.context}\n\n=== USER (request) ===\n${req.prompt}\n\n=== REPLY FORMAT ===\nReply with a single JSON object of exactly this shape and nothing else:\n${shape}\n`,
|
||||
);
|
||||
throw new Rendered();
|
||||
}
|
||||
if (!existsSync(file)) throw new Error(`missing ${file}`);
|
||||
return JSON.parse(readFileSync(file, "utf8")) as T;
|
||||
},
|
||||
};
|
||||
}
|
||||
class Rendered extends Error {}
|
||||
|
||||
const [mode, dir] = process.argv.slice(2) as ["render" | "check", string];
|
||||
if (!["render", "check"].includes(mode) || !dir) {
|
||||
console.error("usage: tsx scripts/fixtures.ts render|check DIR");
|
||||
process.exit(2);
|
||||
}
|
||||
mkdirSync(dir, { recursive: true });
|
||||
let failed = 0;
|
||||
for (const f of fixtures) {
|
||||
// Fixed peer ids, so node and conflict ids are the same when rendering and when checking.
|
||||
let peer = 1000n;
|
||||
setPeerSource(() => peer++);
|
||||
const { doc, other, ids } = f.build();
|
||||
const report = mergeBranch(doc, other, "bob");
|
||||
const detection = f.detect(report, doc);
|
||||
const llm = scripted(dir, f.name, mode);
|
||||
try {
|
||||
if (f.name === "cross-node-contradiction") await scanContradictions(llm, doc, report);
|
||||
else await resolveConflicts(llm, doc);
|
||||
} catch (err) {
|
||||
if (!(err instanceof Rendered)) throw err;
|
||||
}
|
||||
if (mode === "render") {
|
||||
console.log(`${detection.length ? "FAIL" : "ok "} detect ${f.name}${detection.length ? ": " + detection.join("; ") : ""}`);
|
||||
failed += detection.length ? 1 : 0;
|
||||
continue;
|
||||
}
|
||||
const problems = [...detection, ...f.check(doc, ids)];
|
||||
const history = verifyHistory(doc);
|
||||
if (history.mismatches.length || history.unhashed) problems.push("history no longer verifies");
|
||||
console.log(`${problems.length ? "FAIL" : "pass"} ${f.name}: ${f.about}`);
|
||||
for (const p of problems) console.log(` - ${p}`);
|
||||
failed += problems.length ? 1 : 0;
|
||||
}
|
||||
console.log(mode === "render" ? `\nprompts written to ${dir}` : `\n${fixtures.length - failed} of ${fixtures.length} fixtures pass`);
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* Evaluate the link scanner (server/links/scan.ts) on the starter library against hand labels.
|
||||
*
|
||||
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts warm [docs…] live: fill the Wikipedia cache for the
|
||||
* sampled sections, write their traces
|
||||
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts eval [docs…] offline (cache only): precision and
|
||||
* recall against the labels
|
||||
* IE_DATA=/tmp/x npx tsx scripts/linkEval.ts trace [docs…] offline: the traces, for labelling
|
||||
*
|
||||
* The sample is the first SAMPLE sections (in reading order, document text included) of each named
|
||||
* document that have at least 40 words. Labels: tests/fixtures/link-labels.json, one entry per
|
||||
* phrase (by its normalised key) per section, saying whether it is worth linking and to what.
|
||||
* `warm` goes to Wikipedia through the client (serial, spaced as it enforces) and stops at a budget
|
||||
* of requests (IE_EVAL_BUDGET, default 380); nothing but candidate phrases is sent. The embedding
|
||||
* model is the real one unless IE_EMBED says otherwise.
|
||||
*/
|
||||
import { readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { importDoc } from "../src/core/library";
|
||||
import { Doc, ancestorsInDoc, documents, sections, type NodeId, type Snap } from "../src/core/model";
|
||||
import { embedder } from "../server/embed";
|
||||
import { extract } from "../server/links/extract";
|
||||
import { NodeIndex } from "../server/links/nodeIndex";
|
||||
import { Linker, type TraceRow, type Tuning } from "../server/links/scan";
|
||||
import { WikiClient } from "../server/wiki";
|
||||
|
||||
const [mode = "eval", ...rest] = process.argv.slice(2);
|
||||
const DATA = resolve(process.env.IE_DATA ?? "");
|
||||
if (!process.env.IE_DATA) throw new Error("set IE_DATA to a scratch directory");
|
||||
const SAMPLE = Number(process.env.IE_EVAL_SAMPLE ?? 12);
|
||||
const BUDGET = Number(process.env.IE_EVAL_BUDGET ?? 380);
|
||||
const DOCS = rest.length ? rest : ["octopus-minds", "fixed-points", "origin-of-the-elements", "invention-of-writing"];
|
||||
const LABELS = resolve("tests/fixtures/link-labels.json");
|
||||
|
||||
// The whole starter library, so that titles in other documents can be matched as they would be.
|
||||
const doc = Doc.library("eval");
|
||||
for (const f of readdirSync("library").filter((x) => x.endsWith(".md")).sort()) importDoc(doc, readFileSync(join("library", f), "utf8"), f, { creator: "eval", slug: f.replace(/\.md$/, "") });
|
||||
const snap = doc.snap();
|
||||
|
||||
const words = (s: string) => s.split(/\s+/).filter(Boolean).length;
|
||||
function sample(snap: Snap, slug: string): NodeId[] {
|
||||
const d = documents(snap).find((x) => snap.nodes[x].slug === slug);
|
||||
if (!d) throw new Error(`no document ${slug}`);
|
||||
const out: NodeId[] = [];
|
||||
const visit = (id: NodeId) => {
|
||||
if (out.length < SAMPLE && words(snap.nodes[id].body) >= 40) out.push(id);
|
||||
sections(snap, id).forEach(visit);
|
||||
};
|
||||
visit(d);
|
||||
return out;
|
||||
}
|
||||
const pathOf = (id: NodeId) => [...ancestorsInDoc(snap, id).reverse().slice(1), id].map((x) => snap.nodes[x].title).join(" › ") || snap.nodes[id].title;
|
||||
|
||||
// `sample`: the sampled sections' texts only, for labelling before the scanner has seen them.
|
||||
if (mode === "sample") {
|
||||
const out = DOCS.flatMap((slug) => sample(snap, slug).map((id) => ({ doc: slug, node: pathOf(id), text: snap.nodes[id].body })));
|
||||
const file = join(DATA, `sample-${DOCS.join("+")}.json`);
|
||||
writeFileSync(file, JSON.stringify(out, null, 1));
|
||||
console.error(`${out.length} sections → ${file}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const live = mode === "warm";
|
||||
const wiki = new WikiClient({
|
||||
dataDir: DATA,
|
||||
// Offline modes answer from the cache alone: anything uncached is "unavailable", never fetched.
|
||||
...(live ? {} : { fetch: (async () => { throw new TypeError("offline (eval)"); }) as typeof fetch, offlineHoldMs: 0, spacingMs: 0 }),
|
||||
});
|
||||
const index = new NodeIndex(() => doc, { file: join(DATA, "vectors", "eval-nodes"), embedder: embedder(), delayMs: 0 });
|
||||
const tuning: Partial<Tuning> = JSON.parse(process.env.IE_EVAL_TUNING ?? "{}");
|
||||
const linker = new Linker({ doc: () => doc, wiki: () => wiki, embedder: embedder(), index, tuning });
|
||||
|
||||
const t0 = performance.now();
|
||||
await index.refresh();
|
||||
const indexMs = Math.round(performance.now() - t0);
|
||||
console.error(`index: ${index.vectors.size} sections in ${indexMs} ms${index.degraded ? " (no model: degraded)" : ""}`);
|
||||
|
||||
const nodes = DOCS.flatMap((slug) => sample(snap, slug).map((id) => ({ slug, id })));
|
||||
|
||||
if (live) {
|
||||
// One deduplicated lookup of every candidate of every sampled section first: 50 phrases a request.
|
||||
const variants = [...new Set(nodes.flatMap(({ id }) => extract(snap.nodes[id].body, { skip: new Set() }).flatMap((c) => c.variants)))];
|
||||
console.error(`${nodes.length} sections, ${variants.length} distinct phrases to look up`);
|
||||
await wiki.lookup(variants, { priority: "bulk" });
|
||||
wiki.flush();
|
||||
console.error(`lookups done: ${wiki.requests} requests`);
|
||||
}
|
||||
|
||||
type Row = TraceRow & { doc: string; node: string; sentence?: string };
|
||||
const rows: Row[] = [];
|
||||
const perNode: { node: string; ms: number; requests: number }[] = [];
|
||||
for (const { slug, id } of nodes) {
|
||||
if (live && wiki.requests >= BUDGET) {
|
||||
console.error(`budget of ${BUDGET} requests reached; stopping before ${pathOf(id)}`);
|
||||
break;
|
||||
}
|
||||
const trace: TraceRow[] = [];
|
||||
const r = await linker.scan({ node: id, priority: live ? "bulk" : "interactive", trace });
|
||||
perNode.push({ node: pathOf(id), ms: r.stats.ms, requests: r.stats.requests });
|
||||
const body = snap.nodes[id].body;
|
||||
for (const t of trace) {
|
||||
const from = Math.max(body.lastIndexOf(". ", t.start) + 2, body.lastIndexOf("\n", t.start) + 1, 0);
|
||||
const to = body.indexOf(". ", t.start);
|
||||
rows.push({ ...t, doc: slug, node: pathOf(id), sentence: body.slice(from, to < 0 ? body.length : to + 1) });
|
||||
}
|
||||
if (live) wiki.flush();
|
||||
if (live) console.error(`${slug} › ${pathOf(id)}: ${r.stats.candidates} candidates, ${r.suggestions.length} chosen, ${r.stats.requests} requests (total ${wiki.requests})`);
|
||||
}
|
||||
wiki.flush();
|
||||
|
||||
if (mode === "warm" || mode === "trace") {
|
||||
const file = join(DATA, `trace-${DOCS.join("+")}.json`);
|
||||
writeFileSync(file, JSON.stringify(rows, null, 1));
|
||||
console.error(`${rows.length} traced phrases → ${file}; ${wiki.requests} requests`);
|
||||
const ms = perNode.map((p) => p.ms).sort((a, b) => a - b);
|
||||
console.error(`scan time per section: median ${ms[ms.length >> 1]} ms, max ${ms[ms.length - 1]} ms; requests per section: ${(perNode.reduce((a, p) => a + p.requests, 0) / Math.max(1, perNode.length)).toFixed(2)}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// ---- heldout: closed-world scoring against a list of everything worth linking ----
|
||||
|
||||
if (mode === "heldout") {
|
||||
// tests/fixtures/link-labels-heldout.json lists, per section, every phrase worth a link and the
|
||||
// acceptable targets, written from the text before the scanner ran. A link not on it is wrong.
|
||||
const held: { doc: string; node: string; key: string; phrase: string; targets: string[] }[] = JSON.parse(readFileSync(resolve("tests/fixtures/link-labels-heldout.json"), "utf8")).labels.filter((l: { doc: string }) => DOCS.includes(l.doc));
|
||||
const label = (r: Row) => held.find((l) => l.doc === r.doc && l.node === r.node && l.key === r.key);
|
||||
const ok = (r: Row) => !!label(r)?.targets.includes(r.target);
|
||||
const chosen = rows.filter((r) => r.chosen);
|
||||
const line = (name: string, set: Row[]) => {
|
||||
const right = set.filter(ok).length;
|
||||
console.log(`${name.padEnd(16)} ${String(set.length).padStart(4)} chosen ${String(right).padStart(4)} right precision ${(set.length ? right / set.length : 1).toFixed(3)} recall ${(right / held.length).toFixed(3)}`);
|
||||
};
|
||||
console.log(`documents: ${DOCS.join(", ")}; ${nodes.length} sections; ${held.length} phrases worth linking`);
|
||||
line("auto", chosen.filter((r) => r.tier === "auto"));
|
||||
line("auto + suggest", chosen);
|
||||
const fmt = (r: Row) => ` [${r.tier} fit ${r.fit ?? "-"}] ${r.doc} | ${r.node} | “${r.phrase}” → ${r.target}${label(r) ? ` (label: ${label(r)!.targets.join(" or ")})` : " (not on the list)"} — ${r.sentence?.trim().slice(0, 140)}`;
|
||||
console.log("\nauto errors:");
|
||||
for (const r of chosen.filter((r) => r.tier === "auto" && !ok(r))) console.log(fmt(r));
|
||||
console.log("\nauto right:");
|
||||
for (const r of chosen.filter((r) => r.tier === "auto" && ok(r))) console.log(fmt(r));
|
||||
if (process.env.IE_EVAL_SUGGEST) {
|
||||
console.log("\nsuggest errors:");
|
||||
for (const r of chosen.filter((r) => r.tier === "suggest" && !ok(r))) console.log(fmt(r));
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// ---- eval ----
|
||||
|
||||
interface Label {
|
||||
doc: string;
|
||||
node: string;
|
||||
key: string;
|
||||
phrase: string;
|
||||
/** yes: worth linking, to `target`. no: not worth linking. */
|
||||
label: "yes" | "no";
|
||||
target?: string;
|
||||
note?: string;
|
||||
}
|
||||
const labels: Label[] = JSON.parse(readFileSync(LABELS, "utf8")).labels;
|
||||
const mine = labels.filter((l) => DOCS.includes(l.doc));
|
||||
const find = (r: Row) => mine.find((l) => l.doc === r.doc && l.node === r.node && l.key === r.key);
|
||||
const chosen = rows.filter((r) => r.chosen);
|
||||
const unlabelled = chosen.filter((r) => !find(r));
|
||||
const correct = (r: Row) => {
|
||||
const l = find(r);
|
||||
return !!l && l.label === "yes" && l.target === r.target;
|
||||
};
|
||||
const yes = mine.filter((l) => l.label === "yes").length;
|
||||
const report = (name: string, set: Row[]) => {
|
||||
const labelled = set.filter(find);
|
||||
const right = labelled.filter(correct).length;
|
||||
const p = labelled.length ? right / labelled.length : 1;
|
||||
const rcl = yes ? right / yes : 0;
|
||||
console.log(`${name.padEnd(16)} ${String(set.length).padStart(4)} chosen ${String(right).padStart(4)} right precision ${p.toFixed(3)} recall ${rcl.toFixed(3)}`);
|
||||
};
|
||||
console.log(`documents: ${DOCS.join(", ")}; ${nodes.length} sections; ${mine.length} labelled phrases (${yes} worth linking)`);
|
||||
report("auto", chosen.filter((r) => r.tier === "auto"));
|
||||
report("auto + suggest", chosen);
|
||||
if (unlabelled.length) console.log(`unlabelled chosen: ${unlabelled.length}\n${unlabelled.map((r) => ` ${r.doc} | ${r.node} | ${r.key} → ${r.target} [${r.tier}]`).join("\n")}`);
|
||||
const show = (title: string, list: Row[]) => {
|
||||
if (!list.length) return;
|
||||
console.log(`\n${title}`);
|
||||
for (const r of list) {
|
||||
const l = find(r);
|
||||
console.log(` [${r.tier ?? "drop"} ${r.score.toFixed(3)} fit ${r.fit ?? "-"}] “${r.phrase}” → ${r.target}${l ? ` label: ${l.label}${l.target && l.target !== r.target ? ` (${l.target})` : ""}` : ""} (${r.why})`);
|
||||
}
|
||||
};
|
||||
const wrong = chosen.filter((r) => find(r) && !correct(r));
|
||||
show("wrong (chosen, label disagrees):", wrong);
|
||||
const missed = mine.filter((l) => l.label === "yes" && !chosen.some((r) => r.doc === l.doc && r.node === l.node && r.key === l.key && correct(r)));
|
||||
if (missed.length && process.env.IE_EVAL_MISSES) {
|
||||
console.log("\nmissed (worth linking, not chosen or wrong target):");
|
||||
for (const l of missed) {
|
||||
const r = rows.find((x) => x.doc === l.doc && x.node === l.node && x.key === l.key);
|
||||
console.log(` ${l.doc} | ${l.node} | “${l.phrase}” → ${l.target}${r ? ` scanner: ${r.target} [${r.tier ?? "drop"} ${r.score} fit ${r.fit}] ${r.why}` : " (never resolved)"}`);
|
||||
}
|
||||
}
|
||||
if (process.env.IE_EVAL_RIGHT) show("right:", chosen.filter(correct));
|
||||
// Every labelled row with what judge() saw, for tuning (IE_EVAL_DUMP=file).
|
||||
if (process.env.IE_EVAL_DUMP) {
|
||||
const dump = rows.map((r) => ({ ...r, label: find(r)?.label ?? null, labelTarget: find(r)?.target ?? null, right: correct(r) }));
|
||||
writeFileSync(process.env.IE_EVAL_DUMP, JSON.stringify(dump, null, 1));
|
||||
}
|
||||
// The embedding worker is unref'd, but a script is done here whatever is still open.
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Checks on the seed document that do not need a browser.
|
||||
*
|
||||
* tsx scripts/verify.ts coverage of the prompt + history verification
|
||||
* tsx scripts/verify.ts entail F write the parent/children pairs to F, for a fresh model to judge
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { Doc, descendants, sections } from "../src/core/model";
|
||||
import { verifyHistory } from "../src/core/repo";
|
||||
import { writeSeed } from "../src/core/seed";
|
||||
import { overlaps, plain, sentences } from "../src/core/text";
|
||||
import { seed } from "../src/seed/tree";
|
||||
|
||||
const prompt = readFileSync(new URL("../src/seed/prompt.txt", import.meta.url), "utf8");
|
||||
const doc = Doc.library("seed");
|
||||
const first = writeSeed(doc, prompt, seed);
|
||||
const snap = doc.snap();
|
||||
const root = snap.nodes[first];
|
||||
|
||||
if (process.argv[2] === "entail") {
|
||||
// Each node that has sections, with those sections: the claim is that the first is a
|
||||
// summary supported by the rest. The document itself is excluded: it is the prompt, not a summary.
|
||||
const pairs = descendants(snap, first)
|
||||
.map((id) => snap.nodes[id])
|
||||
.filter((n) => n.kind === "section" && sections(snap, n.id).length)
|
||||
.map((n) => ({
|
||||
id: n.id,
|
||||
title: n.title,
|
||||
summary: plain(n.body),
|
||||
sections: sections(snap, n.id).map((c) => ({ title: snap.nodes[c].title, body: plain(snap.nodes[c].body) })),
|
||||
}));
|
||||
writeFileSync(process.argv[3], JSON.stringify(pairs, null, 2));
|
||||
console.log(`wrote ${pairs.length} parent/children pairs to ${process.argv[3]}`);
|
||||
} else {
|
||||
const tops = sections(snap, first);
|
||||
const all = sentences(root.body);
|
||||
let uncovered = 0;
|
||||
for (const s of all) {
|
||||
const by = tops.filter((id) => snap.nodes[id].anchors.some((a) => overlaps(s, [a.start, a.end])));
|
||||
if (!by.length) {
|
||||
uncovered++;
|
||||
console.log(`UNCOVERED: ${root.body.slice(s[0], s[1])}`);
|
||||
}
|
||||
}
|
||||
const nodes = descendants(snap, first).map((id) => snap.nodes[id]);
|
||||
console.log(`prompt sentences: ${all.length}, traced to a section: ${all.length - uncovered}, untraced: ${uncovered}`);
|
||||
console.log(`tree: ${nodes.filter((n) => n.kind === "section").length} sections, ${nodes.filter((n) => n.kind === "note").length} notes`);
|
||||
const v = verifyHistory(doc);
|
||||
console.log(`history: ${v.checked} commits re-hashed after checkout, ${v.mismatches.length} mismatches, ${v.unhashed} without a hash`);
|
||||
process.exit(uncovered || v.mismatches.length ? 1 : 0);
|
||||
}
|
||||
Reference in new issue
Block a user