From d05717bbefc2278e1cc55ca74745b359cea9cfdd Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 22 Sep 2026 11:42:07 +0000 Subject: [PATCH] fix(doctor): read speaker labels from harvested text at Step 1.5 corpusShape now counts speakers from knowledge/text prefixes so doctor --require-shape works after Collect, before Derive. --- src/commands/doctor.mjs | 127 +++++++++++++++++++++++---- tests/doctor-coverage.test.mjs | 59 +++++-------- tests/gates/baseline/audit-tests.txt | 1 - 3 files changed, 131 insertions(+), 56 deletions(-) diff --git a/src/commands/doctor.mjs b/src/commands/doctor.mjs index 6b355abe..b7a7995c 100644 --- a/src/commands/doctor.mjs +++ b/src/commands/doctor.mjs @@ -165,6 +165,88 @@ function resolvedAnchors(skillDir) { return known; } +/** + * Split normalised text into the same blocks the parser wrote: a `[k00NN]` line + * starts a unit, and wrap-continuations join it. Step 1.5 has no `voice.json` yet. + */ +const TEXT_ANCHOR_BRACKETS = /\[(k\d{4,}(?::t\d+)?)\]/g; +const TEXT_ANCHOR_LEADING = /^(k\d{4,}(?::t\d+)?)\b/; +const TEXT_TIMESTAMP = /^\s*(\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?)\s*/; +const TEXT_TIMECODE = /^\s*(\d{1,3}:\d{2}:\d{2}(?:[.,]\d{1,3})?)\s*/; +const TEXT_SPEAKER = /^([^\d::\n][^::\n]{0,23})[::]\s*/; +const TEXT_SENTENCE = /[。!?!?…]+/; + +function textBlocks(text) { + const blocks = []; + for (const line of String(text).split(/\r?\n/)) { + const anchors = [...line.matchAll(TEXT_ANCHOR_BRACKETS)].map((match) => match[1]); + if (anchors.length === 0) { + const leading = TEXT_ANCHOR_LEADING.exec(line); + if (leading) anchors.push(leading[1]); + } + if (anchors.length > 0) blocks.push(line); + else if (line.trim() !== "" && blocks.length > 0) blocks[blocks.length - 1] += ` ${line.trim()}`; + } + return blocks; +} + +/** `[k00NN] :` → speaker plus the remaining sentence text. */ +function speakerPrefix(line) { + let rest = line.replace(TEXT_ANCHOR_BRACKETS, " ").replace(TEXT_ANCHOR_LEADING, " "); + const stamp = TEXT_TIMESTAMP.exec(rest); + if (stamp) rest = rest.slice(stamp[0].length); + const timecode = TEXT_TIMECODE.exec(rest); + if (timecode) rest = rest.slice(timecode[0].length); + const prefix = TEXT_SPEAKER.exec(rest); + if (!prefix) return { speaker: null, text: rest.replace(/\s+/g, " ").trim() }; + return { speaker: prefix[1].trim(), text: rest.slice(prefix[0].length).replace(/\s+/g, " ").trim() }; +} + +function sentenceSamples(text) { + return String(text ?? "") + .split(TEXT_SENTENCE) + .map((piece) => piece.trim()) + .filter((piece) => piece !== "") + .map((piece) => [...piece].filter((char) => !/\s/.test(char)).length) + .filter((count) => count > 0).length; +} + +function speakersFromText(skillDir) { + const textDir = join(skillDir, "knowledge", "text"); + const bySpeaker = {}; + if (!existsSync(textDir)) return bySpeaker; + for (const name of readdirSync(textDir).sort()) { + if (!name.endsWith(".md")) continue; + let body = ""; + try { + body = readFileSync(join(textDir, name), "utf8"); + } catch { + continue; + } + for (const block of textBlocks(body)) { + const { speaker, text } = speakerPrefix(block); + if (!speaker) continue; + const samples = sentenceSamples(text); + if (samples === 0) continue; + bySpeaker[speaker] = { samples: (bySpeaker[speaker]?.samples ?? 0) + samples }; + } + } + return bySpeaker; +} + +function voiceBySpeaker(skillDir) { + const voicePath = join(skillDir, "evidence", "derived", "voice.json"); + if (!existsSync(voicePath)) return null; + try { + const voice = JSON.parse(readFileSync(voicePath, "utf8")); + const claim = (voice.claims ?? []).find((item) => item?.id === "voice.sentence_length"); + const bySpeaker = claim?.value?.by_speaker ?? null; + return bySpeaker && typeof bySpeaker === "object" ? bySpeaker : null; + } catch { + return null; + } +} + /** * A pre-flight read on the **corpus shape**: is this material able to carry a * person at all? @@ -173,12 +255,12 @@ function resolvedAnchors(skillDir) { * hypothetical — a 47-minute multi-speaker floor proceeding was run through the whole * five-step mainline, producing a portrait of a room instead of a person, because the * only judge of "is this the right material" was the model's own judgement at the end. - * The numbers here come from what `retrospect` already derived, so this is a reading, - * not a second derivation: + * Speakers come from parser prefixes in `knowledge/text/*.md`. `voice.json` is only a + * cross-check: it is written at Derive, after this gate is supposed to have run. * * - `units` anchors the ledger records (how much material there is); - * - `speakers` distinct speakers the voice derivation could attribute units to; - * - `top_share` the busiest speaker's share of the attributed units. + * - `speakers` distinct speaker prefixes on those text units; + * - `top_share` the busiest speaker's share of the attributed samples. * * Verdict rules, deliberately blunt and stated in the receipt: * - fewer than 20 citable units → FAIL (nothing to be a person *from*); @@ -190,22 +272,25 @@ function resolvedAnchors(skillDir) { function corpusShape(skillDir, ledger) { const reasons = []; const notes = []; + const warnings = []; const units = ledger.anchors; - const voicePath = join(skillDir, "evidence", "derived", "voice.json"); - let bySpeaker = null; - if (existsSync(voicePath)) { - try { - const voice = JSON.parse(readFileSync(voicePath, "utf8")); - const claim = (voice.claims ?? []).find((item) => item?.id === "voice.sentence_length"); - bySpeaker = claim?.value?.by_speaker ?? null; - } catch { - bySpeaker = null; + const bySpeaker = speakersFromText(skillDir); + const fromVoice = voiceBySpeaker(skillDir); + if (fromVoice) { + const voiceNames = Object.keys(fromVoice).sort(); + const textNames = Object.keys(bySpeaker).sort(); + const voiceAttributed = Object.values(fromVoice).reduce((total, item) => total + (item?.samples ?? 0), 0); + const textAttributed = Object.values(bySpeaker).reduce((total, item) => total + (item?.samples ?? 0), 0); + if (voiceNames.join("\n") !== textNames.join("\n") || voiceAttributed !== textAttributed) { + warnings.push( + `knowledge/text speakers=${textNames.length} attributed=${textAttributed} disagrees with evidence/derived/voice.json speakers=${voiceNames.length} attributed=${voiceAttributed}; shape uses the text`, + ); } } - const speakers = bySpeaker ? Object.keys(bySpeaker) : []; - const attributed = bySpeaker ? Object.values(bySpeaker).reduce((total, item) => total + (item?.samples ?? 0), 0) : 0; - const top = bySpeaker - ? Object.entries(bySpeaker).sort(([, a], [, b]) => (b?.samples ?? 0) - (a?.samples ?? 0))[0] + const speakers = Object.keys(bySpeaker); + const attributed = Object.values(bySpeaker).reduce((total, item) => total + (item?.samples ?? 0), 0); + const top = speakers.length + ? Object.entries(bySpeaker).sort((a, b) => (b[1]?.samples ?? 0) - (a[1]?.samples ?? 0) || (a[0] < b[0] ? -1 : 1))[0] : null; const topShare = top && attributed > 0 ? (top[1]?.samples ?? 0) / attributed : null; @@ -237,6 +322,7 @@ function corpusShape(skillDir, ledger) { verdict: reasons.length === 0 ? "PASS" : "FAIL", reasons, notes, + warnings, }; } @@ -326,7 +412,12 @@ register("doctor", { const personDir = join(baseDir, entry); const ledgerPath = join(personDir, "knowledge", "index.json"); if (!existsSync(ledgerPath)) continue; - shapes.push({ slug: `${family}/${entry}`, ...corpusShape(personDir, readLedger(personDir)) }); + const shaped = corpusShape(personDir, readLedger(personDir)); + const { warnings: shapeWarnings = [], ...shape } = shaped; + for (const line of shapeWarnings) { + if (!warnings.includes(line)) warnings.push(line); + } + shapes.push({ slug: `${family}/${entry}`, ...shape }); } } const skills = listSkills(baseDir); diff --git a/tests/doctor-coverage.test.mjs b/tests/doctor-coverage.test.mjs index 6c7ea88e..8d1cc4e3 100644 --- a/tests/doctor-coverage.test.mjs +++ b/tests/doctor-coverage.test.mjs @@ -13,11 +13,16 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { parseReceipt, runCli } from "./helpers/cli.mjs"; import { resolveSkillsRoot } from "../src/cli/paths.mjs"; +const here = dirname(fileURLToPath(import.meta.url)); +const INTERVIEW_CORPUS = join(here, "fixtures", "public-corpus", "synthetic-interview"); +const HOUSE_CORPUS = join(here, "fixtures", "public-corpus", "us-house-floor-2009-07-29"); + /** base/skills/colleague/ with a ledger and a derived claim. */ function fixture({ dangling = false } = {}) { const base = mkdtempSync(join(tmpdir(), "dst-doctor-")); @@ -145,40 +150,18 @@ test("doctor counts what the generated Skill cites, not only the derived layer", } }); -/** base/skills/colleague/demo with a ledger of N anchors and a per-speaker voice claim. */ -function shapeFixture({ anchors, speakers }) { - const base = mkdtempSync(join(tmpdir(), "dst-shape-")); - const skillDir = join(base, "skills", "colleague", "demo"); - mkdirSync(join(skillDir, "knowledge"), { recursive: true }); - mkdirSync(join(skillDir, "evidence", "derived"), { recursive: true }); - const ids = Array.from({ length: anchors }, (_, index) => `k${String(index + 1).padStart(4, "0")}`); - writeFileSync( - join(skillDir, "knowledge", "index.json"), - `${JSON.stringify([{ id: "k0001", kind: "subtitle", bytes: 1, sha256: "a".repeat(64), anchors: ids }], null, 2)}\n`, - "utf8", - ); - const by_speaker = {}; - for (const [name, samples] of Object.entries(speakers)) by_speaker[name] = { samples }; - writeFileSync( - join(skillDir, "evidence", "derived", "voice.json"), - `${JSON.stringify({ kind: "voice", claims: [{ id: "voice.sentence_length", value: { by_speaker } }] }, null, 2)}\n`, - "utf8", - ); - return base; -} - test("the corpus shape check passes on a corpus that can carry a person", () => { - // 40 citable units, three speakers, three quarters of the units attributable and a - // clear lead — a meeting in which one person is actually the subject. - const base = shapeFixture({ anchors: 40, speakers: { 张三: 15, 李四: 10, 主持人: 5 } }); + const base = mkdtempSync(join(tmpdir(), "dst-shape-")); try { + const harvested = runCli(["harvest", INTERVIEW_CORPUS, "--person", "lin-gong", "--base-dir", base, "--json"]); + assert.equal(harvested.status, 0, harvested.stderr); const run = runCli(["doctor", "--base-dir", base, "--require-shape", "--json"]); assert.equal(run.status, 0, run.stderr); const receipt = parseReceipt(run.stdout); assert.equal(receipt.shape.length, 1); assert.equal(receipt.shape[0].verdict, "PASS"); - assert.equal(receipt.shape[0].units, 40); - assert.equal(receipt.shape[0].attributed_units, 30); + assert.equal(receipt.shape[0].speakers, 2); + assert.equal(receipt.shape[0].top_speaker, "林工"); assert.deepEqual(receipt.shape[0].reasons, []); assert.equal(receipt.verdict, "PASS"); } finally { @@ -187,19 +170,16 @@ test("the corpus shape check passes on a corpus that can carry a person", () => }); test("the corpus shape check catches a multi-speaker corpus nobody can be cut out of", () => { - // The real failure this exists for: a 47-minute floor proceeding, 2744 anchors, 18 - // speakers, 3% of units attributable. It ran the whole five-step mainline and - // produced a portrait of a room, because nothing asked "is this the right material" - // before Distill. Without `--require-shape` the verdict is reported only; with it, - // the command fails. - const base = shapeFixture({ anchors: 100, speakers: { A: 2, B: 1, C: 1 } }); + const base = mkdtempSync(join(tmpdir(), "dst-shape-")); try { + const harvested = runCli(["harvest", HOUSE_CORPUS, "--person", "us-house", "--base-dir", base, "--json"]); + assert.equal(harvested.status, 0, harvested.stderr); const reported = runCli(["doctor", "--base-dir", base, "--json"]); assert.equal(reported.status, 0, "reporting a bad shape is not itself a failure"); const soft = parseReceipt(reported.stdout); assert.equal(soft.shape[0].verdict, "FAIL"); assert.equal(soft.ok, true); - assert.match(soft.shape[0].reasons.join("\n"), /只有 4% 的单元能归到某个说话人/); + assert.match(soft.shape[0].reasons.join("\n"), /只有 3% 的单元能归到某个说话人/); assert.match(soft.shape[0].reasons.join("\n"), /不要从会议流水里切人/); const gated = runCli(["doctor", "--base-dir", base, "--require-shape", "--json"]); @@ -248,13 +228,18 @@ test("doctor fails when views/.view.json cites an anchor the ledger does n }); test("too little material fails the shape check before quality is even discussed", () => { - const base = shapeFixture({ anchors: 5, speakers: {} }); + const base = mkdtempSync(join(tmpdir(), "dst-shape-tiny-")); + const corpus = mkdtempSync(join(tmpdir(), "dst-tiny-corpus-")); try { + writeFileSync(join(corpus, "note.md"), "hello world. a short note.\n", "utf8"); + const harvested = runCli(["harvest", corpus, "--person", "demo", "--base-dir", base, "--json"]); + assert.equal(harvested.status, 0, harvested.stderr); const receipt = parseReceipt(runCli(["doctor", "--base-dir", base, "--json"]).stdout); assert.equal(receipt.shape[0].verdict, "FAIL"); - assert.match(receipt.shape[0].reasons.join("\n"), /可引用单元只有 5 个,低于 20/); + assert.match(receipt.shape[0].reasons.join("\n"), /可引用单元只有 \d+ 个,低于 20/); assert.match(receipt.shape[0].notes.join("\n"), /没有说话人标注/); } finally { rmSync(base, { recursive: true, force: true }); + rmSync(corpus, { recursive: true, force: true }); } }); diff --git a/tests/gates/baseline/audit-tests.txt b/tests/gates/baseline/audit-tests.txt index 00741fee..128430a4 100644 --- a/tests/gates/baseline/audit-tests.txt +++ b/tests/gates/baseline/audit-tests.txt @@ -13,6 +13,5 @@ R56 `blind-test prepare` works with the relative --out the handoff (§8) and the R21 identity.json: a handle claimed twice exits 2 with the exact message and writes nothing R21 identity.json with a person that lists no handles is a warning, not a crash R28 a document's labels (根因:/ 时间线:) are not counted as participants in a multi-source person -R24 Step 1.5: `doctor --require-shape` run after Collect and before Derive fails the C-SPAN floor corpus R48 doctor reports the channels this machine cannot collect from and the computer-use share R58 manifest.json must not point the host at Python installers that are not in the tree