Files
CatoandClaude 380a31be95 Quick check reads PDFs; a scored deadline eval set; docs truth (#183)
* feat(intake): PDF on the quick check, and a deadline eval set

- /api/extract-pdf reads a PDF's text layer on the server (unpdf, %PDF magic
  check, 10 MB, 10 pages, text capped at MAX_TEXT). Nothing stored or logged.
  Scans answer scanned_pdf; the page then offers the photo picker.
- One file input takes a PDF or photos; the text flows into the letter box and
  the existing redaction and analyze path. Messages in en, de, fr, it.
- eval/letters: 17 synthetic Swiss letters (de, fr, en) with expected
  deadlines; eval/pdf: text and image-only PDFs; `pnpm eval:deadlines` scores
  stored replies offline, or live with --url on the free chain.
- Docs: README quick-check/matter line, ROADMAP ticks, CHANGELOG 2026-12-02,
  .env.example host path.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(eval): optional private letter set, scored separately

--private <dir> / CAUSIUS_EVAL_PRIVATE_DIR (default
/opt/causius/shared/eval-private). Absent: "private set: not present,
skipped". Present: "private: N/M (x%)" and pass/fail by position only; no ids,
names, quotes or dates are printed. eval-private/ and eval/private/ ignored.

Co-Authored-By: Claude <noreply@anthropic.com>

* feat(eval): precision, recall and false-invention rate; answer key for the private set

Most letters correctly have no deadline, so each is scored true negative,
false invention, true positive, miss or wrong date. Ranges accept any date in
them. Private set reads answers.json and letters/*.txt and prints only counts,
metrics and pass/fail by position. Four more synthetic traps: open-ended
suspension risk, amount with no date, spend-cap reset, 2-3 working days.

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-03 01:55:56 +01:00

92 lines
4.0 KiB
JavaScript

// pnpm eval:deadlines [--url <base> [--save] [--only id,id] [--delay-ms n]]
//
// Default: offline. Scores the stored replies in eval/replies/ through the
// app's own caseFromReply; never calls a model, so CI can run it.
//
// --url <base>: opt-in live run. POSTs each letter to <base>/api/analyze on the
// free shared chain only (no key is sent, none is needed, nothing is paid for)
// and scores what comes back. Paced under the analyzeFree limit (8 an hour per
// caller), so a full set takes about two hours: run it on purpose, never from
// verify or CI. --save writes each reply to eval/replies/ to be committed.
//
// --private <dir> (or CAUSIUS_EVAL_PRIVATE_DIR; default /opt/causius/shared/eval-private):
// an optional private letter set in the same layout, with stored replies in
// <dir>/replies, scored separately and offline. Only counts, scores and
// pass/fail by position are printed: never ids, names, quotes or dates.
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { load } from "./load.mjs";
const dir = (p) => fileURLToPath(new URL(p, import.meta.url));
const args = process.argv.slice(2);
const flag = (name) => args.includes(name);
const value = (name) => {
const i = args.indexOf(name);
return i >= 0 ? args[i + 1] : undefined;
};
const [score] = await load(["/eval/score.ts"]);
const lettersDir = dir("letters");
const repliesDir = dir("replies");
const { cases } = score.readCases(lettersDir);
const only = value("--only")?.split(",");
const selected = only ? cases.filter((c) => only.includes(c.id)) : cases;
const base = value("--url")?.replace(/\/+$/, "");
let replies = score.readReplies(repliesDir);
if (base) {
if (!/^https?:\/\//.test(base)) {
console.error("--url must be a base address such as https://example.org");
process.exit(2);
}
// One request per window/limit (limits.analyzeFree: 8 an hour), plus a second of slack.
const delay = Number(value("--delay-ms") ?? Math.ceil(3_600_000 / 8) + 1_000);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
replies = new Map();
for (let i = 0; i < selected.length; i++) {
const c = selected[i];
if (i > 0) await sleep(delay);
let outcome;
for (let attempt = 0; attempt < 3 && !outcome; attempt++) {
const res = await fetch(`${base}/api/analyze`, {
method: "POST",
headers: { "content-type": "application/json" },
// No `byok`: the free shared chain, whatever it is today.
body: JSON.stringify({ text: score.readLetter(lettersDir, c), languages: [], locale: c.lang === "fr" ? "fr" : c.lang === "de" ? "de" : "en" }),
}).catch(() => null);
if (res?.status === 429) {
const wait = Number(res.headers.get("retry-after") ?? 60) * 1000;
console.error(`rate limited; waiting ${Math.round(wait / 1000)} s`);
await sleep(wait + 1_000);
continue;
}
const body = res ? await res.json().catch(() => ({})) : {};
outcome = res?.ok && body.case ? body.case : { error: body.error ?? `http ${res?.status ?? "unreachable"}` };
}
if (!outcome || outcome.error) {
console.error(`${c.id}: no case (${outcome?.error ?? "rate limited"})`);
continue;
}
// The letter's own text is not kept in a stored reply.
const { texts, draftReply, ...kept } = outcome;
void texts;
void draftReply;
const stored = {
id: c.id,
source: `live ${new Date().toISOString().slice(0, 10)} via ${base}/api/analyze (free shared chain)`,
reply: JSON.stringify(kept),
};
replies.set(c.id, stored);
if (flag("--save")) writeFileSync(`${repliesDir}/${c.id}.json`, JSON.stringify(stored, null, 2) + "\n");
console.error(`${c.id}: done (${i + 1}/${selected.length})`);
}
}
const results = score.scoreAll(selected, replies);
console.log(score.report(selected, results));
const privateDir = value("--private") ?? process.env.CAUSIUS_EVAL_PRIVATE_DIR ?? score.DEFAULT_PRIVATE_DIR;
console.log("");
console.log(score.scorePrivate(privateDir).lines.join("\n"));