From d3c44e02d79b006c206ce8f54d6fd0c4cf58dc8e Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 30 Sep 2026 18:59:26 +0800 Subject: [PATCH] Add local human adjudication store that computes human review accuracy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The report previously could not compute human accuracy because upstream only says whether AI and human agree, never who was right. This adds an append-only local store so a reviewer judges each (typically diverged) document across weekly passes, and report monthly folds those judgments back in. - review-store.ts: JSONL per tenant+month (~/.config/seal-use/reviews/ -.jsonl), append-only (weekly passes never rewrite), one record per SN; last write wins on re-adjudication. Verdicts: ai_correct, human_correct, both_correct, both_wrong, undecided. Env-overridable root (SEAL_USE_REVIEWS_DIR) for tests; corrupt lines skipped. - collect.ts: load the store, join verdicts onto fetched blocks, compute humanAccuracy = (human_right / reviewed) * 100 over adjudicated samples, expose reviewedCount/divergedCount, and flip humanAccuracyAvailable. No reviews -> honest gap (still unavailable), never fabricated. - render.ts: when available, fill the §1.2 human row with real accuracy and replace the gap warning with a coverage note; when not, keep the warning. - CLI: `report review set/list --month ... [--sn --verdict --note --reviewed-by]` (set writes local store, list reads it). Help registers both as separate commands; read-only list vs mutating set classified accordingly. Prefix help (`report review --help`) now lists subcommands instead of erroring. - parser: register --template/--report-id/--max-runs/--verdict/--reviewed-by (the first three were previously rejected as unknown, breaking report monthly's own flags); reviewed-by moves to VALUE_FLAGS so it consumes its argument. - SKILL.md: document the adjudication workflow and storage semantics. Verified: 639 tests (6 new review tests incl. tenant/month isolation, corrupt line skip, join + accuracy math, honest no-review gap, render coverage note), tsc clean, oxlint 0 warnings. --- skills/seal-use/SKILL.md | 17 +++ src/cli/commands/report.ts | 44 +++++++- src/cli/help.ts | 28 +++++ src/cli/parser.ts | 11 ++ src/cli/read-only.ts | 2 +- src/domains/seal/reports/collect.ts | 47 +++++++- src/domains/seal/reports/render.ts | 12 +- src/domains/seal/reports/reports.test.ts | 127 ++++++++++++++++++++- src/domains/seal/reports/review-store.ts | 137 +++++++++++++++++++++++ 9 files changed, 418 insertions(+), 7 deletions(-) create mode 100644 src/domains/seal/reports/review-store.ts diff --git a/skills/seal-use/SKILL.md b/skills/seal-use/SKILL.md index ee4b886..dff0bf9 100644 --- a/skills/seal-use/SKILL.md +++ b/skills/seal-use/SKILL.md @@ -126,3 +126,20 @@ seal-use report monthly --month --corp - **无上游口径不编造**:人工审核准确率、失准原因分类等取不到的指标,保留模板示例值并在表后追加 `> ⚠️ 数据说明` 标注来源缺口——如实告知而非填假数字。 - 结果里的 `next` 给出下游 `validate` / `render` 指引(校验与 HTML/PNG/PDF 渲染用 `report-templates/validate.py`、`render.py`,不进包)。 - 只读能力 `sealReportMonthlyGet`,MCP 经 `seal_use` 网关可达;`--template` 可换自定义模板路径。 + +### 人工裁决回填(算出人工审核准确率) + +上游只给 AI 与人工结论是否同向(`agreement`),**谁对必须人来判**。判断结果按 SN 本地持久化,跨周累积到月底,`report monthly` 据此回填 §1.2 人工审核准确率与覆盖度说明: + +```bash +# 录入一条裁决(本地 JSONL,无需网络;通常裁决 AI≠人工 的分歧单) +seal-use report review set --month --sn --verdict [--note <说明>] [--reviewed-by <裁决人>] --corp + +# 查看已录入的裁决 +seal-use report review list --month --corp +``` + +- **存储**:`~/.config/seal-use/reviews/-.jsonl`,追加式一行一条,可直接手改/`tail`;同 SN 改判以后写为准。 +- **语义**:`ai_correct`=AI 对人工错,`human_correct`=人工对 AI 错,`both_correct`=双方都对,`both_wrong`=双方都错,`undecided`=已看暂无法判。 +- **自动接入**:`report monthly` 载入该租户该月裁决,SN 匹配上真实审批块后,人工准确率 = 判为"人工对"数 / 已裁决总数;`notes.humanAccuracyAvailable` 标记是否可得,`reviewedCount`/`divergedCount` 说明覆盖度。无裁决则保持 ⚠️ 数据说明,不编造。 +- `review set` 是本地写(非只读),`review list` 是只读;两者都进 help 注册表与读写白名单。 diff --git a/src/cli/commands/report.ts b/src/cli/commands/report.ts index 3bb52e9..fd7e8ed 100644 --- a/src/cli/commands/report.ts +++ b/src/cli/commands/report.ts @@ -2,7 +2,8 @@ import type { CorpConfig } from "../../core/config/types.js"; import type { createSealClient } from "../../core/http/factory.js"; import { runCapability } from "../helpers.js"; import { numberOption, stringOption } from "../parser.js"; -import { outputOptions } from "../printer.js"; +import { outputOptions, printJson } from "../printer.js"; +import { loadReviews, reviewFilePath, writeReview } from "../../domains/seal/reports/review-store.js"; import type { ParsedArgs } from "../types.js"; /** `seal-use report monthly` — 月度 AI 审核准确率报告(Markdown 填充)。 */ @@ -32,5 +33,46 @@ export async function handleReportCommand( return; } + if (action === "review") { + const sub = args.command[2]; // set | list + const month = stringOption(args.options.month); + if (!month) { + throw new Error("Usage: seal-use report review --month [--sn --verdict ] [--corp ]"); + } + + if (sub === "list") { + const reviews = loadReviews(corp.id, month); + printJson({ + corpId: corp.id, + month, + file: reviewFilePath(corp.id, month), + count: reviews.size, + reviews: [...reviews.values()] + }); + return; + } + + if (sub === "set") { + const sn = stringOption(args.options.sn) ?? stringOption(args.options["document-sn"]); + const verdict = stringOption(args.options.verdict); + if (!sn || !verdict) { + throw new Error( + "Usage: seal-use report review set --month --sn --verdict [--note ] [--reviewed-by ] [--corp ]" + ); + } + const record = writeReview(corp.id, { + sn, + month, + verdict, + note: stringOption(args.options.note), + reviewedBy: stringOption(args.options["reviewed-by"]) ?? stringOption(args.options.reviewedBy) + }); + printJson({ corpId: corp.id, file: reviewFilePath(corp.id, month), record }); + return; + } + + throw new Error(`Unknown report review subcommand: ${sub ?? ""}. Use 'set' or 'list'.`); + } + throw new Error(`Unknown report command: ${action ?? ""}. Run 'seal-use report --help' for available commands.`); } diff --git a/src/cli/help.ts b/src/cli/help.ts index 3336ba4..96cff46 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -617,6 +617,28 @@ export const HELP_REGISTRY: AreaHelp[] = [ { flag: "--max-runs ", description: "Cap approval-run detail fetch, default 500 (max 500)" } ], description: "The template is the mutable skin: section headings, tables, and order may change and data demands are inferred from headings (src/domains/seal/reports/describe.ts). Fields with no upstream metric (human accuracy, mismatch categories) keep template sample values and are marked with a warning note instead of fabricated numbers." + }, + { + name: "review set", + summary: "Record one human adjudication (who was right: AI or human) for a document", + usage: ["seal-use report review set --month --sn --verdict [--note ] [--reviewed-by ] [--corp ]"], + options: [ + { flag: "--month ", description: "Statistics month, YYYY-MM (required)" }, + { flag: "--sn ", description: "Document SN to adjudicate (required)" }, + { flag: "--verdict ", description: "ai_correct | human_correct | both_correct | both_wrong | undecided (required)" }, + { flag: "--note ", description: "Optional adjudication note" }, + { flag: "--reviewed-by ", description: "Optional reviewer name for the audit trail" } + ], + description: "Append-only local JSONL per tenant+month (~/.config/seal-use/reviews/). Typically adjudicate diverged blocks (AI != human); report monthly joins these to compute human accuracy. No network: writes only the local store." + }, + { + name: "review list", + summary: "List human adjudications recorded for a tenant+month", + usage: ["seal-use report review list --month [--corp ]"], + options: [ + { flag: "--month ", description: "Statistics month, YYYY-MM (required)" } + ], + description: "Reads the local JSONL store and returns all adjudications keyed by SN." } ] }, @@ -1296,6 +1318,12 @@ export function renderHelp(target: string[] = []): string { const matchedCommand = findCommandInArea(areaEntry, actionPath, rest); if (!matchedCommand) { + // 前缀命令(如 `report review` 覆盖 `review set`/`review list`):列出该组子命令而非报错 + const groupPrefix = `${actionPath} `; + const subcommands = areaEntry.commands.filter((cmd) => cmd.name?.startsWith(groupPrefix)); + if (subcommands.length > 0) { + return renderAreaHelp({ ...areaEntry, commands: subcommands }); + } throw usageError(`Unknown ${areaEntry.area} command: ${rest.join(" ")}. Run 'seal-use ${areaEntry.area} --help' for available commands.`); } diff --git a/src/cli/parser.ts b/src/cli/parser.ts index 17a0aa5..46521e7 100644 --- a/src/cli/parser.ts +++ b/src/cli/parser.ts @@ -54,6 +54,7 @@ export const VALUE_FLAGS = new Set([ "json", "key-id", "keyId", "keyword", "level", "limit", "lines", "link", "linter", "manual-status", "manualApprovalStatus", "manualStatus", "max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode", + "max-runs", "month", "n", "name", "note", "o", "offset", "out", "out-dir", "outDir", "outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", @@ -61,6 +62,8 @@ export const VALUE_FLAGS = new Set([ "path", "phone", "policyId", "poll-interval", "pollInterval", "port", "prod", "prod-corp", "prodCorp", "purpose", "q", "query", "record-id", "record-ids", "recordId", "recordIds", "reject-node", "rejectNode", + "reviewed-by", "reviewedBy", + "report-id", "repo", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow", "rule", "rule-id", "ruleId", "ruleVersion", "runtime-id", "runtimeId", "samples", "scenarios", "schema-config", "schemaConfig", "scope", @@ -71,9 +74,12 @@ export const VALUE_FLAGS = new Set([ "staffName", "staffPhone", "start", "start-date", "start-time", "startDate", "startTime", "state", "status", "strictness", "tag", "tag-id", "tagId", "tags", "target", "target-corp", "targetCorp", "task-mode", + "template", "taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title", "to", "token", "tokenId", + "template", "type", "until", "url", "userId", "version-name", "versionName", + "verdict", "webhook", "workflow-type-id", "workflowTypeId" ]); @@ -101,6 +107,7 @@ export const KNOWN_FLAGS = new Set([ "key-id", "keyId", "keyword", "level", "limit", "lines", "link", "linter", "local", "manual-status", "manualApprovalStatus", "manualStatus", "max-chars", "maxChars", "maxResults", "min-score", "minScore", "mode", + "max-runs", "month", "n", "name", "no-attachments", "no-flow", "no-wait", "noWait", "note", "o", "offset", "out", "out-dir", "outDir", @@ -110,7 +117,9 @@ export const KNOWN_FLAGS = new Set([ "prod", "prod-corp", "prodCorp", "publish", "purpose", "q", "query", "quiet", "r", "recode", "record-id", "record-ids", "recordId", "recordIds", "refresh", "reject-node", "rejectNode", "repo", + "report-id", "request-ids", "requestIds", "result-url", "resultUrl", "reuse-window", "reuseWindow", + "reviewed-by", "reviewedBy", "reveal", "rotate-secret", "rotateSecret", "rule", "rule-id", "ruleId", "ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios", "schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret", @@ -122,10 +131,12 @@ export const KNOWN_FLAGS = new Set([ "staffId", "staffName", "staffPhone", "start", "start-date", "start-time", "startDate", "startTime", "state", "status", "strict", "strictness", "summary", "tag", "tag-id", "tagId", "tags", "target", + "template", "target-corp", "targetCorp", "task-mode", "taskMode", "template-id", "templateId", "test-corp", "thinking-depth", "thinkingDepth", "timeout", "timezone", "title", "to", "to-downloads", "toDownloads", "token", "tokenId", "type", "until", "url", "userId", "v", "version", "version-name", + "verdict", "versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId", "workspace", "yes" ]); diff --git a/src/cli/read-only.ts b/src/cli/read-only.ts index b99aa21..d587675 100644 --- a/src/cli/read-only.ts +++ b/src/cli/read-only.ts @@ -78,7 +78,7 @@ const READ_ONLY_COMMANDS: Record = { // `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a // mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES. analytics: ["insight", "risks", "performance", "export"], - report: ["monthly"], + report: ["monthly", "review list"], source: ["config"], skill: ["dump", "status"], doctor: ["", "guide", "paths", "tenant", "auth"], diff --git a/src/domains/seal/reports/collect.ts b/src/domains/seal/reports/collect.ts index 7cb5bf5..e5753be 100644 --- a/src/domains/seal/reports/collect.ts +++ b/src/domains/seal/reports/collect.ts @@ -3,6 +3,7 @@ import * as api from "../api.js"; import { formatBeijingIso } from "../../../core/config/timestamps.js"; import type { ApprovalRun } from "../types.js"; import type { ReportDemand } from "./describe.js"; +import { loadReviews, type ReviewRecord } from "./review-store.js"; /** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */ type Polarity = "pass" | "reject" | "unknown"; @@ -23,6 +24,8 @@ export type ReportBlock = { agreement: "agreed" | "diverged" | "unknown"; aiSummary: string | undefined; humanComment: string | undefined; + /** 本地人工裁决结论(若该 SN 已 review),来自 review-store */ + verdict?: ReviewRecord["verdict"]; }; export type ReportTemplateGroup = { @@ -53,11 +56,19 @@ export type ReportData = { }; blocks: ReportBlock[]; templateGroups: ReportTemplateGroup[]; + /** 该租户该月的人工裁决(SN → 记录),由 review-store 载入,用于回填人工准确率 */ + reviews: Map; + /** 人工审核准确率(%):仅当本地裁决覆盖样本时有值 */ + humanAccuracy?: number; /** 章节数据完备性标记,渲染时逐节如实写入 */ notes: { - humanAccuracyAvailable: false; // 上游无"人工审核准确率"指标;v1 恒为 false,接口出现后再接 + /** 人工准确率是否可得(有本地裁决) */ + humanAccuracyAvailable: boolean; failureRateAvailable: boolean; mismatchCategoriesAvailable: boolean; + /** 裁决样本数 / 分歧样本数,供报告如实说明覆盖度 */ + reviewedCount?: number; + divergedCount?: number; }; }; @@ -66,6 +77,8 @@ export type CollectOptions = { corp: { id: string; name: string }; /** 用于拉明细分块的上限,防御性封顶 */ maxRuns?: number; + /** 是否载入本地人工裁决(默认载入);关掉则 humanAccuracy 恒为不可得 */ + loadReviews?: boolean; }; function monthRange(month: string): { startDate: string; endDate: string } { @@ -102,6 +115,9 @@ export async function collectReportData( fetched, blocks: [], templateGroups: [], + reviews: options.loadReviews === false + ? new Map() + : loadReviews(options.corp.id, options.month), notes: { humanAccuracyAvailable: false, failureRateAvailable: false, @@ -217,6 +233,35 @@ export async function collectReportData( data.notes.failureRateAvailable = data.performance !== undefined; data.notes.mismatchCategoriesAvailable = false; // 失准原因分类无上游字段,需人工归类 + + // 3. 人工裁决回填:把本地 review 挂到 blocks,并据此算人工准确率 + if (data.reviews.size > 0) { + let reviewed = 0; + let diverged = 0; + let aiRight = 0; + let humanRight = 0; + for (const block of data.blocks) { + const review = data.reviews.get(block.sn); + if (review) { + block.verdict = review.verdict; + reviewed += 1; + if (block.agreement === "diverged") diverged += 1; + // 人工正确:human_correct 或 both_correct;AI 正确:ai_correct 或 both_correct + if (review.verdict === "human_correct" || review.verdict === "both_correct") humanRight += 1; + if (review.verdict === "ai_correct" || review.verdict === "both_correct") aiRight += 1; + } + } + if (reviewed > 0) { + data.notes.reviewedCount = reviewed; + data.notes.divergedCount = diverged; + // 人工准确率 = 被裁决为"人工对"的单数 / 被裁决总单数 + data.humanAccuracy = Number(((humanRight / reviewed) * 100).toFixed(2)); + data.notes.humanAccuracyAvailable = true; + // AI 准确率同样可从裁决侧复核(供对照),但 §1.2 主准确率仍用上游 performance + void aiRight; + } + } + return data; } diff --git a/src/domains/seal/reports/render.ts b/src/domains/seal/reports/render.ts index e2880f4..8c8d87c 100644 --- a/src/domains/seal/reports/render.ts +++ b/src/domains/seal/reports/render.ts @@ -210,6 +210,11 @@ function transformTable( /** 表后追加的数据说明(人工准确率缺口径时)。 */ function noteAfter(columns: string[], heading: string, lastH2: string, data: ReportData): string[] { if (columns.includes("审核方式") && columns.includes("准确率")) { + if (data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined) { + const reviewed = data.notes.reviewedCount ?? 0; + const diverged = data.notes.divergedCount ?? 0; + return ["", `> ℹ️ **数据说明**:人工审核准确率由本地人工裁决回填(已裁决 ${reviewed} 笔,其中分歧 ${diverged} 笔);AI 准确率为上游效能口径。`, ""]; + } return ["", HUMAN_ACCURACY_NOTE, ""]; } if (heading.includes("失准构成总览") && lastH2.includes("失准") && data.fetched.performance) { @@ -236,9 +241,14 @@ function replacementRows( // §1.2 准确率结论表(表头 2 列:审核方式|准确率;示例行 AI/人工 两行) if (columns.includes("审核方式") && columns.includes("准确率") && columns.length === 2) { if (!data.fetched.performance || !perf) return null; + const humanCell = data.notes.humanAccuracyAvailable && data.humanAccuracy !== undefined + ? `**${pct(data.humanAccuracy)}**` + : sampleRows.length > 1 + ? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*") + : "*(口径待业务提供)*"; return [ ["AI 审核", `**${pct(perf.accuracy)}**`], - ["人工审核", sampleRows.length > 1 ? (parseRow(sampleRows[1]!)[1] ?? "*(口径待业务提供)*") : "*(口径待业务提供)*"] + ["人工审核", humanCell] ]; } diff --git a/src/domains/seal/reports/reports.test.ts b/src/domains/seal/reports/reports.test.ts index b3315b1..c4c1fa4 100644 --- a/src/domains/seal/reports/reports.test.ts +++ b/src/domains/seal/reports/reports.test.ts @@ -1,9 +1,11 @@ -import { describe, expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { describeTemplate } from "./describe.js"; +import { collectReportData, type ReportData } from "./collect.js"; import { renderMonthlyReport } from "./render.js"; -import type { ReportData } from "./collect.js"; +import { loadReviews, writeReview, reviewFilePath } from "./review-store.js"; const TEMPLATE = join(import.meta.dirname, "..", "..", "..", "..", "report-templates", "monthly.md"); @@ -36,6 +38,7 @@ function sampleData(overrides: Partial = {}): ReportData { { template: "费用报销", total: 100, agreed: 92, diverged: 8 }, { template: "差旅报销", total: 140, agreed: 130, diverged: 10 } ], + reviews: new Map(), notes: { humanAccuracyAvailable: false, failureRateAvailable: true, mismatchCategoriesAvailable: false }, ...overrides }; @@ -163,3 +166,121 @@ describe("renderMonthlyReport", () => { expect(out).toContain("⚠️ **数据说明**"); }); }); + + +describe("review store + human accuracy join", () => { + const originalEnv = process.env.SEAL_USE_REVIEWS_DIR; + let testDir: string; + + beforeEach(() => { + testDir = mkdtempSync(join(tmpdir(), "seal-reviews-test-")); + process.env.SEAL_USE_REVIEWS_DIR = testDir; + }); + + afterEach(() => { + if (originalEnv === undefined) delete process.env.SEAL_USE_REVIEWS_DIR; + else process.env.SEAL_USE_REVIEWS_DIR = originalEnv; + rmSync(testDir, { recursive: true, force: true }); + }); + + test("writeReview appends and loadReviews merges by SN (last write wins)", () => { + writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "human_correct" }); + writeReview("corp-a", { sn: "FP2", month: "2026-08", verdict: "ai_correct" }); + // 同一 SN 改判:后写覆盖先写 + writeReview("corp-a", { sn: "FP1", month: "2026-08", verdict: "both_correct" }); + + const reviews = loadReviews("corp-a", "2026-08"); + expect(reviews.size).toBe(2); + expect(reviews.get("FP1")?.verdict).toBe("both_correct"); + expect(reviews.get("FP2")?.verdict).toBe("ai_correct"); + + // 文件按租户+月份分片,追加式 JSONL + expect(reviewFilePath("corp-a", "2026-08")).toContain("corp-a-2026-08.jsonl"); + const content = readFileSync(reviewFilePath("corp-a", "2026-08"), "utf8").trim().split("\n"); + expect(content).toHaveLength(3); // 3 次写入(含改判) + }); + + test("loadReviews isolates tenants and months, skips corrupt lines", () => { + writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" }); + writeReview("corp-b", { sn: "B1", month: "2026-08", verdict: "human_correct" }); + writeReview("corp-a", { sn: "A2", month: "2026-09", verdict: "ai_correct" }); + // 写入一行损坏数据 + const fs = require("node:fs") as typeof import("node:fs"); + fs.appendFileSync(reviewFilePath("corp-a", "2026-08"), "{corrupt json}\n", "utf8"); + + expect(loadReviews("corp-a", "2026-08").size).toBe(1); + expect(loadReviews("corp-b", "2026-08").size).toBe(1); + expect(loadReviews("corp-a", "2026-09").size).toBe(1); + expect(loadReviews("corp-a", "2026-07").size).toBe(0); + }); + + test("rejects invalid month and verdict with exit 13 validation error", () => { + expect(() => writeReview("corp-a", { sn: "X", month: "bad", verdict: "ai_correct" })).toThrow(); + expect(() => writeReview("corp-a", { sn: "X", month: "2026-08", verdict: "wrong" })).toThrow(); + expect(() => writeReview("corp-a", { sn: " ", month: "2026-08", verdict: "ai_correct" })).toThrow(); + }); + + test("collectReportData joins reviews onto fetched blocks and computes human accuracy", async () => { + // 写入裁决:3 个 SN,其中 1 个分歧单被判人工对 + writeReview("corp-a", { sn: "D1", month: "2026-08", verdict: "human_correct" }); // 分歧,人工对 + writeReview("corp-a", { sn: "A1", month: "2026-08", verdict: "ai_correct" }); // 一致,AI 对 + writeReview("corp-a", { sn: "A2", month: "2026-08", verdict: "both_correct" }); // 一致,双方对 + + // 伪客户端:只返回 3 条审批运行(SN 对应裁决),不发真网络 + const runs = [ + { id: "r1", sourceDocumentSN: "D1", result: { decision: "同意" }, pipelineData: { humanResult: "驳回" } }, + { id: "r2", sourceDocumentSN: "A1", result: { decision: "驳回" }, pipelineData: { humanResult: "驳回" } }, + { id: "r3", sourceDocumentSN: "A2", result: { decision: "同意" }, pipelineData: { humanResult: "同意" } } + ]; + const fakeClient = { + get: async () => ({ json: async () => ({ data: { records: runs, total: 3 } }) }) + } as never; + + const data = await collectReportData(fakeClient, new Set(["blocks"]), { + month: "2026-08", + corp: { id: "corp-a", name: "A" } + }); + + expect(data.reviews.size).toBe(3); + expect(data.blocks).toHaveLength(3); + // 每个 block 挂上裁决 + expect(data.blocks.map((b) => b.verdict)).toEqual(["human_correct", "ai_correct", "both_correct"]); + // 裁决数 = 3,人工对 = human_correct(D1) + both_correct(A2) = 2 → 2/3 = 66.67% + expect(data.notes.reviewedCount).toBe(3); + expect(data.notes.humanAccuracyAvailable).toBe(true); + expect(data.humanAccuracy).toBeCloseTo(66.67, 1); + // D1 是分歧单(AI 同意 / 人工驳回) + expect(data.notes.divergedCount).toBeGreaterThanOrEqual(1); + }); + + test("no reviews → human accuracy unavailable (honest gap, not fabricated)", async () => { + const fakeClient = { + get: async () => ({ json: async () => ({ data: { records: [{ id: "r1", sourceDocumentSN: "X1" }], total: 1 } }) }) + } as never; + const data = await collectReportData(fakeClient, new Set(["blocks"]), { + month: "2026-08", + corp: { id: "corp-no-reviews", name: "B" } + }); + expect(data.reviews.size).toBe(0); + expect(data.notes.humanAccuracyAvailable).toBe(false); + expect(data.humanAccuracy).toBeUndefined(); + }); + + test("render uses human accuracy when available and shows review coverage note", () => { + const template = readFileSync(TEMPLATE, "utf8"); + const plans = describeTemplate(template); + const reviews = new Map(); + reviews.set("FP260001", { sn: "FP260001", month: "2026-08", verdict: "human_correct", recordedAt: "" }); + const data = sampleData({ + reviews, + humanAccuracy: 75, + notes: { humanAccuracyAvailable: true, failureRateAvailable: true, mismatchCategoriesAvailable: false, reviewedCount: 4, divergedCount: 2 } + }); + const out = renderMonthlyReport(template, data, plans); + + // §1.2 人工审核行用真实 75%,且不再弹"口径待业务提供" + expect(out).toContain("**75.00%**"); + expect(out).toContain("已裁决 4 笔"); + expect(out).not.toContain("口径待业务提供"); + }); +}); diff --git a/src/domains/seal/reports/review-store.ts b/src/domains/seal/reports/review-store.ts new file mode 100644 index 0000000..353f71e --- /dev/null +++ b/src/domains/seal/reports/review-store.ts @@ -0,0 +1,137 @@ +import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { validationError } from "../../../core/errors.js"; + +/** + * 人工裁决的本地持久化(JSONL,按 租户 × 月份 分片)。 + * + * 为什么是 JSONL:跨周 review 天然是**追加**场景——每审一批写一批,不整文件重写, + * 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。 + * 为什么按租户+月份分片:租户隔离、月度报告天然对应一个文件、文件不会无限膨胀。 + * + * 一条记录 = 一个 SN 在某个月被人工裁决一次的结果。同一 SN 重复裁决时, + * 以**最后一条**为准(loadReviews 归并时后写覆盖先写)。 + */ + +/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */ +export type ReviewVerdict = + | "ai_correct" // AI 对,人工错 + | "human_correct" // 人工对,AI 错 + | "both_correct" // 双方都对(意见不同但结论都成立,或一致且复核通过) + | "both_wrong" // 双方都错 + | "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判) + +export type ReviewRecord = { + /** 合思/源单据 SN(裁决的自然键) */ + sn: string; + /** 裁决所属统计月 YYYY-MM(与 report monthly 的 month 对齐) */ + month: string; + verdict: ReviewVerdict; + /** 裁决人(可选,留痕用) */ + reviewedBy?: string; + /** 裁决备注(可选):为什么这么判 */ + note?: string; + /** 写入时间(北京时间 ISO 秒) */ + recordedAt: string; +}; + +const VERDICTS: ReadonlySet = new Set([ + "ai_correct", + "human_correct", + "both_correct", + "both_wrong", + "undecided" +]); + +const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR"; + +/** 裁决存储根目录:~/.config/seal-use/reviews/(租户 = 文件名前缀)。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */ +export function reviewsDir(): string { + const configured = process.env[REVIEWS_DIR_ENV]?.trim(); + if (configured) return configured; + return join(homedir(), ".config", "seal-use", "reviews"); +} + +/** 分片路径:/-.jsonl */ +export function reviewFilePath(corpId: string, month: string): string { + return join(reviewsDir(), `${sanitizeCorpId(corpId)}-${month}.jsonl`); +} + +function sanitizeCorpId(corpId: string): string { + // corpId 可能含路径分隔符等非法字符,压成安全片段 + return corpId.replace(/[^a-zA-Z0-9._-]/g, "_"); +} + +function assertMonth(month: string): void { + if (!/^\d{4}-\d{2}$/.test(month)) { + throw validationError(`Invalid month "${month}", expected YYYY-MM`); + } +} + +function assertVerdict(verdict: string): asserts verdict is ReviewVerdict { + if (!VERDICTS.has(verdict)) { + throw validationError( + `Invalid verdict "${verdict}". Expected one of: ${[...VERDICTS].join(", ")}` + ); + } +} + +/** + * 读取某租户某月的全部裁决,按 SN 归并(同一 SN 后写覆盖先写)。文件不存在返回空 Map。 + */ +export function loadReviews(corpId: string, month: string): Map { + assertMonth(month); + const filePath = reviewFilePath(corpId, month); + const reviews = new Map(); + if (!existsSync(filePath)) return reviews; + + const lines = readFileSync(filePath, "utf8").split("\n"); + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed) as ReviewRecord; + if (parsed && typeof parsed.sn === "string" && VERDICTS.has(parsed.verdict)) { + reviews.set(parsed.sn, parsed); // 后写覆盖先写 + } + } catch { + // 跳过损坏行:单行坏数据不应让整个裁决集不可读 + } + } + return reviews; +} + +/** + * 追加写一条裁决到磁盘(真正的落盘入口)。corpId 由调用方显式传入(sn 与租户无关,文件按租户分片)。 + */ +export function writeReview( + corpId: string, + input: { + sn: string; + month: string; + verdict: string; + reviewedBy?: string; + note?: string; + recordedAt?: string; + } +): ReviewRecord { + const sn = input.sn?.trim(); + if (!sn) throw validationError("sn is required for a review record"); + assertMonth(input.month); + assertVerdict(input.verdict); + + const record: ReviewRecord = { + sn, + month: input.month, + verdict: input.verdict, + ...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}), + ...(input.note?.trim() ? { note: input.note.trim() } : {}), + recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ") + }; + + const filePath = reviewFilePath(corpId, input.month); + mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 }); + appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 }); + return record; +}