Merge pull request #249 from yunyingk/mac15/add-report-glossary-page

Add trailing terms definition appendix to report renderers
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-16 18:07:44 +08:00
commit a760ea9572
11 files changed
+143 -16

No files matched your search

@@ -369,3 +369,7 @@ seal-use report export reports/审核报告.md --out build/交付整包/
3. **超高清拼接长图 (`.png`)**:
- 由原生无头浏览器以 4x 视口倍率切片截取,并通过高性能图形算法在内存中无损拼接;
- 专为钉钉、微信、飞书等移动端 IM 聊天窗口设计,方便管理层在手机上顺滑滑动审阅。
4. **末尾术语与指标定义规范附录页 (Glossary Page)**:
- 渲染流水线在生成 HTML、PDF、PNG 产物时,自动在末尾追加独立术语解释与指标定义附录页(涵盖审批决策与五类裁决、人机一致性与极性、KaTeX 量化公式、`recordId` 与 `SN` 双主键规范);
- 原始报告 Markdown 保持干净不被侵入修改;PDF 在打印时拥有独立的物理分页隔离(`page-break-before: always`);
- 若特定简报场景不需要附录页,可在 `report render` 或 `report export` 中指定 `--no-glossary` 参数跳过追加。
+5 -2
View File
@@ -78,10 +78,12 @@ export async function handleLocalReportCommand(action: string | undefined, args:
}
const out = stringOption(args.options.out) ?? stringOption(args.options.o);
if (!out) throw usageError(`Usage: seal-use report ${action} <报告文件.md> --out <${action === "export" ? "目标文件夹" : "产物路径词干"}>`);
const glossary = args.options["no-glossary"] ? false : booleanOption(args.options.glossary) ?? true;
if (action === "export") {
const result = await exportReportPackage(file, {
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
glossary
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成完整导出包。请按 validation.issues 修正后重试。", 1);
@@ -89,7 +91,8 @@ export async function handleLocalReportCommand(action: string | undefined, args:
}
const result = await renderReportFile(file, {
out, format: stringOption(args.options.format), width: numberOption(args.options.width),
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite)
chrome: stringOption(args.options.chrome), overwrite: booleanOption(args.options.overwrite),
glossary
});
printJson(result, outputOptions(args.options));
if (!result.validation.valid) throw new CliError("报告校验未通过,未生成渲染产物。请按 validation.issues 修正后重试。", 1);
+2
View File
@@ -706,6 +706,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--format <format>", description: "all (default), html, png, or pdf; PNG/PDF also produce HTML" },
{ flag: "--width <px>", description: "PNG viewport width, default 1200 (320–5000)" },
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
{ flag: "--no-glossary", description: "Omit the trailing terms definition and calculation standards appendix" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files after successful rendering" }
],
description: "No enterprise login. Validation failure produces JSON issues and no artifacts. Validation and HTML use the bundled runtime; PNG/PDF need Chrome/Chromium. No Python or Pillow required. First use of math fetches and caches KaTeX resources. Markdown parsing is bundled, with no runtime npm/npx dependency."
@@ -719,6 +720,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--format <format>", description: "all (default), html, or pdf" },
{ flag: "--width <px>", description: "PNG viewport width, default 1200" },
{ flag: "--chrome <executable>", description: "Chrome/Chromium executable; otherwise auto-detected" },
{ flag: "--no-glossary", description: "Omit the trailing terms definition and calculation standards appendix" },
{ flag: "--overwrite", description: "Explicitly permit replacing existing output files" }
],
description: "Bundles the report into a clean single directory: includes the Markdown with its .md.assets/ companion folder, plus self-contained HTML and print-ready PDF."
+4 -4
View File
@@ -27,9 +27,9 @@ export const BOOLEAN_FLAGS = new Set([
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
@@ -102,7 +102,7 @@ export const KNOWN_FLAGS = new Set([
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expires-in", "expiresIn", "f", "fail-on-flips",
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-id", "flow-ids", "flow-status-list",
"flowId", "flowIds", "flowStatusList", "force", "format", "from", "from-link",
"full", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"full", "glossary", "h", "has-input", "has-output", "help", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso",
"host", "human", "human-accuracy", "humanAccuracy", "humanResult", "id", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"includeBridge", "includeSimulation", "includeUnchanged", "input", "integration", "json",
"json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit", "lines",
@@ -110,7 +110,7 @@ export const KNOWN_FLAGS = new Set([
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
"max-runs",
"month",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-wait", "noWait", "node-id", "nodeId",
"n", "name", "name-contains", "no-attachments", "no-flow", "no-glossary", "no-wait", "noWait", "node-id", "nodeId",
"note", "observation-id", "observation-types", "o", "offset", "out", "out-dir", "outDir", "outbound",
"outgoing-result-webhook", "outgoingResultWebhook", "output", "output-file", "outputFile", "overwrite",
"p", "package-id", "package-ids", "packageId", "packageIds", "path",
@@ -122,6 +122,15 @@ describe("local report CLI", () => {
expect(html).not.toContain("file://");
expect(html).not.toContain("cdn.jsdelivr");
expect(html).toContain("测试企业");
expect(html).toContain('<section class="report-glossary-page">');
expect(html).toContain("附录:核心术语与指标定义规范");
const outNoGlossary = join(dir, "build", "无附录");
const resultNoGlossary = await runCli(["report", "render", file, "--out", outNoGlossary, "--format", "html", "--no-glossary", "--chrome", join(dir, "absent")]);
expect(resultNoGlossary.exitCode).toBe(0);
const htmlNoGlossary = readFileSync(outNoGlossary + ".html", "utf8");
expect(htmlNoGlossary).not.toContain('<section class="report-glossary-page">');
expect(htmlNoGlossary).not.toContain("附录:核心术语与指标定义规范");
});
test("failed validation prevents rendering and returns issues without creating outputs", async () => {
@@ -199,6 +208,7 @@ describe("local report CLI", () => {
expect(existsSync(join(packageDir, "报告.md.assets"))).toBe(true);
expect(existsSync(join(packageDir, "报告.md.assets", "1-chart.svg"))).toBe(true);
expect(existsSync(join(packageDir, "报告.html"))).toBe(true);
expect(readFileSync(join(packageDir, "报告.html"), "utf8")).toContain('<section class="report-glossary-page">');
});
test("export packages companion 4x PNGs for vector SVGs when Chrome is available", async () => {
+5 -2
View File
@@ -14,6 +14,7 @@ export type ReportRenderOptions = {
width?: number;
chrome?: string;
overwrite?: boolean;
glossary?: boolean;
};
function inputFile(file: string): string {
@@ -101,7 +102,7 @@ export async function renderReportFile(file: string, options: ReportRenderOption
const stage = mkdtempSync(join(tmpdir(), "seal-report-render-"))
try {
const html = join(stage, "report.html")
writeFileSync(html, await buildReportHtml(path))
writeFileSync(html, await buildReportHtml(path, { glossary: options.glossary !== false }))
if (binary) {
const profile = join(stage, "browser-profile")
mkdirSync(profile, { mode: 0o700 })
@@ -132,6 +133,7 @@ export type ReportPackageOptions = {
width?: number;
chrome?: string;
overwrite?: boolean;
glossary?: boolean;
};
/**
@@ -156,7 +158,8 @@ export async function exportReportPackage(file: string, options: ReportPackageOp
format: options.format ?? "all",
width: options.width,
chrome: options.chrome,
overwrite: options.overwrite
overwrite: options.overwrite,
glossary: options.glossary
});
// 当处于全量或图片导出模式时,为伴生资产目录中的矢量 SVG 自动增补 4x Retina 超高清 PNG 原图
@@ -0,0 +1,54 @@
/**
* 审核报告核心术语与计算口径定义规范(附录解释页)。
* 作为 HTML、PDF、长图 PNG 渲染产物末尾的独立解释页面,帮助管理层、审计部门与业务团队统一理解报告指标。
* 独立于报告原始 Markdown 之外,由渲染流水线自动追加,无须用户手动编写模板片段。
*/
export const REPORT_GLOSSARY_MARKDOWN = `
<!-- section:glossary-appendix -->
<section class="report-glossary-page">
## 附录:核心术语与指标定义规范
为确保管理层、审计部门与业务团队对报告评估口径达成一致理解,本附录定义报告中涉及的专业术语、人机决策极性、统计指标与标识主键。
### 一、 审批决策与五类复核裁决
| 概念分类 | 术语名称 | 定义与事实认定标准 | 适用场景与边界说明 |
| :--- | :--- | :--- | :--- |
| **线上审批动作** | **AI 审批决策** | 线上业务流水线中,AI 模型基于企业预设规则给出的自动化决策(\`同意\` / \`驳回\` / \`违规拦截\`)。 | 反映模型当时的线上运行记录,不自动代表事实真理。 |
| **线上审批动作** | **人工审批结论** | 业务单据流转中,企业审批人在系统后台实际执行的最终处理结果(\`同意\` / \`驳回\` / \`终止\`)。 | 反映企业实际操作事实,可能包含历史特批、人为疏漏或操作误判。 |
| **事后复核裁决** | **\`ai_correct\`<br>AI正确 / 人工错误** | 制度规则明确,单据客观违规或合规,AI 依规判定准确;人工存在漏审、违规放行或误驳回。 | 证明 AI 规则执行严格,人工初审存在风险或误操作。 |
| **事后复核裁决** | **\`human_correct\`<br>人工正确 / AI误判** | AI 因长尾语义理解不全、格式特殊或规则盲区误判;人工按实际真实业务事实处置正确。 | 明确属于规则或模型缺陷,应纳入规则优化与回归测试样本池。 |
| **事后复核裁决** | **\`both_correct\`<br>双方均正确** | 双方基于不同合法口径均成立:AI 严格按线上现行规则校验正确,人工依据线下特批或特有制度豁免放行。 | 需明确评价标准;通常反映线上规则尚未覆盖最新线下特批制度。 |
| **事后复核裁决** | **\`both_wrong\`<br>双方均误判** | 双方均未识别出单据的隐蔽违规(如关联方交易违规),或均误读了制度条款导致处理失准。 | 需同时对 AI 规则库与人工审批作业规范进行同步整改。 |
| **事后复核裁决** | **\`undecided\`<br>存疑待定** | 因缺失核心原始凭证、有效特批待提供或业务争议,尚无法形成最终定性裁决结论。 | 需后续补充材料;前置门禁允许通过,但在统计分母中保留且不虚增正确分子。 |
### 二、 人机一致性与决策极性
- **决策极性 (Polarity)**:单据在决策空间中的方向属性。\`同意\` / \`通过\` / \`APPROVE\` 归类为正向放行(Positive);\`驳回\` / \`拒绝\` / \`终止\` / \`REJECT\` 归类为负向拦截(Negative)。
- **同向一致 (Agreed)**:AI 审批决策与人工审批结论的极性完全相同。在未逐笔覆盖人工复核裁决时,统计口径默认假设双方判断均正确。
- **人机分歧 (Diverged)**:AI 审批决策与人工审批结论的极性相反(即“AI驳回且人工同意”或“AI同意且人工驳回”)。属于报告核心争议分析池,要求 100% 逐单核查定性。
### 三、 核心量化指标与计算公式
- **AI 审核准确率 (AI Accuracy)**:
依规判定正确单数占样本总量的百分比。
$$\\text{AI 审核准确率} = \\frac{\\text{AI 判定正确单数}}{\\text{样本总量}} \\times 100\\% = \\frac{\\text{ai\\_correct} + \\text{both\\_correct} + \\text{未覆盖同向一致单}}{\\text{样本总量}} \\times 100\\%$$
- **人工审核准确率 (Human Accuracy)**:
人工判定正确单数占已复核样本总量的百分比(仅在存在人工裁决样本时披露)。
$$\\text{人工审核准确率} = \\frac{\\text{人工判定正确单数}}{\\text{复核样本总量}} \\times 100\\% = \\frac{\\text{human\\_correct} + \\text{both\\_correct} + \\text{未覆盖同向一致单}}{\\text{复核样本总量}} \\times 100\\%$$
- **AI 额外风险拦截 (Risk Interception)**:
指在人机分歧单据中,AI 敏锐识别出违规并实施拦截(\`aiDecision=reject\`),人工初审出现遗漏放行(\`humanResult=pass\`),且经事后业务核实判定 AI 正确(\`verdict=ai_correct\`)的真实风险拦截单量。
- **自动化审批率 (Automation Rate)**:
单据完全由 AI 模型依规放行且无需人工审批流介入的比例。
- **平均审核耗时 (Average Duration)**:
单据进入审核流水线至模型输出完整判定意见的全生命周期平均耗时(秒)。
### 四、 单据双主键标识规范
- **审核ID (\`recordId\`)**:单次 AI 审核运行的全局唯一实例主键(如 \`run-xxxx\`)。同一业务单据若多次提交或重跑,每次运行产生唯一的 \`recordId\`。复核裁决与台账关联优先以 \`recordId\` 为绝对主键精确锁定版本。
- **单据编号 (\`SN\`)**:业务源系统中的单据业务自然键(如 \`CL202608001\`)。用于业务人员在原业务系统中反向检索原单及沟通核对。当台账缺少 \`recordId\` 时,系统自动回退兼容按 \`SN\` 关联。
</section>
`.trim();
+37 -5
View File
@@ -24,7 +24,7 @@ function source(content: string) {
describe("native report HTML", () => {
test("preserves code escaping and leaves code examples and escaped dollars out of math rendering", async () => {
globalThis.fetch = Object.assign(async () => { throw new Error("must not fetch") }, { preconnect: originalFetch.preconnect })
const html = await buildReportHtml(source('# Title\n\n```text\n<img src="missing.png">\n$example$\n```\n\n\\$5\n'))
const html = await buildReportHtml(source('# Title\n\n```text\n<img src="missing.png">\n$example$\n```\n\n\\$5\n'), { glossary: false })
expect(html).toContain("&lt;img")
expect(html).toContain("$example$")
expect(html).not.toContain("renderMathInElement")
@@ -37,7 +37,7 @@ describe("native report HTML", () => {
return new Response(url.endsWith("katex.min.css") ? ".katex{src:url(fonts/Mock.woff2)}" : "fixture")
}, { preconnect: originalFetch.preconnect })
const file = source("# Math\n\n$a_b < c$\n\n$$\\frac{100}{100} = 100\\%$$\n")
const html = await buildReportHtml(file)
const html = await buildReportHtml(file, { glossary: false })
expect(html).toContain("a_b &lt; c")
expect(html).not.toContain("<em>")
expect(html).toContain("\\displaystyle \\frac{100}{100} = 100\\%")
@@ -47,15 +47,47 @@ describe("native report HTML", () => {
expect(html).not.toContain("cdn.jsdelivr")
expect(calls).toHaveLength(4)
globalThis.fetch = Object.assign(async () => { throw new Error("offline cache miss") }, { preconnect: originalFetch.preconnect })
expect(await buildReportHtml(file)).toBe(html)
expect(await buildReportHtml(file, { glossary: false })).toBe(html)
})
test("failed formula downloads produce domain errors instead of an incomplete HTML", async () => {
globalThis.fetch = Object.assign(async () => new Response("not found", { status: 404 }), { preconnect: originalFetch.preconnect })
await expect(buildReportHtml(source("# Math\n\n$x$"))).rejects.toMatchObject({ exitCode: 1 })
await expect(buildReportHtml(source("# Math\n\n$x$"), { glossary: false })).rejects.toMatchObject({ exitCode: 1 })
})
test("percent-encoded literal entity names are decoded only once", async () => {
const file = source("# Image\n\n![image](%26amp%3B.svg)")
writeFileSync(join(dirname(file), "&amp;.svg"), '<svg xmlns="http://www.w3.org/2000/svg"></svg>')
expect(await buildReportHtml(file)).toContain("data:image/svg+xml;base64,")
expect(await buildReportHtml(file, { glossary: false })).toContain("data:image/svg+xml;base64,")
})
test("appends terms glossary appendix by default and respects glossary: false", async () => {
globalThis.fetch = Object.assign(async (input: string | URL | Request) => {
const url = String(input)
return new Response(url.endsWith("katex.min.css") ? ".katex{src:url(fonts/Mock.woff2)}" : "fixture")
}, { preconnect: originalFetch.preconnect })
const file = source("# Sample Report\n\nSome content\n")
const defaultHtml = await buildReportHtml(file)
expect(defaultHtml).toContain('<section class="report-glossary-page">')
expect(defaultHtml).toContain("附录:核心术语与指标定义规范")
expect(defaultHtml).toContain("审批决策与五类复核裁决")
expect(defaultHtml).toContain("人机一致性与决策极性")
expect(defaultHtml).toContain("核心量化指标与计算公式")
expect(defaultHtml).toContain("单据双主键标识规范")
expect(defaultHtml).toContain("ai_correct")
expect(defaultHtml).toContain("recordId")
const noGlossaryHtml = await buildReportHtml(file, { glossary: false })
expect(noGlossaryHtml).not.toContain('<section class="report-glossary-page">')
expect(noGlossaryHtml).not.toContain("附录:核心术语与指标定义规范")
})
test("does not duplicate glossary if already present in markdown", async () => {
globalThis.fetch = Object.assign(async (input: string | URL | Request) => {
const url = String(input)
return new Response(url.endsWith("katex.min.css") ? ".katex{src:url(fonts/Mock.woff2)}" : "fixture")
}, { preconnect: originalFetch.preconnect })
const file = source("# Report\n\n<!-- section:glossary-appendix -->\nExisting glossary")
const html = await buildReportHtml(file)
const occurrences = html.split("section:glossary-appendix").length - 1
expect(occurrences).toBe(1)
})
})
+18 -3
View File
@@ -5,6 +5,7 @@ import { basename, dirname, extname, join, resolve } from "node:path"
import { Marked, type TokenizerExtension, type Tokens } from "marked"
import { CliError } from "../../../../core/errors.js"
import { REPORT_CSS } from "../templates/resources.js"
import { REPORT_GLOSSARY_MARKDOWN } from "./glossary.js"
const katexBase = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/"
const mimeTypes: Record<string, string> = {
@@ -20,7 +21,7 @@ function decodeHtml(text: string) {
return text.replace(/&(?:amp|lt|gt|quot|apos|#\d+|#x[\da-f]+);/gi, (entity) => {
if (entity.startsWith("&#")) {
const number = entity.toLowerCase().startsWith("&#x") ? parseInt(entity.slice(3, -1), 16) : Number(entity.slice(2, -1))
return number > 0 && number <= 0x10ffff ? String.fromCodePoint(number) : "�"
return number > 0 && number <= 0x10ffff ? String.fromCodePoint(number) : ""
}
return ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"', "&apos;": "'" })[entity.toLowerCase()] ?? entity
})
@@ -63,9 +64,23 @@ async function mathAssets(): Promise<{ styles: string; scripts: string }> {
return { styles: `<style>${css}</style>\n`, scripts: scripts.join("\n") }
}
export type BuildReportHtmlOptions = {
glossary?: boolean;
};
/** 渲染完整 HTML;标题取自正文 H1,并剥掉可能夹在里面的 HTML 注释。 */
export async function buildReportHtml(file: string): Promise<string> {
const text = readFileSync(file, "utf8").replace(/\r\n?/g, "\n")
export async function buildReportHtml(
file: string,
options: BuildReportHtmlOptions = {}
): Promise<string> {
let text = readFileSync(file, "utf8").replace(/\r\n?/g, "\n")
const shouldAppendGlossary =
options.glossary !== false &&
!text.includes("<!-- section:glossary-appendix -->") &&
!text.includes("附录:核心术语与指标定义规范")
if (shouldAppendGlossary) {
text = `${text}\n\n${REPORT_GLOSSARY_MARKDOWN}\n`
}
let hasMath = false
const math: TokenizerExtension = {
name: "reportMath", level: "inline", start: (source) => source.indexOf("$"),
+1
View File
@@ -1,3 +1,4 @@
export * from "./browser.js";
export * from "./html.js";
export * from "./png.js";
export * from "./glossary.js";
@@ -24,10 +24,13 @@ em { color:var(--muted); font-size:14px; }
hr { border:0; border-top:1px solid var(--line); margin:32px 0; }
a { color:#0969da; }
.katex-display { margin:18px 0; }
.report-glossary-page { margin-top:48px; padding-top:24px; border-top:2px dashed var(--line); page-break-before:always; break-before:page; }
.report-glossary-page h2 { margin-top:0; }
@page { size: A4; margin: 14mm 12mm; }
@media print {
body { max-width:none; padding:0; font-size:12pt; }
h2, h3 { page-break-after:avoid; break-after:avoid; }
tr, img, blockquote { page-break-inside:avoid; break-inside:avoid; }
thead { display:table-header-group; }
.report-glossary-page { margin-top:0; padding-top:0; border-top:none; page-break-before:always; break-before:page; }
}