// `archilyzer case …` -- a research case's pipeline from a shell or a Claude Code session // (plans/release-38/research-cases-and-assist.md, lane A). The stages are controller/casePipelineRun.ts, the same // functions umtool's case page runs; each records its run in the case's stages.json, so the page shows a run made // here and the other way round. // // The case is umtool's board, `/.umtool/research//case.json` (created on umtool's /research); // the pipeline's files sit beside it. The reports root is --root, else REPORTS_DIR, else the parent of // SONG_REPORTS_DIR, else ~/reports -- umtool's own rule (umtool/lib/paths.mjs). The corpus is read, never written: // TRANSCRIPTS_DIR picks it, as for `archilyzer corpus grep`. // // PRIVATE NAMES ARE NEVER ARGUMENTS. `case private-names add` reads the terms from stdin, one per line, // hashes each and stores only the hash; nothing it prints names one. An argument would sit in the shell's history // and the process list. import { readFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { getPaths, type Paths } from "../lib/paths"; import type { FlagValue } from "./_parseFlags"; import { CASE_FILES, isFindingBy, type FindingBy } from "../lib/research/caseTypes"; import { privateNameHash } from "../lib/research/privateNames-server"; import { CasePipelineError, emptyDefinition, longestLine, privateTermProblem, readerPrompt } from "../lib/research/casePipeline"; import { appendFindings, mutateDefinition, readBatchText, readBatches, readCandidateCounts, readCoverage, readDefinition, readFindings, readStages, readSummary, saveDefinition, withholdStored, writeSummary, } from "../lib/research/caseStore-server"; import { mergeView, runBatches, runCandidates, runCoverage, runDateChecks, runExport } from "../controller/casePipelineRun"; const str = (v: FlagValue | undefined) => (typeof v === "string" ? v : undefined); const int = (v: FlagValue | undefined, name: string): number | undefined => { if (v === undefined) return undefined; const n = Number(v); if (!Number.isFinite(n) || n < 0) throw new CasePipelineError(`--${name} is a number`); return n; }; export function reportsRoot(flags: Record, env: NodeJS.ProcessEnv = process.env): string { const r = str(flags.root) ?? env.REPORTS_DIR ?? (env.SONG_REPORTS_DIR ? path.dirname(path.resolve(env.SONG_REPORTS_DIR)) : path.join(os.homedir(), "reports")); return path.resolve(r); } /** The case's directory, refused unless umtool made the case (its case.json is there). */ export async function caseDirOf(root: string, id: string | undefined): Promise<{ dir: string; id: string; title: string }> { if (!id || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(id)) throw new CasePipelineError(`a case id (lowercase letters, digits and dashes), not ${JSON.stringify(id ?? "")}`); const dir = path.join(root, ".umtool", "research", id); let title = id; try { const c = JSON.parse(await readFile(path.join(dir, "case.json"), "utf8")) as { title?: unknown }; if (typeof c.title === "string" && c.title) title = c.title; } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") throw new CasePipelineError(`no case "${id}" under ${root} (make it on umtool's /research first: the pipeline sits beside its board)`, 404); throw new CasePipelineError(`${id}/case.json cannot be read: ${(e as Error).message}`, 409); } return { dir, id, title }; } async function readStdin(): Promise { if (process.stdin.isTTY) process.stderr.write("one per line, then Ctrl-D:\n"); const chunks: Buffer[] = []; for await (const c of process.stdin) chunks.push(c as Buffer); return Buffer.concat(chunks).toString("utf8"); } const n = (k: number, w: string) => `${k} ${w}${k === 1 ? "" : "s"}`; const out = (json: boolean, value: unknown, text: () => string) => { console.log(json ? JSON.stringify(value, null, 2) : text()); return 0; }; export type CaseVerb = | "show" | "define" | "private-names" | "prompt" | "coverage" | "candidates" | "batches" | "batch" | "findings" | "summary" | "merge" | "export" | "date-checks"; export async function main(verb: CaseVerb, positionals: string[], flags: Record, deps: { paths?: Paths } = {}): Promise { try { const c = await caseDirOf(reportsRoot(flags), positionals[0]); const json = flags.json === true; const corpus = () => deps.paths ?? getPaths(); switch (verb) { case "show": { const def = await readDefinition(c.dir, c.id); const [stages, counts, batches, findings, summary, coverage] = await Promise.all([readStages(c.dir), readCandidateCounts(c.dir), readBatches(c.dir), readFindings(c.dir), readSummary(c.dir), readCoverage(c.dir)]); const view = { case: c.id, dir: c.dir, defined: !!def, status: def?.status ?? null, subjects: def?.subjects.map((s) => s.name) ?? [], eras: def?.eras.map((e) => e.id) ?? [], groups: def?.groups.map((g) => g.id) ?? [], privateNames: def?.privateNames.sha256.length ?? 0, coverage: coverage.length, candidates: counts?.windows ?? null, batches: { total: batches.length, pending: batches.filter((b) => b.state === "pending").length, read: batches.filter((b) => b.state === "read").length }, findings: { rows: findings.rows.length, invalid: findings.invalid.length }, summary: summary ? { draft: summary.draft, by: summary.by } : null, stages, }; return out(json, view, () => [ `${c.title} (${c.id}) — ${c.dir}`, def ? `defined: ${n(view.subjects.length, "subject")}, eras ${view.eras.join(", ") || "none"}, groups ${view.groups.join(", ") || "none"}, ${n(view.privateNames, "private name")} (hashed); status ${view.status}` : "not defined yet (archilyzer case define --file pipeline.json)", `coverage: ${view.coverage} channel-years · candidates: ${view.candidates ?? "not built"} · batches: ${view.batches.total} (${view.batches.pending} pending, ${view.batches.read} read) · findings: ${view.findings.rows}${view.findings.invalid ? ` (${view.findings.invalid} lines do not check)` : ""} · summary: ${summary ? (summary.draft ? "a draft" : "written") : "none"}`, ...Object.entries(stages).map(([k, s]) => ` ${k}: ${s?.state} ${s?.endedAt ?? s?.startedAt} (${s?.by})${s?.error ? ` — ${s.error}` : ""}`), ].join("\n"), ); } case "define": { const file = str(flags.file); if (!file) throw new CasePipelineError("--file is required"); const raw = JSON.parse(await readFile(file, "utf8")) as Record; const pn = raw.privateNames as Record | undefined; if (pn && "terms" in pn) throw new CasePipelineError("privateNames.terms is never stored: add the names with `archilyzer case private-names add` (stdin), which keeps only their hashes"); const prev = await readDefinition(c.dir, c.id); const def = await saveDefinition(c.dir, c.id, { ...raw, privateNames: { sha256: prev?.privateNames.sha256 ?? [], note: typeof pn?.note === "string" ? pn.note : (prev?.privateNames.note ?? "") } }); return out(json, def, () => `${c.id}: ${n(def.subjects.length, "subject")}, ${n(def.eras.length, "era")}, ${n(def.groups.length, "group")} saved (${CASE_FILES.definition}); ${n(def.privateNames.sha256.length, "private name")} kept`); } case "private-names": { const op = positionals[1]; if (op !== "add" && op !== "remove" && op !== "clear" && op !== "count") throw new CasePipelineError("private-names takes add, remove, clear or count (terms on stdin)"); if (op === "count") { const def = await readDefinition(c.dir, c.id); return out(json, { count: def?.privateNames.sha256.length ?? 0 }, () => `${n(def?.privateNames.sha256.length ?? 0, "private name")} (hashed)`); } const terms = op === "clear" ? [] : (await readStdin()).split("\n").map((t) => t.trim()).filter(Boolean); for (const [i, t] of terms.entries()) { const p = privateTermProblem(t); if (p) throw new CasePipelineError(`line ${i + 1}: ${p}`); } const hashes = terms.map(privateNameHash); let changed = 0; const def = await mutateDefinition( c.dir, c.id, (d) => { const before = d.privateNames.sha256.length; if (op === "clear") d.privateNames.sha256 = []; else if (op === "add") d.privateNames.sha256 = [...new Set([...d.privateNames.sha256, ...hashes])]; else d.privateNames.sha256 = d.privateNames.sha256.filter((h) => !hashes.includes(h)); changed = Math.abs(d.privateNames.sha256.length - before); }, () => emptyDefinition(c.id), ); // A name added after the candidates and batches were written is withheld from them now. const withheld = op === "add" ? await withholdStored(c.dir, def.privateNames.sha256) : 0; return out(json, { changed, count: def.privateNames.sha256.length, withheld }, () => `${op === "add" ? "added" : "removed"} ${changed}; ${n(def.privateNames.sha256.length, "private name")} (hashed)${withheld ? `; withheld in ${n(withheld, "place")} of the candidates and batches` : ""}`, ); } case "prompt": { const def = await readDefinition(c.dir, c.id); if (!def) throw new CasePipelineError(`case ${c.id} has no pipeline yet`, 409); const group = positionals[1] ?? "common"; if (group !== "common" && !def.groups.some((g) => g.id === group)) throw new CasePipelineError(`no group "${group}" (${def.groups.map((g) => g.id).join(", ")})`); console.log(readerPrompt(def, group)); return 0; } case "coverage": { const r = await runCoverage(c.dir, c.id, corpus(), "cli"); return out(json, r, () => [ "channel\tyear\tlisted\theld\ttranscribed\tuntranscribed audio", ...r.rows.map((x) => `${x.channel}\t${x.year || "undated"}${x.key ? "*" : ""}\t${x.listed}\t${x.held}\t${x.transcribed}\t${x.untranscribedAudio}`), ...r.skipped.map((s) => `skipped ${s.slug}: ${s.reason}`), "(* a key year: an era touches it)", ].join("\n"), ); } case "candidates": { const r = await runCandidates(c.dir, c.id, corpus(), "cli", { W: int(flags.window, "window"), maxSpan: int(flags["max-span"], "max-span"), maxPerRecording: int(flags["per-recording"], "per-recording") }); const k = r.counts; return out(json, k, () => [ `${n(k.windows, "window")} in ${n(k.videos, "recording")} (${n(k.titleHits, "title hit")}) → ${CASE_FILES.candidates}`, `by family: ${Object.entries(k.byFamily).map(([f, n]) => `${f} ${n}`).join(", ") || "none"}`, `by year: ${Object.entries(k.byYear).map(([y, n]) => `${y} ${n}`).join(", ") || "none"}`, `by channel: ${Object.entries(k.byChannel).map(([s, n]) => `${s} ${n}`).join(", ") || "none"}`, `by group: ${Object.entries(k.byGroup).map(([g, n]) => `${g} ${n}`).join(", ") || "none"}`, `noise: ${Object.entries(k.noise).map(([f, n]) => `${f} ${n}`).join(", ")}`, `scanned: ${k.scanned.channels} channels, ${k.scanned.videos} recordings, ${k.scanned.inEra} in an era, ${k.scanned.withText} with words, ${k.scanned.noText} with none yet, ${k.scanned.undated} undated`, ...k.skipped.map((s) => `skipped ${s.slug}: ${s.reason}`), ].join("\n"), ); } case "batches": { const r = await runBatches(c.dir, c.id, "cli", { budget: int(flags.budget, "budget") }); return out(json, r.batches, () => [`round ${r.round}: ${r.made.length} made, ${r.kept.length} kept`, ...r.batches.map((b) => `${b.id}\t${b.state}\t${n(b.windows.length, "window")}\t${b.chars} chars\t${b.file}`)].join("\n")); } case "batch": { const t = await readBatchText(c.dir, positionals[1] ?? ""); process.stdout.write(t); if (longestLine(t) > 200) process.stderr.write("warning: this batch has a line over 200 characters (it was written by something else)\n"); return 0; } case "findings": { const file = str(flags.file); if (!file) throw new CasePipelineError("--file is required (one finding row per line)"); const def = await readDefinition(c.dir, c.id); const rows = (await readFile(file, "utf8")).split("\n").filter((l) => l.trim()).map((l, i) => { try { return JSON.parse(l) as unknown; } catch { throw new CasePipelineError(`line ${i + 1} of ${file} is not JSON`); } }); const written = await appendFindings(c.dir, rows, def?.privateNames.sha256 ?? []); return out(json, written, () => `${written.length} ${written.length === 1 ? "row" : "rows"} appended: ${written.map((r) => r.row).join(", ")}`); } case "summary": { const file = str(flags.file); if (!file) throw new CasePipelineError("--file is required"); const by = str(flags.by) ?? "hand"; if (!isFindingBy(by)) throw new CasePipelineError("--by is hand, api, local or code"); const def = await readDefinition(c.dir, c.id); const s = await writeSummary(c.dir, { text: await readFile(file, "utf8"), draft: by !== "hand", by: by as FindingBy, ...(str(flags.model) ? { model: str(flags.model) } : {}) }, def?.privateNames.sha256 ?? []); return out(json, s, () => `summary saved${s.draft ? " (a draft: it says so in the report until a person saves it)" : ""}`); } case "merge": { const m = await mergeView(c.dir, c.id, { minRelevance: int(flags["min-relevance"], "min-relevance") }); return out(json, m, () => [ ...m.sections.map((s) => `${s.label} (${s.group}): ${s.rows.length} — ${s.rows.map((r) => r.row).join(", ")}`), `quarantined: ${m.quarantined.length}; below relevance ${m.minRelevance}: ${m.belowFloor.length}; duplicates folded: ${m.duplicates.length}; rows: ${m.total}`, ...m.invalid.map((x) => `line ${x.line} does not check: ${x.errors.join("; ")}`), ].join("\n"), ); } case "export": { const r = await runExport(c.dir, c.id, c.title, "cli", { minRelevance: int(flags["min-relevance"], "min-relevance"), paths: corpus() }); return out(json, { report: path.join(c.dir, CASE_FILES.report) }, () => `${path.join(c.dir, CASE_FILES.report)} and ${CASE_FILES.reportHtml}: ${r.merged.sections.reduce((n, s) => n + s.rows.length, 0)} findings`); } case "date-checks": { const r = await runDateChecks(c.dir, c.id, corpus(), "cli", { aroundDays: int(flags.around, "around"), latest: int(flags.latest, "latest") }); return out(json, r, () => r.map((d) => `${d.date} ${d.label}: ${n(d.uploads.length, "upload")} — ${d.sentence}`).join("\n")); } } } catch (e) { console.error(`case ${verb}: ${(e as Error).message}`); return e instanceof CasePipelineError && e.status === 400 ? 2 : 1; } }