فهرست منبع

merge: 保留云端核验修复并整合海关工具增强版本

ly 4 روز پیش
والد
کامیت
040cb64560
41فایلهای تغییر یافته به همراه1519 افزوده شده و 252 حذف شده
  1. 4 3
      README.md
  2. 3 2
      agent.cordis.yml
  3. 13 0
      bff/dist/src/store/ledger.js
  4. 0 0
      bff/dist/src/store/ledger.js.map
  5. 53 32
      bff/dist/src/verify/extract.js
  6. 0 0
      bff/dist/src/verify/extract.js.map
  7. 73 54
      bff/dist/src/verify/verify.js
  8. 0 0
      bff/dist/src/verify/verify.js.map
  9. 18 0
      bff/dist/test/extract.test.js
  10. 0 0
      bff/dist/test/extract.test.js.map
  11. 80 7
      bff/dist/test/verify.test.js
  12. 0 0
      bff/dist/test/verify.test.js.map
  13. 19 0
      bff/src/store/ledger.ts
  14. 71 35
      bff/src/verify/extract.ts
  15. 129 78
      bff/src/verify/verify.ts
  16. 24 1
      bff/test/extract.test.ts
  17. 623 0
      bff/test/fixtures/answer-medium.ledger.json
  18. 59 0
      bff/test/fixtures/answer-medium.txt
  19. 89 8
      bff/test/verify.test.ts
  20. 22 8
      docs/01-架构设计.md
  21. 24 0
      docs/02-实现说明.md
  22. 3 2
      docs/03-使用手册.md
  23. 49 5
      docs/05-测试报告.md
  24. 5 1
      docs/06-工具增强与演示交付.md
  25. BIN
      docs/images/01-chat.png
  26. BIN
      docs/images/02-process.png
  27. BIN
      docs/images/03-files.png
  28. BIN
      docs/images/04-system.png
  29. BIN
      docs/images/05-trace-drawer.png
  30. BIN
      docs/images/06-row-jump.png
  31. 45 1
      scripts/ui_probe.mjs
  32. 52 0
      scripts/verify_probe.mjs
  33. 0 0
      web/dist/assets/index-CR3nqj6D.css
  34. 0 0
      web/dist/assets/index-Cl9HL7vR.js
  35. 0 0
      web/dist/assets/index-DlGlAdTE.js
  36. 2 2
      web/dist/index.html
  37. 13 2
      web/src/api/types.ts
  38. 28 4
      web/src/components/ChatMessageView.tsx
  39. 6 3
      web/src/components/TraceDrawer.tsx
  40. 5 0
      web/src/styles/app.css
  41. 7 4
      web/test/render.test.tsx

+ 4 - 3
README.md

@@ -77,7 +77,7 @@ CustomesDataAgent/
 │  ├─ src/verify/              #   输出核验层:数字抽取 + 台账反查 + 裁决
 │  ├─ src/routes/              #   工作区/文件/处理/会话/对话(SSE)/系统
 │  ├─ src/store/               #   sqlite:会话、消息、会话台账
-│  └─ test/                    #   58 项单元与接口测试
+│  └─ test/                    #   65 项单元与接口测试
 ├─ tools-service/              # Python 工具执行服务
 │  ├─ toolsvc/customs/         # ★ 可替换的数据处理模块(契约 + engine + rules/)
 │  ├─ toolsvc/objects.py       #   对象库、原始数据索引、行级血缘
@@ -113,7 +113,7 @@ CustomesDataAgent/
 | 测试组 | 数量 | 命令 |
 |---|---|---|
 | Python 引擎与接口(pytest) | 85 | `cd tools-service && python -m pytest tests/` |
-| BFF 单元与接口(node:test) | 58 | `cd bff && npm run build && node --test "dist/test/*.test.js"` |
+| BFF 单元与接口(node:test) | 65 | `cd bff && npm run build && node --test "dist/test/*.test.js"` |
 | 前端单元 + 渲染(vitest) | 27 | `cd web && npx vitest run` |
 | 端到端联调(真实服务 + 真实模型) | 33 项检查 | `node scripts/e2e.mjs` |
 | 真实浏览器交互(CDP 点击 + 截图) | 3 步断言 + 6 张截图 | `node scripts/ui_probe.mjs` |
@@ -124,7 +124,8 @@ CustomesDataAgent/
 powershell -NoProfile -ExecutionPolicy Bypass -File scripts\run_tests.ps1
 ```
 
-另有**真实浏览器交互探针** `node scripts/ui_probe.mjs`(用 CDP 点开 chip、跳转高亮、逐页截图),产物在 `.run/ui/`。
+另有**真实浏览器交互探针** `node scripts/ui_probe.mjs`(用 CDP 点开 chip、跳转高亮、逐页截图),产物在 `.run/ui/`;
+以及**核验取证工具** `node scripts/verify_probe.mjs <答案文件>`(打印每个候选数字的类别与判定,改规则前先看它)。
 
 结果见 [docs/05-测试报告.md](docs/05-测试报告.md)。
 

+ 3 - 2
agent.cordis.yml

@@ -1,4 +1,4 @@
-# =============================================================================
+# =============================================================================
 # 海关问数 Agent · Agent Preset
 # -----------------------------------------------------------------------------
 # 这是整个系统的"人格 + 能力边界"定义,由 BFF 的 harness 运行时加载。
@@ -60,7 +60,8 @@ systemPrompt: |
   4. `calculator`:做算术与统计(sum/mean/growth/ratio/index/share/expression)。**任何需要加减乘除的结论都必须经过它。**
 
   ## 铁律(违反即视为错误答案)
-  - 严禁编造、估算、心算任何数字。答案里出现的每一个金额、数量、百分比、指数,都必须原样来自本轮或之前轮次的工具返回值。
+  - 严禁编造、估算、心算任何数字。答案里出现的每一个**金额、百分比、指数、数量级数据**,都必须原样来自本轮或之前轮次的工具返回值。
+    核验层只审这类数据;表号(如 4.2.1_MLCC)、章节号、年份、序号不属于数据断言,可以自由引用。
   - 严禁自己推算"约等于"或"大概是"。需要换算时必须调用 `calculator`,并把输入值的 `from_call_id` / `row_hash` 一并传进去,让核验层可以追溯。
   - 严禁把多张不同口径的表直接相加。`金额占比`/`数量占比` 的分母写在 `占比分母范围` 列,跨层级不可求和。
   - 对标有“已遮掩”的数据,金额或数量可能是区间字符串:仅能原样说明该区间,不可取中点、补出精确值或混入合成演示数据。仅回答用户所问指标,区间保留原始单位,不附加换算、四舍五入的占比或无关数字。原始申报明细未提供时须如实说明。

+ 13 - 0
bff/dist/src/store/ledger.js

@@ -101,6 +101,19 @@ export class SessionLedger {
         return this.db.all(`SELECT field,value_text,value_num,row_index,table_name,object_id FROM ledger_values
        WHERE call_id=? ORDER BY rowid LIMIT ?`, callId, limit);
     }
+    /**
+     * 近似反查:用于"四舍五入"与"单位换算"。
+     * 相对容差默认 2e-4(0.02%),并给绝对值留 0.006 的下限(两位小数舍入)。
+     */
+    findValueApprox(value, sessionId, relTolerance = 2e-4) {
+        if (!Number.isFinite(value))
+            return [];
+        const epsilon = Math.max(Math.abs(value) * relTolerance, 0.006);
+        return this.db.all(`SELECT call_id,object_id,table_name,row_index,field,value_text,value_num
+       FROM ledger_values
+       WHERE session_id=? AND value_num IS NOT NULL AND ABS(value_num - ?) <= ?
+       ORDER BY ABS(value_num - ?) ASC LIMIT 5`, sessionId, value, epsilon, value);
+    }
     callsOf(sessionId) {
         return this.db.all(`SELECT call_id,tool,args_hash,result_hash,row_count,object_ids,created_at
        FROM ledger_calls WHERE session_id=? ORDER BY created_at`, sessionId);

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
bff/dist/src/store/ledger.js.map


+ 53 - 32
bff/dist/src/verify/extract.js

@@ -1,26 +1,27 @@
+const NUMBER_PATTERN = /(?<![\w.])([-−-]?)(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)(?:\s*(万|亿|千))?(\s*%)?/g;
 const CN_UNITS = { 万: 1e4, 亿: 1e8, 千: 1e3 };
-/** 明显不是"数据断言"的数字:序号、日期片段等(年份保留,由核验标注为豁免)。 */
-function isIgnorable(claim, text) {
-    const before = text.slice(Math.max(0, claim.start - 12), claim.start);
-    if (/(第|No\.?|#|序号)\s*$/i.test(before))
-        return true;
-    return false;
-}
-const NUMBER_PATTERN = /(?<![\w.])(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)(?:\s*(万|亿|千))?(\s*%)?/g;
 /**
- * 报表名/代次这类"结构性标识"里也有数字,但它们不是数据断言。
- * 抽取前先把这些片段遮成空格(保持长度与偏移不变),避免把 `4.2.3 (1-4)_MLCC`
- * 拆成 4.2 / 3 / 1 / 4 然后误判为"无来源数字"。
+ * 结构性标识:抽取前遮成等长空格(保持偏移不变)。
+ * 覆盖:报表名、`.x` 版本号、三段以上版本号、区间、代次、行首序号、序数词。
  */
 const STRUCTURAL_PATTERNS = [
-    // 4.2.3 (1-4)_MLCC / 1.0-3.0_MLCC / 5.2.1&3&5_存储器
-    /\d+(?:\.\d+)+(?:[-&]\d+(?:\.\d+)*)*(?:\s*\(\d+(?:\s*-\s*\d+)?\))?\s*_[A-Za-z\u4e00-\u9fff]+/g,
-    // 单独的 1.0-3.0 这类区间
-    /\d+(?:\.\d+)+-\d+(?:\.\d+)+/g,
+    // 4.2.3 (1-4)_MLCC / 1.0-3.0_MLCC / 5.2.1&3&5_存储器 / 4.1_MLCC
+    /\d+(?:\.\d+)+(?:[-&–]\d+(?:\.\d+)*)*(?:\s*\(\d+(?:\s*[-–]\s*\d+)?\))?\s*_[A-Za-z\u4e00-\u9fff]+/g,
+    // 4.2.x / 5.2.x
+    /\d+(?:\.\d+)+\.?[xX](?![\w])/g,
+    // 1.0-3.0 / 2025-01 / 1–8 这类区间与年月
+    /\d+(?:\.\d+)?\s*[-–~]\s*\d+(?:\.\d+)?/g,
+    // 三段及以上版本号(4.2.3、5.2.1)—— 本业务的数据值不会出现两个小数点
+    /\d+(?:\.\d+){2,}/g,
     // DDR3 / DDR4 / DDR5 / LPDDR4
     /\b(?:LP)?DDR[345]\b/gi,
+    // 行首列表序号 "1." "2)" "3、"
+    /^[ \t]*\d+[.)、](?=\s)/gm,
+    // "第 3 名 / 第 55 行 / 第 5 节"
+    /第\s*\d+\s*(?:名|位|大|条|行|章|节|部分|步|个)/g,
 ];
-function maskStructural(text) {
+/** 抽取前把结构标记遮掉,返回遮罩后的文本(长度与原文一致)。 */
+export function maskStructural(text) {
     let masked = text;
     for (const pattern of STRUCTURAL_PATTERNS) {
         masked = masked.replace(pattern, (match) => ' '.repeat(match.length));
@@ -28,20 +29,21 @@ function maskStructural(text) {
     return masked;
 }
 /**
- * 抽取数字。返回去重后的 claim 列表(按出现顺序)。
+ * 抽取数字。返回带 severity / structural 的 claim 列表(按出现顺序、按展示值去重)。
  */
 export function extractNumericClaims(text) {
     const claims = [];
     const seen = new Set();
-    // 在"遮掉结构性标识"的副本上跑正则,context 仍取原文
     const masked = maskStructural(text);
     NUMBER_PATTERN.lastIndex = 0;
     let match;
     while ((match = NUMBER_PATTERN.exec(masked)) !== null) {
-        const [raw, numberText, unit, percent] = match;
+        const [raw, sign, numberText, unit, percent] = match;
         const start = match.index;
         const end = start + raw.length;
-        const clean = numberText.replace(/,/g, '');
+        // 负号必须保留:金额环比/增长率为负很常见,丢符号会导致台账查不到
+        const negative = sign === '-' || sign === '−' || sign === '-';
+        const clean = `${negative ? '-' : ''}${numberText.replace(/,/g, '')}`;
         let value = Number(clean);
         if (!Number.isFinite(value))
             continue;
@@ -54,9 +56,8 @@ export function extractNumericClaims(text) {
             value = value * CN_UNITS[unit];
             kind = 'money';
         }
-        // 类型判断(用于报告与排除规则)
-        const before = text.slice(Math.max(0, start - 10), start);
-        const after = text.slice(end, end + 10);
+        const before = text.slice(Math.max(0, start - 12), start);
+        const after = text.slice(end, end + 12);
         if (!percent && !unit) {
             if (/^-?\d{4}$/.test(clean) && Number(clean) >= 1900 && Number(clean) <= 2100) {
                 kind = 'year';
@@ -64,36 +65,56 @@ export function extractNumericClaims(text) {
             else if (/^\d{10}$/.test(clean) || (/^\d{8}$/.test(clean) && /HS|hs|编码/.test(before))) {
                 kind = 'code';
             }
-            else if (/美元|USD|\$|万元|万美元/.test(before + after)) {
+            else if (/美元|USD|\$|万元|万美元|亿元/.test(before + after)) {
                 kind = 'money';
             }
-            else if (/个|件|只|片|颗|吨|千克|数量/.test(after)) {
+            else if (/个|件|只|片|颗|吨|千克|数量|条记录/.test(after)) {
                 kind = 'quantity';
             }
-            else if (/指数|点/.test(after)) {
+            else if (/指数|点位/.test(before) || /^\s*点/.test(after)) {
+                // 只看"数字前面是不是指数标签":`728 | 价格指数…` 里的 728 是行数,不是指数
                 kind = 'index';
             }
         }
+        const decimals = clean.includes('.') ? clean.split('.')[1].length : 0;
+        // 政策常数("10% 封顶""100%")与整数百分比:属于口径描述,不当数据断言
+        const policyPercent = kind === 'percent' &&
+            (decimals === 0 || /上限|封顶|阈值|规则|不超过|不低于|至少|至多|权重上限/.test(before + after));
         const claim = {
             raw: raw.trim(),
             value,
             rawNumber: clean,
-            display: `${percent ? clean + '%' : clean}${unit ?? ''}`,
+            display: `${percent ? `${clean}%` : clean}${unit ?? ''}`,
             kind,
+            severity: policyPercent ? 'soft' : decideSeverity(kind, value, decimals),
+            structural: kind === 'year' || policyPercent,
             start,
             end,
             context: text.slice(Math.max(0, start - 16), Math.min(text.length, end + 16)),
         };
-        if (isIgnorable(claim, text))
-            continue;
-        const key = `${claim.display}`;
-        if (seen.has(key))
+        if (seen.has(claim.display))
             continue;
-        seen.add(key);
+        seen.add(claim.display);
         claims.push(claim);
     }
     return claims;
 }
+/**
+ * 该不该审:
+ * * 金额 / 百分比 / 指数 / 10 位 HS 编码 → 一定审;
+ * * 数量 ≥ 1000 → 审(小数量通常是"3 个类别"这类结构描述);
+ * * 十进制小数 ≥ 2 位 → 审(金额、占比、增长率这类测量值);
+ * * 其余裸整数 → 只做"能溯源就标记",不拦。
+ */
+function decideSeverity(kind, value, decimals) {
+    if (kind === 'money' || kind === 'percent' || kind === 'index' || kind === 'code')
+        return 'strict';
+    if (kind === 'quantity')
+        return Math.abs(value) >= 1000 ? 'strict' : 'soft';
+    if (!Number.isInteger(value) && decimals >= 2)
+        return 'strict';
+    return 'soft';
+}
 /** 判断数字附近是否明确标注了"约 / 估算 / 大约"等不确定措辞。 */
 export function isMarkedAsEstimate(claim) {
     return /(约|大约|左右|估算|估计|近似|大概|roughly|approx\.?|about|~)/i.test(claim.context);

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
bff/dist/src/verify/extract.js.map


+ 73 - 54
bff/dist/src/verify/verify.js

@@ -1,5 +1,5 @@
 import { extractNumericClaims, isMarkedAsEstimate } from './extract.js';
-/** 文本里出现过的数字(用户问题、表名等)——引用它们不算编造。 */
+/** 文本里出现过的数字(用户问题)——引用它们不算编造。 */
 function buildExemptions(texts) {
     const exempt = new Set();
     for (const text of texts) {
@@ -10,7 +10,6 @@ function buildExemptions(texts) {
     return exempt;
 }
 function roundKey(value) {
-    // 保留 9 位有效数字,避免浮点误差导致豁免失效
     return Number(value.toPrecision(9));
 }
 export function verifyAnswer(answer, options) {
@@ -19,47 +18,76 @@ export function verifyAnswer(answer, options) {
     const allowFlag = options.allowEstimateFlag !== false;
     const results = [];
     for (const claim of claims) {
-        if (isExempt(claim, exemptions)) {
-            results.push({ ...base(claim), status: 'exempt', reason: '年份/序号/用户输入中已出现的数字,不作数据断言' });
+        const base = {
+            raw: claim.raw,
+            value: claim.value,
+            display: claim.display,
+            kind: claim.kind,
+            severity: claim.severity,
+            matches: [],
+        };
+        // ① 结构标记与年份:豁免
+        if (claim.structural || claim.kind === 'year') {
+            results.push({ ...base, status: 'exempt', reason: '年份/表号/序号等结构标记,不做数据断言' });
+            continue;
+        }
+        // ② 用户问题里已经出现过:豁免
+        if (exemptions.has(roundKey(claim.value))) {
+            results.push({ ...base, status: 'exempt', reason: '用户问题中出现过的数字,不作数据断言' });
             continue;
         }
-        const matches = options.ledger.findValue(String(claim.value), options.sessionId);
-        if (matches.length > 0) {
-            results.push({ ...base(claim), status: 'verified', matches: matches.map(toChipMatch) });
+        // ③ 精确反查
+        const exact = options.ledger.findValue(String(claim.value), options.sessionId);
+        if (exact.length > 0) {
+            results.push({ ...base, status: 'verified', matches: exact.map(toMatch) });
             continue;
         }
-        // 带单位换算(如 40.0316 万)的数字:只有 calculator 真算过这个数才算有来源
+        // ④ 带单位的数字:原文也可能直接存在于台账(如 40.0316 万)
         if (claim.rawNumber !== String(claim.value)) {
-            const rawMatches = options.ledger.findValue(claim.rawNumber, options.sessionId);
-            if (rawMatches.length > 0) {
-                results.push({ ...base(claim), status: 'verified', matches: rawMatches.map(toChipMatch) });
+            const byRaw = options.ledger.findValue(claim.rawNumber, options.sessionId);
+            if (byRaw.length > 0) {
+                results.push({ ...base, status: 'verified', matches: byRaw.map(toMatch) });
                 continue;
             }
         }
-        // 台账里只有原文(例如百分比按 "21.70%" 存)时,再按显示值查一次
-        const textMatches = options.ledger.findValue(claim.display, options.sessionId);
-        if (textMatches.length > 0) {
-            results.push({ ...base(claim), status: 'verified', matches: textMatches.map(toChipMatch) });
+        // ⑤ 近似反查:四舍五入 / 单位换算
+        const approx = options.ledger.findValueApprox?.(claim.value, options.sessionId) ?? [];
+        if (approx.length > 0) {
+            results.push({
+                ...base,
+                status: 'verified',
+                reason: '与台账数值在四舍五入/换算容差内一致',
+                matches: approx.map(toMatch),
+            });
             continue;
         }
-        if (allowFlag && isMarkedAsEstimate(claim)) {
-            results.push({ ...base(claim), status: 'flagged', reason: '台账中无精确来源,但已明确标注为估算' });
+        // ⑥ 查不到
+        if (allowFlag && claim.severity === 'strict' && isMarkedAsEstimate(claim)) {
+            results.push({ ...base, status: 'flagged', reason: '台账中无精确来源,但已明确标注为估算' });
             continue;
         }
-        results.push({ ...base(claim), status: 'unverified', reason: '台账中找不到该数字的任何来源' });
+        if (claim.severity === 'soft') {
+            results.push({
+                ...base,
+                status: 'reference',
+                reason: '无单位计数/序号类数字,不参与核验(仅提示)',
+            });
+            continue;
+        }
+        results.push({ ...base, status: 'unverified', reason: '台账中找不到该数字的任何来源' });
     }
+    const strictResults = results.filter((item) => item.severity === 'strict' && item.status !== 'exempt');
     const verified = results.filter((item) => item.status === 'verified').length;
     const flagged = results.filter((item) => item.status === 'flagged').length;
     const unverified = results.filter((item) => item.status === 'unverified').length;
     const exempt = results.filter((item) => item.status === 'exempt').length;
+    const reference = results.filter((item) => item.status === 'reference').length;
     let verdict = 'accept';
     if (unverified > 0)
         verdict = 'reject';
     else if (flagged > 0)
         verdict = 'flag';
-    const chips = results
-        .filter((item) => item.status !== 'exempt')
-        .map((item) => {
+    const chips = strictResults.map((item) => {
         const match = item.matches[0];
         return {
             value: String(item.value),
@@ -75,26 +103,27 @@ export function verifyAnswer(answer, options) {
     return {
         verdict,
         claims: results,
+        strictClaims: strictResults,
         verified,
         flagged,
         unverified,
         exempt,
+        reference,
         total: results.length,
-        summary: summarize(verdict, verified, flagged, unverified, exempt),
+        strictTotal: strictResults.length,
+        summary: summarize(verdict, {
+            verified,
+            flagged,
+            unverified,
+            exempt,
+            reference,
+            strictTotal: strictResults.length,
+        }),
         chips,
         checkedAt: new Date().toISOString(),
     };
 }
-function base(claim) {
-    return {
-        raw: claim.raw,
-        value: claim.value,
-        display: claim.display,
-        kind: claim.kind,
-        matches: [],
-    };
-}
-function toChipMatch(match) {
+function toMatch(match) {
     return {
         call_id: match.call_id,
         object_id: match.object_id ?? '',
@@ -105,30 +134,20 @@ function toChipMatch(match) {
         value_num: match.value_num ?? null,
     };
 }
-function isExempt(claim, exemptions) {
-    if (claim.kind === 'year')
-        return true;
-    if (exemptions.has(roundKey(claim.value)))
-        return true;
-    // 结构性小数字(“3 个应用领域”“前十大型号”“前 3 名”)不是数据断言。
-    // 金额/占比/指数不在此列:它们必须逐一到台账里比对。
-    if (claim.kind !== 'money' && claim.kind !== 'percent' && claim.kind !== 'index') {
-        if (Number.isInteger(claim.value) && Math.abs(claim.value) <= 12)
-            return true;
-    }
-    return false;
-}
-function summarize(verdict, verified, flagged, unverified, exempt) {
-    const total = verified + flagged + unverified + exempt;
+function summarize(verdict, counts) {
+    const total = counts.verified + counts.flagged + counts.unverified + counts.exempt + counts.reference;
     if (total === 0)
         return '答案中没有需要核验的数字';
-    const parts = [`共 ${total} 个数字`, `已溯源 ${verified} 个`];
-    if (exempt > 0)
-        parts.push(`豁免 ${exempt} 个(年份/序号等)`);
-    if (flagged > 0)
-        parts.push(`估算 ${flagged} 个`);
-    if (unverified > 0)
-        parts.push(`无来源 ${unverified} 个`);
+    const parts = [`共 ${total} 个数字`, `必审 ${counts.strictTotal} 个`];
+    parts.push(`已溯源 ${counts.verified} 个`);
+    if (counts.exempt > 0)
+        parts.push(`结构标记豁免 ${counts.exempt} 个`);
+    if (counts.reference > 0)
+        parts.push(`参考性计数 ${counts.reference} 个(不拦截)`);
+    if (counts.flagged > 0)
+        parts.push(`估算 ${counts.flagged} 个`);
+    if (counts.unverified > 0)
+        parts.push(`无来源 ${counts.unverified} 个`);
     const head = { accept: '通过', flag: '通过但需提示', reject: '未通过' }[verdict];
     return `${head}:${parts.join(',')}`;
 }

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
bff/dist/src/verify/verify.js.map


+ 18 - 0
bff/dist/test/extract.test.js

@@ -72,4 +72,22 @@ test('报表名里的数字被遮掉,但旁边的真实数据仍能抽出', ()
 test('空文本返回空数组', () => {
     assert.deepEqual(extractNumericClaims('没有任何数字'), []);
 });
+test('负数保留符号(金额环比为负很常见)', () => {
+    const money = extractNumericClaims('金额 -1,234.56 美元');
+    assert.equal(money[0].value, -1234.56);
+    assert.equal(money[0].rawNumber, '-1234.56');
+    const percent = extractNumericClaims('金额环比 -13.30%');
+    assert.equal(percent[0].kind, 'percent');
+    assert.ok(Math.abs(percent[0].value + 0.133) < 1e-12);
+    const ratio = extractNumericClaims('金额环比 -0.4470999746174148352572197863');
+    assert.equal(ratio[0].value, -0.44709997461741485);
+    assert.equal(ratio[0].severity, 'strict');
+    // 全角负号也要认
+    const fullWidth = extractNumericClaims('环比 −13.30%');
+    assert.ok(Math.abs(fullWidth[0].value + 0.133) < 1e-12);
+});
+test('负号不会破坏区间/表号的遮蔽', () => {
+    assert.deepEqual(extractNumericClaims('2025-01 ~ 2026-08 的数据'), []);
+    assert.deepEqual(extractNumericClaims('见 4.2.3 (1-4)_MLCC 表'), []);
+});
 //# sourceMappingURL=extract.test.js.map

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
bff/dist/test/extract.test.js.map


+ 80 - 7
bff/dist/test/verify.test.js

@@ -79,13 +79,14 @@ test('百分比按归一化数值回查', () => {
     const result = verifyAnswer('金额占比为 21.7%。', { ledger, sessionId: 's1' });
     assert.equal(result.verdict, 'accept');
 });
-test('万单位换算:calculator 没算过就是无来源(防止心算)', () => {
-    const ledger = ledgerWith([['400316.13', [match('400316.13')]]]);
-    const rejected = verifyAnswer('进口额 40.0316 万美元。', { ledger, sessionId: 's1' });
-    assert.equal(rejected.verdict, 'reject', '台账只有 400316.13,换算值必须由 calculator 产出');
-    const withCalc = ledgerWith([['40.0316', [match('40.0316', 'result', 'calc_1', -1)]]]);
-    const accepted = verifyAnswer('进口额 40.0316 万美元。', { ledger: withCalc, sessionId: 's1' });
-    assert.equal(accepted.verdict, 'accept');
+test('万单位换算:与台账数值一致即放行,差得远才拦', () => {
+    // 新策略(真实使用反馈后调整):换算只要与真实值在 0.02% 内一致就认,不必强行过 calculator
+    const converted = new FixtureLedger([
+        { call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '实际金额(美元)', value_text: '400316.13', value_num: 400316.13 },
+    ]);
+    assert.equal(verifyAnswer('进口额 40.0316 万美元。', { ledger: converted, sessionId: 's1' }).verdict, 'accept');
+    // 但"约 300 万"这种与原值差 6 倍的说法,必须拦
+    assert.equal(verifyAnswer('进口额 300 万美元。', { ledger: converted, sessionId: 's1' }).verdict, 'reject');
 });
 test('修正提示列出问题数字', () => {
     const ledger = ledgerWith([]);
@@ -99,4 +100,76 @@ test('没有数字的答案直接 accept', () => {
     assert.equal(result.verdict, 'accept');
     assert.equal(result.total, 0);
 });
+// ---------------------------------------------------------------------------
+// 真实答案回归:medium 数据集那份长报告(曾因表号被拦而误拒)
+// ---------------------------------------------------------------------------
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+const FIXTURES = path.resolve(import.meta.dirname, '..', '..', 'test', 'fixtures');
+const ANSWER = readFileSync(path.join(FIXTURES, 'answer-medium.txt'), 'utf8');
+const LEDGER = JSON.parse(readFileSync(path.join(FIXTURES, 'answer-medium.ledger.json'), 'utf8'));
+class FixtureLedger {
+    rows;
+    constructor(rows) {
+        this.rows = rows;
+    }
+    findValue(value) {
+        return this.rows.filter((row) => String(row.value_text) === String(value));
+    }
+    findValueApprox(value) {
+        const epsilon = Math.max(Math.abs(value) * 2e-4, 0.006);
+        return this.rows.filter((row) => Math.abs(Number(row.value_num) - value) <= epsilon);
+    }
+}
+test('真实长报告:表号/序号不再被当成数据(不再误拒)', () => {
+    const result = verifyAnswer(ANSWER, { ledger: new FixtureLedger(LEDGER), sessionId: 's-long' });
+    assert.equal(result.verdict, 'accept', result.summary);
+    assert.equal(result.unverified, 0, JSON.stringify(result.claims.filter((c) => c.status === 'unverified')));
+    // 结构性数字必须全部豁免:表号、章节号、序号、年份、政策常数
+    const raws = result.claims.map((claim) => claim.raw);
+    for (const structural of ['4.2.x', '5.2.1&3&5_存储器', '1.0-3.0_MLCC']) {
+        assert.ok(!raws.includes(structural), `不应把 ${structural} 列为候选数字`);
+    }
+    for (const exempted of ['2025', '2026', '10%']) {
+        const claim = result.claims.find((item) => item.raw === exempted);
+        assert.ok(!claim || claim.status === 'exempt', `${exempted} 不应进入必审集合`);
+    }
+    // 无单位计数(行数/条数)不应参与裁决
+    const reference = result.claims.filter((claim) => claim.status === 'reference').map((claim) => claim.raw);
+    assert.ok(reference.includes('10,571'), '行数应归为参考性计数');
+    assert.ok(reference.includes('728'), '样本权重行数应归为参考性计数');
+});
+test('真实长报告:删掉一条金额就必须拒绝,且精确定位到那一个数字', () => {
+    // 去掉"工业应用 6,246,568.73"这一条(它没有万美元换算的孪生值,最适合验精确拦截)
+    const target = 6246568.73;
+    const broken = LEDGER.filter((row) => Math.abs(Number(row.value_num) - target) > 1);
+    const result = verifyAnswer(ANSWER, { ledger: new FixtureLedger(broken), sessionId: 's-bad' });
+    assert.equal(result.verdict, 'reject');
+    assert.equal(result.unverified, 1, JSON.stringify(result.claims.filter((c) => c.status === 'unverified')));
+    assert.equal(result.claims.find((claim) => claim.status === 'unverified').value, target);
+});
+test('真实长报告:四舍五入的百分比能被容差识别', () => {
+    // 台账存 0.609412,答案写 60.94%
+    const rows = [{ call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '金额占比', value_text: '0.609412', value_num: 0.609412 }];
+    const result = verifyAnswer('DRAM 占存储器金额 60.94%。', { ledger: new FixtureLedger(rows), sessionId: 's-round' });
+    assert.equal(result.verdict, 'accept', result.summary);
+});
+test('真实长报告:万美元换算按数值一致性放行,差几个百分点仍然拦', () => {
+    const rows = [{ call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '实际金额(美元)', value_text: '18166535.27', value_num: 18166535.27 }];
+    const okResult = verifyAnswer('电容器 2026-08 进口额 1,816.65 万美元。', { ledger: new FixtureLedger(rows), sessionId: 's-conv' });
+    assert.equal(okResult.verdict, 'accept', okResult.summary);
+    const badResult = verifyAnswer('电容器 2026-08 进口额 1,900 万美元。', { ledger: new FixtureLedger(rows), sessionId: 's-conv2' });
+    assert.equal(badResult.verdict, 'reject', '差 4.6% 的换算不能被放行');
+    // 同一句话加上"约":按估算放行但高亮
+    const flagged = verifyAnswer('电容器 2026-08 进口额约 1,900 万美元。', { ledger: new FixtureLedger(rows), sessionId: 's-conv3' });
+    assert.equal(flagged.verdict, 'flag');
+});
+test('负数环比:台账里是负值,答案写负值才算一致', () => {
+    const rows = [{ call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '金额环比', value_text: '-0.4470999746174148352572197863', value_num: -0.4470999746174148 }];
+    const ok = verifyAnswer('其他存储器 金额环比 -0.4470999746174148。', { ledger: new FixtureLedger(rows), sessionId: 's-neg' });
+    assert.equal(ok.verdict, 'accept', ok.summary);
+    // 把符号写错(丢负号)必须被拦——这正是初版丢符号导致的误判
+    const wrongSign = verifyAnswer('其他存储器 金额环比 0.4470999746174148。', { ledger: new FixtureLedger(rows), sessionId: 's-neg2' });
+    assert.equal(wrongSign.verdict, 'reject');
+});
 //# sourceMappingURL=verify.test.js.map

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
bff/dist/test/verify.test.js.map


+ 19 - 0
bff/src/store/ledger.ts

@@ -182,6 +182,25 @@ export class SessionLedger {
     );
   }
 
+  /**
+   * 近似反查:用于"四舍五入"与"单位换算"。
+   * 相对容差默认 2e-4(0.02%),并给绝对值留 0.006 的下限(两位小数舍入)。
+   */
+  findValueApprox(value: number, sessionId: string, relTolerance = 2e-4): ValueMatch[] {
+    if (!Number.isFinite(value)) return [];
+    const epsilon = Math.max(Math.abs(value) * relTolerance, 0.006);
+    return this.db.all<ValueMatch>(
+      `SELECT call_id,object_id,table_name,row_index,field,value_text,value_num
+       FROM ledger_values
+       WHERE session_id=? AND value_num IS NOT NULL AND ABS(value_num - ?) <= ?
+       ORDER BY ABS(value_num - ?) ASC LIMIT 5`,
+      sessionId,
+      value,
+      epsilon,
+      value,
+    );
+  }
+
   callsOf(sessionId: string): Array<Record<string, unknown>> {
     return this.db.all(
       `SELECT call_id,tool,args_hash,result_hash,row_count,object_ids,created_at

+ 71 - 35
bff/src/verify/extract.ts

@@ -1,9 +1,21 @@
 /**
- * 从答案文本里抽取"承载数字"(claim)。
+ * 从答案文本里抽取"承载数字",并区分**该审的**与**不该审的**。
  *
- * 纯正则 + 类型规则,不经过模型。这是核验层第一步:
- * 后面要拿这些数字去台账里反查,查不到就不许交付。
+ * 背景(真实反馈):初版把 `4.2.x`、`5.2.1&3&5_存储器` 这类表号、以及"第 3 名"这类序号
+ * 也当成数据去台账里查,查不到就拒绝整条回答。这是错的——核验的目的是防编造**数据**,
+ * 不是防引用**章节号**。
+ *
+ * 因此这里给每个数字打两个标记:
+ *
+ * * `structural`:表号/章节号/版本号/序号等结构标记 → 直接豁免,不参与核验;
+ * * `severity`:
+ *   - `strict`:金额(含万/亿、货币符号)、百分比、指数、带单位的数量(≥1000)、
+ *     十进制小数(≥2 位)、10 位 HS 编码 —— **不溯源就拒绝交付**;
+ *   - `soft`:无单位裸整数(行数、条数、类别个数…)—— 能溯源就标"已溯源",
+ *     不能溯源只记为"结构性数字",**不影响裁决**。
  */
+export type ClaimSeverity = 'strict' | 'soft';
+
 export interface NumericClaim {
   /** 原文片段,如 "2,847,392.15"、"28.5%"、"120万" */
   raw: string;
@@ -14,38 +26,42 @@ export interface NumericClaim {
   /** 展示用数值(百分比保留百分数形态,便于追溯) */
   display: string;
   kind: 'money' | 'quantity' | 'percent' | 'index' | 'year' | 'code' | 'plain';
+  severity: ClaimSeverity;
+  /** 结构标记(表号/章节号/序号/年份)→ 豁免 */
+  structural: boolean;
   start: number;
   end: number;
   /** 上下文,用于判断是否标注了"约/估算" */
   context: string;
 }
 
-const CN_UNITS: Record<string, number> = { 万: 1e4, 亿: 1e8, 千: 1e3 };
-
-/** 明显不是"数据断言"的数字:序号、日期片段等(年份保留,由核验标注为豁免)。 */
-function isIgnorable(claim: NumericClaim, text: string): boolean {
-  const before = text.slice(Math.max(0, claim.start - 12), claim.start);
-  if (/(第|No\.?|#|序号)\s*$/i.test(before)) return true;
-  return false;
-}
+const NUMBER_PATTERN = /(?<![\w.])([-−-]?)(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)(?:\s*(万|亿|千))?(\s*%)?/g;
 
-const NUMBER_PATTERN = /(?<![\w.])(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)(?:\s*(万|亿|千))?(\s*%)?/g;
+const CN_UNITS: Record<string, number> = { 万: 1e4, 亿: 1e8, 千: 1e3 };
 
 /**
- * 报表名/代次这类"结构性标识"里也有数字,但它们不是数据断言。
- * 抽取前先把这些片段遮成空格(保持长度与偏移不变),避免把 `4.2.3 (1-4)_MLCC`
- * 拆成 4.2 / 3 / 1 / 4 然后误判为"无来源数字"。
+ * 结构性标识:抽取前遮成等长空格(保持偏移不变)。
+ * 覆盖:报表名、`.x` 版本号、三段以上版本号、区间、代次、行首序号、序数词。
  */
 const STRUCTURAL_PATTERNS: RegExp[] = [
-  // 4.2.3 (1-4)_MLCC / 1.0-3.0_MLCC / 5.2.1&3&5_存储器
-  /\d+(?:\.\d+)+(?:[-&]\d+(?:\.\d+)*)*(?:\s*\(\d+(?:\s*-\s*\d+)?\))?\s*_[A-Za-z\u4e00-\u9fff]+/g,
-  // 单独的 1.0-3.0 这类区间
-  /\d+(?:\.\d+)+-\d+(?:\.\d+)+/g,
+  // 4.2.3 (1-4)_MLCC / 1.0-3.0_MLCC / 5.2.1&3&5_存储器 / 4.1_MLCC
+  /\d+(?:\.\d+)+(?:[-&–]\d+(?:\.\d+)*)*(?:\s*\(\d+(?:\s*[-–]\s*\d+)?\))?\s*_[A-Za-z\u4e00-\u9fff]+/g,
+  // 4.2.x / 5.2.x
+  /\d+(?:\.\d+)+\.?[xX](?![\w])/g,
+  // 1.0-3.0 / 2025-01 / 1–8 这类区间与年月
+  /\d+(?:\.\d+)?\s*[-–~]\s*\d+(?:\.\d+)?/g,
+  // 三段及以上版本号(4.2.3、5.2.1)—— 本业务的数据值不会出现两个小数点
+  /\d+(?:\.\d+){2,}/g,
   // DDR3 / DDR4 / DDR5 / LPDDR4
   /\b(?:LP)?DDR[345]\b/gi,
+  // 行首列表序号 "1." "2)" "3、"
+  /^[ \t]*\d+[.)、](?=\s)/gm,
+  // "第 3 名 / 第 55 行 / 第 5 节"
+  /第\s*\d+\s*(?:名|位|大|条|行|章|节|部分|步|个)/g,
 ];
 
-function maskStructural(text: string): string {
+/** 抽取前把结构标记遮掉,返回遮罩后的文本(长度与原文一致)。 */
+export function maskStructural(text: string): string {
   let masked = text;
   for (const pattern of STRUCTURAL_PATTERNS) {
     masked = masked.replace(pattern, (match) => ' '.repeat(match.length));
@@ -54,20 +70,21 @@ function maskStructural(text: string): string {
 }
 
 /**
- * 抽取数字。返回去重后的 claim 列表(按出现顺序)。
+ * 抽取数字。返回带 severity / structural 的 claim 列表(按出现顺序、按展示值去重)。
  */
 export function extractNumericClaims(text: string): NumericClaim[] {
   const claims: NumericClaim[] = [];
   const seen = new Set<string>();
-  // 在"遮掉结构性标识"的副本上跑正则,context 仍取原文
   const masked = maskStructural(text);
   NUMBER_PATTERN.lastIndex = 0;
   let match: RegExpExecArray | null;
   while ((match = NUMBER_PATTERN.exec(masked)) !== null) {
-    const [raw, numberText, unit, percent] = match;
+    const [raw, sign, numberText, unit, percent] = match;
     const start = match.index;
     const end = start + raw.length;
-    const clean = numberText.replace(/,/g, '');
+    // 负号必须保留:金额环比/增长率为负很常见,丢符号会导致台账查不到
+    const negative = sign === '-' || sign === '−' || sign === '-';
+    const clean = `${negative ? '-' : ''}${numberText.replace(/,/g, '')}`;
     let value = Number(clean);
     if (!Number.isFinite(value)) continue;
 
@@ -80,43 +97,62 @@ export function extractNumericClaims(text: string): NumericClaim[] {
       kind = 'money';
     }
 
-    // 类型判断(用于报告与排除规则)
-    const before = text.slice(Math.max(0, start - 10), start);
-    const after = text.slice(end, end + 10);
+    const before = text.slice(Math.max(0, start - 12), start);
+    const after = text.slice(end, end + 12);
     if (!percent && !unit) {
       if (/^-?\d{4}$/.test(clean) && Number(clean) >= 1900 && Number(clean) <= 2100) {
         kind = 'year';
       } else if (/^\d{10}$/.test(clean) || (/^\d{8}$/.test(clean) && /HS|hs|编码/.test(before))) {
         kind = 'code';
-      } else if (/美元|USD|\$|万元|万美元/.test(before + after)) {
+      } else if (/美元|USD|\$|万元|万美元|亿元/.test(before + after)) {
         kind = 'money';
-      } else if (/个|件|只|片|颗|吨|千克|数量/.test(after)) {
+      } else if (/个|件|只|片|颗|吨|千克|数量|条记录/.test(after)) {
         kind = 'quantity';
-      } else if (/指数|点/.test(after)) {
+      } else if (/指数|点位/.test(before) || /^\s*点/.test(after)) {
+        // 只看"数字前面是不是指数标签":`728 | 价格指数…` 里的 728 是行数,不是指数
         kind = 'index';
       }
     }
 
+    const decimals = clean.includes('.') ? clean.split('.')[1].length : 0;
+    // 政策常数("10% 封顶""100%")与整数百分比:属于口径描述,不当数据断言
+    const policyPercent =
+      kind === 'percent' &&
+      (decimals === 0 || /上限|封顶|阈值|规则|不超过|不低于|至少|至多|权重上限/.test(before + after));
     const claim: NumericClaim = {
       raw: raw.trim(),
       value,
       rawNumber: clean,
-      display: `${percent ? clean + '%' : clean}${unit ?? ''}`,
+      display: `${percent ? `${clean}%` : clean}${unit ?? ''}`,
       kind,
+      severity: policyPercent ? 'soft' : decideSeverity(kind, value, decimals),
+      structural: kind === 'year' || policyPercent,
       start,
       end,
       context: text.slice(Math.max(0, start - 16), Math.min(text.length, end + 16)),
     };
-    if (isIgnorable(claim, text)) continue;
 
-    const key = `${claim.display}`;
-    if (seen.has(key)) continue;
-    seen.add(key);
+    if (seen.has(claim.display)) continue;
+    seen.add(claim.display);
     claims.push(claim);
   }
   return claims;
 }
 
+/**
+ * 该不该审:
+ * * 金额 / 百分比 / 指数 / 10 位 HS 编码 → 一定审;
+ * * 数量 ≥ 1000 → 审(小数量通常是"3 个类别"这类结构描述);
+ * * 十进制小数 ≥ 2 位 → 审(金额、占比、增长率这类测量值);
+ * * 其余裸整数 → 只做"能溯源就标记",不拦。
+ */
+function decideSeverity(kind: NumericClaim['kind'], value: number, decimals: number): ClaimSeverity {
+  if (kind === 'money' || kind === 'percent' || kind === 'index' || kind === 'code') return 'strict';
+  if (kind === 'quantity') return Math.abs(value) >= 1000 ? 'strict' : 'soft';
+  if (!Number.isInteger(value) && decimals >= 2) return 'strict';
+  return 'soft';
+}
+
 /** 判断数字附近是否明确标注了"约 / 估算 / 大约"等不确定措辞。 */
 export function isMarkedAsEstimate(claim: NumericClaim): boolean {
   return /(约|大约|左右|估算|估计|近似|大概|roughly|approx\.?|about|~)/i.test(claim.context);

+ 129 - 78
bff/src/verify/verify.ts

@@ -1,36 +1,42 @@
 /**
  * 数据真实性核验层。
  *
- * **唯一不被模型可见、也不可被模型调用的模块**:它位于 BFF 的答案输出路径上,
- * 纯代码执行。模型可以在答案里写任何数字,但写不出台账里的记录。
+ * **唯一不被模型可见、也不可被模型调用的模块**:它位于 BFF 的答案输出路径上,纯代码执行。
  *
- * 裁决规则(对应架构文档 3.2):
- *   accept —— 所有承载数字都能在台账中找到来源;
- *   flag   —— 有无来源数字,但模型标注了"约/估算",交付但前端高亮;
- *   reject —— 有无来源数字且未标注,**不交付**,触发一次修正重试。
+ * 判定原则(经真实使用反馈校准):
  *
- * 允许放行的少量例外(否则会把正常表述判成造假):
- *   * 年份(1900-2100)、序号、日期;
- *   * 表名/字段名里的数字(如 "1.0-3.0_MLCC"、"DDR4"、"DDR5");
- *   * 用户问题里出现过的数字(引用用户输入不算编造);
- *   * 极小的整数(1~12)在列表/枚举语境中。
+ * | 类别 | 例子 | 怎么处理 |
+ * |---|---|---|
+ * | 结构标记 | `4.2.x`、`5.2.1&3&5_存储器`、`第 3 名`、年份 | 直接**豁免**,不查台账 |
+ * | 必审数据(strict) | 金额、百分比、指数、≥1000 的数量、≥2 位小数、HS 编码 | 台账查不到 → **拒绝交付** |
+ * | 参考数据(soft) | 无单位裸整数(行数、条数、类别个数) | 能溯源就标"已溯源",查不到记为"参考性计数",**不拦截** |
+ *
+ * 另外两条现实规则:
+ * 1. **四舍五入容差**:台账存 `0.609412`、模型写 `60.94%` 视为同一数字(相对误差 ≤ 0.02%);
+ * 2. **单位换算**:`1,816.65 万美元` 只要能对上 `18,166,535.27` 就认为换算正确——不必强行过
+ *    calculator;但"约 300 万"这种与原值差几个百分点的,仍然会被拦(或标估算)。
  */
-import type { SessionLedger, ValueMatch } from '../store/ledger.js';
+import type { ValueMatch } from '../store/ledger.js';
 import { extractNumericClaims, isMarkedAsEstimate, type NumericClaim } from './extract.js';
 
-/** 核验只需要"按值反查"这一个能力,便于替换/测试。 */
+/** 核验只需要"按值反查"这两个能力,便于替换/测试。 */
 export interface LedgerLookup {
   findValue(value: string, sessionId: string): ValueMatch[];
+  /** 可选:带容差的近似反查(用于四舍五入 / 单位换算) */
+  findValueApprox?(value: number, sessionId: string): ValueMatch[];
 }
 
 export type Verdict = 'accept' | 'flag' | 'reject';
 
+export type ClaimStatus = 'verified' | 'flagged' | 'unverified' | 'exempt' | 'reference';
+
 export interface ClaimResult {
   raw: string;
   value: number;
   display: string;
   kind: NumericClaim['kind'];
-  status: 'verified' | 'flagged' | 'unverified' | 'exempt';
+  severity: 'strict' | 'soft';
+  status: ClaimStatus;
   reason?: string;
   matches: Array<{
     call_id: string;
@@ -45,15 +51,28 @@ export interface ClaimResult {
 
 export interface VerificationResult {
   verdict: Verdict;
+  /** 全部候选数字(含结构性与参考性),便于解释"我们看过哪些数字" */
   claims: ClaimResult[];
+  /** 只含必审数字(前端 chip 用) */
+  strictClaims: ClaimResult[];
   verified: number;
   flagged: number;
   unverified: number;
   exempt: number;
+  reference: number;
   total: number;
+  strictTotal: number;
   summary: string;
-  /** 给前端渲染溯源 chip 的紧凑结构 */
-  chips: Array<{ value: string; display: string; status: ClaimResult['status']; call_id?: string; object_id?: string; table?: string; row_index?: number; field?: string }>;
+  chips: Array<{
+    value: string;
+    display: string;
+    status: ClaimStatus;
+    call_id?: string;
+    object_id?: string;
+    table?: string;
+    row_index?: number;
+    field?: string;
+  }>;
   checkedAt: string;
 }
 
@@ -65,7 +84,7 @@ export interface VerifyOptions {
   allowEstimateFlag?: boolean;
 }
 
-/** 文本里出现过的数字(用户问题、表名等)——引用它们不算编造。 */
+/** 文本里出现过的数字(用户问题)——引用它们不算编造。 */
 function buildExemptions(texts: string[]): Set<number> {
   const exempt = new Set<number>();
   for (const text of texts) {
@@ -77,7 +96,6 @@ function buildExemptions(texts: string[]): Set<number> {
 }
 
 function roundKey(value: number): number {
-  // 保留 9 位有效数字,避免浮点误差导致豁免失效
   return Number(value.toPrecision(9));
 }
 
@@ -88,86 +106,118 @@ export function verifyAnswer(answer: string, options: VerifyOptions): Verificati
   const results: ClaimResult[] = [];
 
   for (const claim of claims) {
-    if (isExempt(claim, exemptions)) {
-      results.push({ ...base(claim), status: 'exempt', reason: '年份/序号/用户输入中已出现的数字,不作数据断言' });
+    const base = {
+      raw: claim.raw,
+      value: claim.value,
+      display: claim.display,
+      kind: claim.kind,
+      severity: claim.severity,
+      matches: [] as ClaimResult['matches'],
+    };
+
+    // ① 结构标记与年份:豁免
+    if (claim.structural || claim.kind === 'year') {
+      results.push({ ...base, status: 'exempt', reason: '年份/表号/序号等结构标记,不做数据断言' });
       continue;
     }
-    const matches = options.ledger.findValue(String(claim.value), options.sessionId);
-    if (matches.length > 0) {
-      results.push({ ...base(claim), status: 'verified', matches: matches.map(toChipMatch) });
+    // ② 用户问题里已经出现过:豁免
+    if (exemptions.has(roundKey(claim.value))) {
+      results.push({ ...base, status: 'exempt', reason: '用户问题中出现过的数字,不作数据断言' });
       continue;
     }
-    // 带单位换算(如 40.0316 万)的数字:只有 calculator 真算过这个数才算有来源
+
+    // ③ 精确反查
+    const exact = options.ledger.findValue(String(claim.value), options.sessionId);
+    if (exact.length > 0) {
+      results.push({ ...base, status: 'verified', matches: exact.map(toMatch) });
+      continue;
+    }
+    // ④ 带单位的数字:原文也可能直接存在于台账(如 40.0316 万)
     if (claim.rawNumber !== String(claim.value)) {
-      const rawMatches = options.ledger.findValue(claim.rawNumber, options.sessionId);
-      if (rawMatches.length > 0) {
-        results.push({ ...base(claim), status: 'verified', matches: rawMatches.map(toChipMatch) });
+      const byRaw = options.ledger.findValue(claim.rawNumber, options.sessionId);
+      if (byRaw.length > 0) {
+        results.push({ ...base, status: 'verified', matches: byRaw.map(toMatch) });
         continue;
       }
     }
-    // 台账里只有原文(例如百分比按 "21.70%" 存)时,再按显示值查一次
-    const textMatches = options.ledger.findValue(claim.display, options.sessionId);
-    if (textMatches.length > 0) {
-      results.push({ ...base(claim), status: 'verified', matches: textMatches.map(toChipMatch) });
+    // ⑤ 近似反查:四舍五入 / 单位换算
+    const approx = options.ledger.findValueApprox?.(claim.value, options.sessionId) ?? [];
+    if (approx.length > 0) {
+      results.push({
+        ...base,
+        status: 'verified',
+        reason: '与台账数值在四舍五入/换算容差内一致',
+        matches: approx.map(toMatch),
+      });
       continue;
     }
-    if (allowFlag && isMarkedAsEstimate(claim)) {
-      results.push({ ...base(claim), status: 'flagged', reason: '台账中无精确来源,但已明确标注为估算' });
+
+    // ⑥ 查不到
+    if (allowFlag && claim.severity === 'strict' && isMarkedAsEstimate(claim)) {
+      results.push({ ...base, status: 'flagged', reason: '台账中无精确来源,但已明确标注为估算' });
       continue;
     }
-    results.push({ ...base(claim), status: 'unverified', reason: '台账中找不到该数字的任何来源' });
+    if (claim.severity === 'soft') {
+      results.push({
+        ...base,
+        status: 'reference',
+        reason: '无单位计数/序号类数字,不参与核验(仅提示)',
+      });
+      continue;
+    }
+    results.push({ ...base, status: 'unverified', reason: '台账中找不到该数字的任何来源' });
   }
 
+  const strictResults = results.filter((item) => item.severity === 'strict' && item.status !== 'exempt');
   const verified = results.filter((item) => item.status === 'verified').length;
   const flagged = results.filter((item) => item.status === 'flagged').length;
   const unverified = results.filter((item) => item.status === 'unverified').length;
   const exempt = results.filter((item) => item.status === 'exempt').length;
+  const reference = results.filter((item) => item.status === 'reference').length;
 
   let verdict: Verdict = 'accept';
   if (unverified > 0) verdict = 'reject';
   else if (flagged > 0) verdict = 'flag';
 
-  const chips = results
-    .filter((item) => item.status !== 'exempt')
-    .map((item) => {
-      const match = item.matches[0];
-      return {
-        value: String(item.value),
-        display: item.display,
-        status: item.status,
-        call_id: match?.call_id,
-        object_id: match?.object_id,
-        table: match?.table,
-        row_index: match?.row_index,
-        field: match?.field,
-      };
-    });
+  const chips = strictResults.map((item) => {
+    const match = item.matches[0];
+    return {
+      value: String(item.value),
+      display: item.display,
+      status: item.status,
+      call_id: match?.call_id,
+      object_id: match?.object_id,
+      table: match?.table,
+      row_index: match?.row_index,
+      field: match?.field,
+    };
+  });
 
   return {
     verdict,
     claims: results,
+    strictClaims: strictResults,
     verified,
     flagged,
     unverified,
     exempt,
+    reference,
     total: results.length,
-    summary: summarize(verdict, verified, flagged, unverified, exempt),
+    strictTotal: strictResults.length,
+    summary: summarize(verdict, {
+      verified,
+      flagged,
+      unverified,
+      exempt,
+      reference,
+      strictTotal: strictResults.length,
+    }),
     chips,
     checkedAt: new Date().toISOString(),
   };
 }
 
-function base(claim: NumericClaim) {
-  return {
-    raw: claim.raw,
-    value: claim.value,
-    display: claim.display,
-    kind: claim.kind,
-    matches: [] as ClaimResult['matches'],
-  };
-}
-
-function toChipMatch(match: ValueMatch): ClaimResult['matches'][number] {
+function toMatch(match: ValueMatch): ClaimResult['matches'][number] {
   return {
     call_id: match.call_id,
     object_id: match.object_id ?? '',
@@ -179,24 +229,25 @@ function toChipMatch(match: ValueMatch): ClaimResult['matches'][number] {
   };
 }
 
-function isExempt(claim: NumericClaim, exemptions: Set<number>): boolean {
-  if (claim.kind === 'year') return true;
-  if (exemptions.has(roundKey(claim.value))) return true;
-  // 结构性小数字(“3 个应用领域”“前十大型号”“前 3 名”)不是数据断言。
-  // 金额/占比/指数不在此列:它们必须逐一到台账里比对。
-  if (claim.kind !== 'money' && claim.kind !== 'percent' && claim.kind !== 'index') {
-    if (Number.isInteger(claim.value) && Math.abs(claim.value) <= 12) return true;
-  }
-  return false;
-}
-
-function summarize(verdict: Verdict, verified: number, flagged: number, unverified: number, exempt: number): string {
-  const total = verified + flagged + unverified + exempt;
+function summarize(
+  verdict: Verdict,
+  counts: {
+    verified: number;
+    flagged: number;
+    unverified: number;
+    exempt: number;
+    reference: number;
+    strictTotal: number;
+  },
+): string {
+  const total = counts.verified + counts.flagged + counts.unverified + counts.exempt + counts.reference;
   if (total === 0) return '答案中没有需要核验的数字';
-  const parts = [`共 ${total} 个数字`, `已溯源 ${verified} 个`];
-  if (exempt > 0) parts.push(`豁免 ${exempt} 个(年份/序号等)`);
-  if (flagged > 0) parts.push(`估算 ${flagged} 个`);
-  if (unverified > 0) parts.push(`无来源 ${unverified} 个`);
+  const parts = [`共 ${total} 个数字`, `必审 ${counts.strictTotal} 个`];
+  parts.push(`已溯源 ${counts.verified} 个`);
+  if (counts.exempt > 0) parts.push(`结构标记豁免 ${counts.exempt} 个`);
+  if (counts.reference > 0) parts.push(`参考性计数 ${counts.reference} 个(不拦截)`);
+  if (counts.flagged > 0) parts.push(`估算 ${counts.flagged} 个`);
+  if (counts.unverified > 0) parts.push(`无来源 ${counts.unverified} 个`);
   const head = { accept: '通过', flag: '通过但需提示', reject: '未通过' }[verdict];
   return `${head}:${parts.join(',')}`;
 }

+ 24 - 1
bff/test/extract.test.ts

@@ -1,4 +1,4 @@
-/** 数字抽取与文本分类测试。 */
+/** 数字抽取与文本分类测试。 */
 import { test } from 'node:test';
 import assert from 'node:assert/strict';
 import { extractNumericClaims, isMarkedAsEstimate } from '../src/verify/extract.js';
@@ -88,3 +88,26 @@ test('报表名里的数字被遮掉,但旁边的真实数据仍能抽出', ()
 test('空文本返回空数组', () => {
   assert.deepEqual(extractNumericClaims('没有任何数字'), []);
 });
+
+test('负数保留符号(金额环比为负很常见)', () => {
+  const money = extractNumericClaims('金额 -1,234.56 美元');
+  assert.equal(money[0].value, -1234.56);
+  assert.equal(money[0].rawNumber, '-1234.56');
+
+  const percent = extractNumericClaims('金额环比 -13.30%');
+  assert.equal(percent[0].kind, 'percent');
+  assert.ok(Math.abs(percent[0].value + 0.133) < 1e-12);
+
+  const ratio = extractNumericClaims('金额环比 -0.4470999746174148352572197863');
+  assert.equal(ratio[0].value, -0.44709997461741485);
+  assert.equal(ratio[0].severity, 'strict');
+
+  // 全角负号也要认
+  const fullWidth = extractNumericClaims('环比 −13.30%');
+  assert.ok(Math.abs(fullWidth[0].value + 0.133) < 1e-12);
+});
+
+test('负号不会破坏区间/表号的遮蔽', () => {
+  assert.deepEqual(extractNumericClaims('2025-01 ~ 2026-08 的数据'), []);
+  assert.deepEqual(extractNumericClaims('见 4.2.3 (1-4)_MLCC 表'), []);
+});

+ 623 - 0
bff/test/fixtures/answer-medium.ledger.json

@@ -0,0 +1,623 @@
+[
+  {
+    "call_id": "call_fixture_1",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 1,
+    "field": "实际金额(美元)",
+    "value_text": "37441250.52",
+    "value_num": 37441250.52
+  },
+  {
+    "call_id": "call_fixture_2",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 2,
+    "field": "实际金额(美元)",
+    "value_text": "37441300",
+    "value_num": 37441300
+  },
+  {
+    "call_id": "call_fixture_3",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 3,
+    "field": "实际金额(美元)",
+    "value_text": "29254842.5",
+    "value_num": 29254842.5
+  },
+  {
+    "call_id": "call_fixture_4",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 4,
+    "field": "实际金额(美元)",
+    "value_text": "29254800",
+    "value_num": 29254800
+  },
+  {
+    "call_id": "call_fixture_5",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 5,
+    "field": "金额占比",
+    "value_text": "0.1954",
+    "value_num": 0.1954
+  },
+  {
+    "call_id": "call_fixture_6",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 6,
+    "field": "金额占比",
+    "value_text": "0.1938",
+    "value_num": 0.1938
+  },
+  {
+    "call_id": "call_fixture_7",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 7,
+    "field": "金额占比",
+    "value_text": "0.37979999999999997",
+    "value_num": 0.37979999999999997
+  },
+  {
+    "call_id": "call_fixture_8",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 8,
+    "field": "金额占比",
+    "value_text": "0.38",
+    "value_num": 0.38
+  },
+  {
+    "call_id": "call_fixture_9",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 9,
+    "field": "实际金额(美元)",
+    "value_text": "898825565.94",
+    "value_num": 898825565.94
+  },
+  {
+    "call_id": "call_fixture_10",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 10,
+    "field": "实际金额(美元)",
+    "value_text": "898825600",
+    "value_num": 898825600
+  },
+  {
+    "call_id": "call_fixture_11",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 11,
+    "field": "实际金额(美元)",
+    "value_text": "706956679.67",
+    "value_num": 706956679.67
+  },
+  {
+    "call_id": "call_fixture_12",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 12,
+    "field": "实际金额(美元)",
+    "value_text": "706956700",
+    "value_num": 706956700
+  },
+  {
+    "call_id": "call_fixture_13",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 13,
+    "field": "实际金额(美元)",
+    "value_text": "547703479.9",
+    "value_num": 547703479.9
+  },
+  {
+    "call_id": "call_fixture_14",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 14,
+    "field": "金额占比",
+    "value_text": "0.6093999999999999",
+    "value_num": 0.6093999999999999
+  },
+  {
+    "call_id": "call_fixture_15",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 15,
+    "field": "实际金额(美元)",
+    "value_text": "444144586.78",
+    "value_num": 444144586.78
+  },
+  {
+    "call_id": "call_fixture_16",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 16,
+    "field": "金额占比",
+    "value_text": "0.6282",
+    "value_num": 0.6282
+  },
+  {
+    "call_id": "call_fixture_17",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 17,
+    "field": "实际金额(美元)",
+    "value_text": "343587158.9",
+    "value_num": 343587158.9
+  },
+  {
+    "call_id": "call_fixture_18",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 18,
+    "field": "金额占比",
+    "value_text": "0.3823",
+    "value_num": 0.3823
+  },
+  {
+    "call_id": "call_fixture_19",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 19,
+    "field": "实际金额(美元)",
+    "value_text": "252739518.57",
+    "value_num": 252739518.57
+  },
+  {
+    "call_id": "call_fixture_20",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 20,
+    "field": "金额占比",
+    "value_text": "0.3575",
+    "value_num": 0.3575
+  },
+  {
+    "call_id": "call_fixture_21",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 21,
+    "field": "实际金额(美元)",
+    "value_text": "7534927.14",
+    "value_num": 7534927.14
+  },
+  {
+    "call_id": "call_fixture_22",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 22,
+    "field": "金额占比",
+    "value_text": "0.0084",
+    "value_num": 0.0084
+  },
+  {
+    "call_id": "call_fixture_23",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 23,
+    "field": "实际金额(美元)",
+    "value_text": "10072574.32",
+    "value_num": 10072574.32
+  },
+  {
+    "call_id": "call_fixture_24",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 24,
+    "field": "金额占比",
+    "value_text": "0.014199999999999999",
+    "value_num": 0.014199999999999999
+  },
+  {
+    "call_id": "call_fixture_25",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 25,
+    "field": "实际金额(美元)",
+    "value_text": "14543218.66",
+    "value_num": 14543218.66
+  },
+  {
+    "call_id": "call_fixture_26",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 26,
+    "field": "实际金额(美元)",
+    "value_text": "18166535.27",
+    "value_num": 18166535.27
+  },
+  {
+    "call_id": "call_fixture_27",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 27,
+    "field": "实际金额(美元)",
+    "value_text": "18166500",
+    "value_num": 18166500
+  },
+  {
+    "call_id": "call_fixture_28",
+    "object_id": "obj_fixture",
+    "table_name": "1.0-3.0_MLCC",
+    "row_index": 28,
+    "field": "金额指数",
+    "value_text": "1000",
+    "value_num": 1000
+  },
+  {
+    "call_id": "call_fixture_29",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 29,
+    "field": "实际金额(美元)",
+    "value_text": "1249.1413",
+    "value_num": 1249.1413
+  },
+  {
+    "call_id": "call_fixture_30",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 30,
+    "field": "实际金额(美元)",
+    "value_text": "946.5654",
+    "value_num": 946.5654
+  },
+  {
+    "call_id": "call_fixture_31",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 31,
+    "field": "实际金额(美元)",
+    "value_text": "67984260.08",
+    "value_num": 67984260.08
+  },
+  {
+    "call_id": "call_fixture_32",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 32,
+    "field": "实际金额(美元)",
+    "value_text": "93626474.33",
+    "value_num": 93626474.33
+  },
+  {
+    "call_id": "call_fixture_33",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 33,
+    "field": "实际金额(美元)",
+    "value_text": "1377.1787",
+    "value_num": 1377.1787
+  },
+  {
+    "call_id": "call_fixture_34",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 34,
+    "field": "实际金额(美元)",
+    "value_text": "1111.4966",
+    "value_num": 1111.4966
+  },
+  {
+    "call_id": "call_fixture_35",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 35,
+    "field": "金额占比",
+    "value_text": "-0.133",
+    "value_num": -0.133
+  },
+  {
+    "call_id": "call_fixture_36",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 36,
+    "field": "实际金额(美元)",
+    "value_text": "-0.133021",
+    "value_num": -0.133021
+  },
+  {
+    "call_id": "call_fixture_37",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 37,
+    "field": "实际金额(美元)",
+    "value_text": "16197411.8",
+    "value_num": 16197411.8
+  },
+  {
+    "call_id": "call_fixture_38",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 38,
+    "field": "实际金额(美元)",
+    "value_text": "0.12157",
+    "value_num": 0.12157
+  },
+  {
+    "call_id": "call_fixture_39",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 39,
+    "field": "金额占比",
+    "value_text": "0.1216",
+    "value_num": 0.1216
+  },
+  {
+    "call_id": "call_fixture_40",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 40,
+    "field": "金额占比",
+    "value_text": "0.035",
+    "value_num": 0.035
+  },
+  {
+    "call_id": "call_fixture_41",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 41,
+    "field": "实际金额(美元)",
+    "value_text": "0.034991",
+    "value_num": 0.034991
+  },
+  {
+    "call_id": "call_fixture_42",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 42,
+    "field": "实际金额(美元)",
+    "value_text": "83656729.6",
+    "value_num": 83656729.6
+  },
+  {
+    "call_id": "call_fixture_43",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 43,
+    "field": "实际金额(美元)",
+    "value_text": "0.119174",
+    "value_num": 0.119174
+  },
+  {
+    "call_id": "call_fixture_44",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 44,
+    "field": "金额占比",
+    "value_text": "0.1192",
+    "value_num": 0.1192
+  },
+  {
+    "call_id": "call_fixture_45",
+    "object_id": "obj_fixture",
+    "table_name": "1.0-3.0_MLCC",
+    "row_index": 45,
+    "field": "金额指数",
+    "value_text": "1124.4614",
+    "value_num": 1124.4614
+  },
+  {
+    "call_id": "call_fixture_46",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 46,
+    "field": "实际金额(美元)",
+    "value_text": "1008.7919",
+    "value_num": 1008.7919
+  },
+  {
+    "call_id": "call_fixture_47",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 47,
+    "field": "实际金额(美元)",
+    "value_text": "1056.7325",
+    "value_num": 1056.7325
+  },
+  {
+    "call_id": "call_fixture_48",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 48,
+    "field": "金额占比",
+    "value_text": "0.4808",
+    "value_num": 0.4808
+  },
+  {
+    "call_id": "call_fixture_49",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 49,
+    "field": "金额占比",
+    "value_text": "0.29969999999999997",
+    "value_num": 0.29969999999999997
+  },
+  {
+    "call_id": "call_fixture_50",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 50,
+    "field": "金额占比",
+    "value_text": "0.2195",
+    "value_num": 0.2195
+  },
+  {
+    "call_id": "call_fixture_51",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 51,
+    "field": "金额占比",
+    "value_text": "0.4899",
+    "value_num": 0.4899
+  },
+  {
+    "call_id": "call_fixture_52",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 52,
+    "field": "金额占比",
+    "value_text": "0.3089",
+    "value_num": 0.3089
+  },
+  {
+    "call_id": "call_fixture_53",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 53,
+    "field": "金额占比",
+    "value_text": "0.20120000000000002",
+    "value_num": 0.20120000000000002
+  },
+  {
+    "call_id": "call_fixture_54",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 54,
+    "field": "金额占比",
+    "value_text": "0.7948000000000001",
+    "value_num": 0.7948000000000001
+  },
+  {
+    "call_id": "call_fixture_55",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 55,
+    "field": "金额占比",
+    "value_text": "0.7685",
+    "value_num": 0.7685
+  },
+  {
+    "call_id": "call_fixture_56",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 56,
+    "field": "金额占比",
+    "value_text": "0.2052",
+    "value_num": 0.2052
+  },
+  {
+    "call_id": "call_fixture_57",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 57,
+    "field": "金额占比",
+    "value_text": "0.23149999999999998",
+    "value_num": 0.23149999999999998
+  },
+  {
+    "call_id": "call_fixture_58",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 58,
+    "field": "实际金额(美元)",
+    "value_text": "6246568.73",
+    "value_num": 6246568.73
+  },
+  {
+    "call_id": "call_fixture_59",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 59,
+    "field": "金额占比",
+    "value_text": "0.1668",
+    "value_num": 0.1668
+  },
+  {
+    "call_id": "call_fixture_60",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 60,
+    "field": "实际金额(美元)",
+    "value_text": "5430946.41",
+    "value_num": 5430946.41
+  },
+  {
+    "call_id": "call_fixture_61",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 61,
+    "field": "金额占比",
+    "value_text": "0.1451",
+    "value_num": 0.1451
+  },
+  {
+    "call_id": "call_fixture_62",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 62,
+    "field": "实际金额(美元)",
+    "value_text": "5226118.44",
+    "value_num": 5226118.44
+  },
+  {
+    "call_id": "call_fixture_63",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 63,
+    "field": "金额占比",
+    "value_text": "0.1396",
+    "value_num": 0.1396
+  },
+  {
+    "call_id": "call_fixture_64",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 64,
+    "field": "实际金额(美元)",
+    "value_text": "5027544.89",
+    "value_num": 5027544.89
+  },
+  {
+    "call_id": "call_fixture_65",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 65,
+    "field": "金额占比",
+    "value_text": "0.1343",
+    "value_num": 0.1343
+  },
+  {
+    "call_id": "call_fixture_66",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 66,
+    "field": "实际金额(美元)",
+    "value_text": "4917552.73",
+    "value_num": 4917552.73
+  },
+  {
+    "call_id": "call_fixture_67",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 67,
+    "field": "金额占比",
+    "value_text": "0.1313",
+    "value_num": 0.1313
+  },
+  {
+    "call_id": "call_fixture_68",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 68,
+    "field": "实际金额(美元)",
+    "value_text": "4791793.14",
+    "value_num": 4791793.14
+  },
+  {
+    "call_id": "call_fixture_69",
+    "object_id": "obj_fixture",
+    "table_name": "4.2.1_MLCC",
+    "row_index": 69,
+    "field": "金额占比",
+    "value_text": "0.128",
+    "value_num": 0.128
+  }
+]

+ 59 - 0
bff/test/fixtures/answer-medium.txt

@@ -0,0 +1,59 @@
+一、这份数据是什么
+工作区里有 1 份原始数据(medium.csv,10,571 行 × 25 列,字段包含 HS 编码、原产国、贸易国、指运港、品牌型号等)和 2 个同名统计结果对象(obj_51cb4a23 是较新版本,obj_a60a9718 是稍早版本,两者同为 49,069 行、表结构一致,建议以 obj_51cb4a23 为准)。统计结果共 16 张模板表,覆盖两个专项:MLCC(电容器) 与 存储器(DRAM/Flash)。
+
+二、数据质量底数(数据质量摘要)
+| 项目 | 值 |
+| 原始记录总数 | 10,571 |
+| 纳入计算 | 10,564 |
+| 剔除 | 7 |
+| 告警(alerts) | 107 |
+| 数据月份区间 | 2025-01 ~ 2026-08 |
+| 确认全年完整的年份 | 空(无任何年份被确认为全年) |
+| 币种 / 数量 | USD / 成交数量 |
+| 日期口径 | ISO 周四归月,不拆周 |
+
+另有 映射冲突 142 条:品牌 96 条、型号 38 条、国家地区 7 条、应用一轮 1 条;选样排除 230 条(原因均为“品牌型号缺失或年度金额缺失/非正;实际值仍纳入”)。这两张表需要业务人员人工复核。
+
+三、两个专项的规模(单位:美元,数据来自 4.2.1_MLCC、5.2.1&3&5_存储器)
+| 专项 | 2025 年 | 2026 年(1–8 月,暂算) | 说明 |
+| MLCC(多层瓷介电容器) | 37,441,250.52(3,744.13 万美元) | 29,254,842.50(2,925.48 万美元) | 占“电容器”一级类目金额 19.54% / 19.38%,但数量占比 37.98% / 38.00%,属于典型的低单价、高数量类目 |
+| 存储器 合计 | 898,825,565.94(89,882.56 万美元) | 706,956,679.67(70,695.67 万美元) | 由 DRAM + Flash + 其他存储器三项相加得出,三者同属“存储器”一级类目,口径一致 |
+| — DRAM | 547,703,479.90(占 60.94%) | 444,144,586.78(占 62.82%) | 占存储器金额过半 |
+| — Flash | 343,587,158.90(占 38.23%) | 252,739,518.57(占 35.75%) | — |
+| — 其他存储器 | 7,534,927.14(占 0.84%) | 10,072,574.32(占 1.42%) | — |
+
+注意:2026 年只有 1–8 月记录,不能与 2025 年 12 个月直接相比;且系统未确认任何年份为全年完整(年度数据状态 全部为“已提供期间暂算”)。
+
+四、最新月度与基期(4.1_MLCC、5.1_存储器,均为进口 I)
+| 指标 | 2025-01(基期) | 2026-08(最新) |
+| 电容器 进口额 | 14,543,218.66 美元 | 18,166,535.27 美元(1,816.65 万美元) |
+| 电容器 金额指数 / 数量指数 | 1000 / 1000 | 1249.1413 / 946.5654 |
+| 存储器 进口额 | 67,984,260.08 美元 | 93,626,474.33 美元 |
+| 存储器 金额指数 / 数量指数 | 1000 / 1000 | 1377.1787 / 1111.4966 |
+
+• 电容器 2026-08 金额环比 -13.30%(表内 金额环比 = -0.133021);与 2025-08 的 16,197,411.80 美元相比,同比增长率 = 0.121570(即 +12.16%)。
+• 存储器 2026-08 金额环比 +3.50%(0.034991);与 2025-08 的 83,656,729.60 美元相比,同比增长率 = 0.119174(即 +11.92%)。
+• 基期 2025-01 的环比为空,属正常(无上月)。
+
+价格指数只在 1.0-3.0_MLCC / 1.0-3.0_存储器 两个基础类目表里有值(例如 MLCC 2025-02 价格指数 1124.4614、DRAM 2025-02 为 1008.7919、2025-03 为 1056.7325);4.2.x、5.2.x 及行业层级的 价格指数 全为空,不可计算、也不要用其他表填补。
+
+五、结构下钻要点
+• DDR 代际(按 5.2.1&3&5_存储器 的金额占比):2025 年 DDR4 48.08%、DDR5 29.97%、DDR3 21.95%;2026 年 DDR4 48.99%、DDR5 30.89%、DDR3 20.12%,DDR5 份额小幅上移。
+• Flash 结构:NAND 占 Flash 金额 79.48%(2025 年)/ 76.85%(2026 年),NOR 占 20.52% / 23.15%。
+• MLCC 应用领域(重点全量层级,2025 年,占比分母为 MLCC):工业应用 6,246,568.73 美元(16.68%)、网络通信 5,430,946.41(14.51%)、未识别 5,226,118.44(13.96%)、先进计算 5,027,544.89(13.43%)、汽车电子 4,917,552.73(13.13%)、新能源 4,791,793.14(12.80%)。
+• 其他DRAM、其他DDR、其他Flash 三个基础类目在统计期内 0 行记录,不是 0 值。
+
+六、辅助表用途
+| 表 | 行数 | 用途 |
+| 样本权重 | 728 | 价格指数加权样本,规则“10% 封顶再分配”(如 MLCC 2025 年样本数量 37 个) |
+| 选样排除 | 230 | 价格指数选样剔除明细 |
+| 重点全量层级 | 678 | 应用领域/品牌/品牌国别/前十大型号 四类层级占比 |
+| 供应链条件占比 | 24,771 | MLCC、DDR 两专项 × 两种分析方式(完整前缀条件、品牌国别条件)× 7 类节点(app/dispatch/port/port_country/trade_country/origin/brand_country)的占比 |
+| 4.3_MLCC / 5.3_存储器 | 2,556 / 4,546 | 原产国、贸易国、启运国、经停港、应用领域多维交叉,全部为进口方向 |
+
+周四归月映射 209 行(ISO 周→归属年月的换算依据)。
+
+七、需要留意的三点
+1. 只有进口(I)方向数据,各表 进/出口 均无出口记录,因此无法给出出口或顺差结论。
+2. 所有金额占比、数量占比都有独立分母(写在 占比分母范围 列),跨层级不可相加,例如 MLCC 占“电容器”、DDR3 占“DDR”、应用领域占“MLCC”,不能混着汇总。
+3. 年度可比性受限:年度完整性 为空列表,2026 年仅到 8 月;任何“2026 年全年”的说法都不成立。若需要全年对比,请在数据处理工作区补齐 2025 全年确认标记或补录 2026 年 9–12 月数据后重新处理。

+ 89 - 8
bff/test/verify.test.ts

@@ -1,4 +1,4 @@
-/** 核验层测试:accept / flag / reject 三种裁决与豁免规则。 */
+/** 核验层测试:accept / flag / reject 三种裁决与豁免规则。 */
 import { test } from 'node:test';
 import assert from 'node:assert/strict';
 import { buildCorrectionPrompt, verifyAnswer, type LedgerLookup } from '../src/verify/verify.js';
@@ -88,14 +88,15 @@ test('百分比按归一化数值回查', () => {
   assert.equal(result.verdict, 'accept');
 });
 
-test('万单位换算:calculator 没算过就是无来源(防止心算)', () => {
-  const ledger = ledgerWith([['400316.13', [match('400316.13')]]]);
-  const rejected = verifyAnswer('进口额 40.0316 万美元。', { ledger, sessionId: 's1' });
-  assert.equal(rejected.verdict, 'reject', '台账只有 400316.13,换算值必须由 calculator 产出');
+test('万单位换算:与台账数值一致即放行,差得远才拦', () => {
+  // 新策略(真实使用反馈后调整):换算只要与真实值在 0.02% 内一致就认,不必强行过 calculator
+  const converted = new FixtureLedger([
+    { call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '实际金额(美元)', value_text: '400316.13', value_num: 400316.13 },
+  ]);
+  assert.equal(verifyAnswer('进口额 40.0316 万美元。', { ledger: converted, sessionId: 's1' }).verdict, 'accept');
 
-  const withCalc = ledgerWith([['40.0316', [match('40.0316', 'result', 'calc_1', -1)]]]);
-  const accepted = verifyAnswer('进口额 40.0316 万美元。', { ledger: withCalc, sessionId: 's1' });
-  assert.equal(accepted.verdict, 'accept');
+  // 但"约 300 万"这种与原值差 6 倍的说法,必须拦
+  assert.equal(verifyAnswer('进口额 300 万美元。', { ledger: converted, sessionId: 's1' }).verdict, 'reject');
 });
 
 test('修正提示列出问题数字', () => {
@@ -111,3 +112,83 @@ test('没有数字的答案直接 accept', () => {
   assert.equal(result.verdict, 'accept');
   assert.equal(result.total, 0);
 });
+
+// ---------------------------------------------------------------------------
+// 真实答案回归:medium 数据集那份长报告(曾因表号被拦而误拒)
+// ---------------------------------------------------------------------------
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+const FIXTURES = path.resolve(import.meta.dirname, '..', '..', 'test', 'fixtures');
+const ANSWER = readFileSync(path.join(FIXTURES, 'answer-medium.txt'), 'utf8');
+const LEDGER: Array<Record<string, any>> = JSON.parse(readFileSync(path.join(FIXTURES, 'answer-medium.ledger.json'), 'utf8'));
+
+class FixtureLedger implements LedgerLookup {
+  constructor(private readonly rows: Array<Record<string, any>>) {}
+  findValue(value: string): ValueMatch[] {
+    return this.rows.filter((row) => String(row.value_text) === String(value)) as ValueMatch[];
+  }
+  findValueApprox(value: number): ValueMatch[] {
+    const epsilon = Math.max(Math.abs(value) * 2e-4, 0.006);
+    return this.rows.filter((row) => Math.abs(Number(row.value_num) - value) <= epsilon) as ValueMatch[];
+  }
+}
+
+test('真实长报告:表号/序号不再被当成数据(不再误拒)', () => {
+  const result = verifyAnswer(ANSWER, { ledger: new FixtureLedger(LEDGER), sessionId: 's-long' });
+  assert.equal(result.verdict, 'accept', result.summary);
+  assert.equal(result.unverified, 0, JSON.stringify(result.claims.filter((c) => c.status === 'unverified')));
+
+  // 结构性数字必须全部豁免:表号、章节号、序号、年份、政策常数
+  const raws = result.claims.map((claim) => claim.raw);
+  for (const structural of ['4.2.x', '5.2.1&3&5_存储器', '1.0-3.0_MLCC']) {
+    assert.ok(!raws.includes(structural), `不应把 ${structural} 列为候选数字`);
+  }
+  for (const exempted of ['2025', '2026', '10%']) {
+    const claim = result.claims.find((item) => item.raw === exempted);
+    assert.ok(!claim || claim.status === 'exempt', `${exempted} 不应进入必审集合`);
+  }
+
+  // 无单位计数(行数/条数)不应参与裁决
+  const reference = result.claims.filter((claim) => claim.status === 'reference').map((claim) => claim.raw);
+  assert.ok(reference.includes('10,571'), '行数应归为参考性计数');
+  assert.ok(reference.includes('728'), '样本权重行数应归为参考性计数');
+});
+
+test('真实长报告:删掉一条金额就必须拒绝,且精确定位到那一个数字', () => {
+  // 去掉"工业应用 6,246,568.73"这一条(它没有万美元换算的孪生值,最适合验精确拦截)
+  const target = 6246568.73;
+  const broken = LEDGER.filter((row) => Math.abs(Number(row.value_num) - target) > 1);
+  const result = verifyAnswer(ANSWER, { ledger: new FixtureLedger(broken), sessionId: 's-bad' });
+  assert.equal(result.verdict, 'reject');
+  assert.equal(result.unverified, 1, JSON.stringify(result.claims.filter((c) => c.status === 'unverified')));
+  assert.equal(result.claims.find((claim) => claim.status === 'unverified')!.value, target);
+});
+
+test('真实长报告:四舍五入的百分比能被容差识别', () => {
+  // 台账存 0.609412,答案写 60.94%
+  const rows = [{ call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '金额占比', value_text: '0.609412', value_num: 0.609412 }];
+  const result = verifyAnswer('DRAM 占存储器金额 60.94%。', { ledger: new FixtureLedger(rows), sessionId: 's-round' });
+  assert.equal(result.verdict, 'accept', result.summary);
+});
+
+test('真实长报告:万美元换算按数值一致性放行,差几个百分点仍然拦', () => {
+  const rows = [{ call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '实际金额(美元)', value_text: '18166535.27', value_num: 18166535.27 }];
+  const okResult = verifyAnswer('电容器 2026-08 进口额 1,816.65 万美元。', { ledger: new FixtureLedger(rows), sessionId: 's-conv' });
+  assert.equal(okResult.verdict, 'accept', okResult.summary);
+
+  const badResult = verifyAnswer('电容器 2026-08 进口额 1,900 万美元。', { ledger: new FixtureLedger(rows), sessionId: 's-conv2' });
+  assert.equal(badResult.verdict, 'reject', '差 4.6% 的换算不能被放行');
+  // 同一句话加上"约":按估算放行但高亮
+  const flagged = verifyAnswer('电容器 2026-08 进口额约 1,900 万美元。', { ledger: new FixtureLedger(rows), sessionId: 's-conv3' });
+  assert.equal(flagged.verdict, 'flag');
+});
+test('负数环比:台账里是负值,答案写负值才算一致', () => {
+  const rows = [{ call_id: 'c1', object_id: 'o', table_name: 't', row_index: 0, field: '金额环比', value_text: '-0.4470999746174148352572197863', value_num: -0.4470999746174148 }];
+  const ok = verifyAnswer('其他存储器 金额环比 -0.4470999746174148。', { ledger: new FixtureLedger(rows), sessionId: 's-neg' });
+  assert.equal(ok.verdict, 'accept', ok.summary);
+
+  // 把符号写错(丢负号)必须被拦——这正是初版丢符号导致的误判
+  const wrongSign = verifyAnswer('其他存储器 金额环比 0.4470999746174148。', { ledger: new FixtureLedger(rows), sessionId: 's-neg2' });
+  assert.equal(wrongSign.verdict, 'reject');
+});

+ 22 - 8
docs/01-架构设计.md

@@ -127,19 +127,33 @@ BFF、前端、其他工具**只**依赖 `contract.py` 里的类型;替换实
 模型可以引用 `_trace.row_hash` 传给 `calculator`(此时该输入会被判定为"已溯源"),
 但它无法让台账里出现一个不存在的值。
 
-### 4.2 输出侧:三段式裁决
+### 4.2 输出侧:只审"该审的数据"
+
+核验的第一步不是查台账,而是**判断这个数字要不要审**。真实使用反馈暴露过初版的错误:
+把 `4.2.x`、`5.2.1&3&5_存储器` 这类表号也当数据去查,查不到就拒绝整条回答。
+
+现在的分类(`bff/src/verify/extract.ts`):
+
+| 类别 | 例子 | 处理 |
+|---|---|---|
+| 结构标记 | 表号 `4.2.1_MLCC`、`4.2.x`、区间 `1.0-3.0`、`DDR4`、行首序号、`第 3 名`、年份 | **豁免**,不进台账 |
+| 必审(strict) | 金额(含万/亿)、百分比(带小数)、指数、≥1000 的数量、≥2 位小数、10 位 HS 编码 | 查不到 → **拒绝** |
+| 参考(soft) | 无单位裸整数(行数、条数、类别个数)、整数百分比与"10% 封顶"这类政策常数 | 查不到只记"参考计数",**不拦截** |
 
 | 裁决 | 条件 | 处理 |
 |---|---|---|
-| `accept` | 所有承载数字都能在台账中找到来源 | 交付 |
-| `flag` | 有无来源数字,但明确标注了"约/估算/左右" | 交付,前端黄色高亮 |
-| `reject` | 有无来源数字且未标注 | **不交付**;注入修正提示重跑一次;仍失败则返回拒绝说明 |
+| `accept` | 所有**必审**数字都有来源 | 交付 |
+| `flag` | 有必审数字查不到,但模型标了"约/估算" | 交付,前端黄色高亮 |
+| `reject` | 有必审数字查不到且未标注 | **不交付**;注入修正提示重跑一次;仍失败则返回拒绝说明 |
+
+两条现实规则(同样是为了"别误杀"):
 
-**豁免规则**(否则正常表述会被误判):年份(1900–2100)、序号、用户问题里已出现的数字、
-表名/代次里的数字(`1.0-3.0_MLCC`、`DDR4`)、以及 ≤12 的非金额类小整数。
+1. **四舍五入容差**:台账存 `0.609412`、答案写 `60.94%`,视为同一数字(相对误差 ≤ 0.02%,绝对值下限 0.006);
+2. **单位换算按数值一致性判定**:`1,816.65 万美元` 只要与台账的 `18,166,535.27` 在容差内一致就放行,
+   不必强行过 `calculator`;但"约 1,900 万"这种差 4.6% 的,仍然会被拦(或按估算标记)。
 
-**换算必须过 calculator**:答案写"40.03 万美元"而台账里只有 `400316.13`,属无来源 → reject;
-只有 `calculator` 真的算过 `40.0316` 才会命中。这条规则专门堵"模型自己心算换单位"。
+> 仍然建议模型用 `calculator` 做换算——核验会因此更稳(`inputs` 里有 `call_id`/`row_hash`),
+> 但不会再因为"没走计算器"而误杀一次正确的换算。
 
 ### 4.3 两本台账的分工
 

+ 24 - 0
docs/02-实现说明.md

@@ -322,6 +322,30 @@ event: final         {message_id, text, delivered, verification, steps, attempts
 
 ---
 
+### 4.5 核验层的判定细则(`bff/src/verify/`)
+
+```
+extract.ts                      verify.ts
+文本 → 遮掉结构标记 → 抽数字 → 分类(severity) → 逐个查台账 → 裁决 → chips
+```
+
+**遮蔽(maskStructural)**:表号 `\d+(\.\d+)+…_[A-Za-z汉字]+`、`.x` 版本号、区间、三段版本号、
+`DDR3/4/5`、行首序号、`第 N 名/第 N 行` —— 遮成等长空格,偏移不变,因此后面取上下文仍然准确。
+
+**分类**:见 `docs/01` 第 4.2 节的三类表。要点是"金额/百分比/指数/大数量/多小数"必审,其余只做提示。
+
+**查台账三种方式**(命中任一即"已溯源"):
+
+1. 精确:`ledger_values.value_num = value`;
+2. 原文:`value_text` 等于原始数字文本(如 `40.0316`);
+3. 近似:`|value_num − value| ≤ max(0.02% × |value|, 0.006)`,用于四舍五入与单位换算。
+
+**可调参数**:容差在 `SessionLedger.findValueApprox(relTolerance)`;分类规则在 `decideSeverity()`;
+是否放行"估算"在 `agent.cordis.yml → verification.allowEstimateFlag`。
+
+**取证工具**:`node scripts/verify_probe.mjs <答案文件> [--ledger <台账JSON>]`
+把一段答案的每个候选数字的 kind / severity / 状态 / 原因打出来,改规则前先跑它。
+`bff/test/fixtures/answer-medium.txt` 就是那次误拒的真实答案,已固化为回归样本。
 ## 5. 指标口径(与第一阶段代码保持一致)
 
 | 指标 | 定义 |

+ 3 - 2
docs/03-使用手册.md

@@ -252,8 +252,9 @@ CSV 第一行是字段名,至少要有这 7 列(大小写要与下表一致
 
 | 结论 | 含义 | 你要做什么 |
 |---|---|---|
-| 绿色 `数据核验通过` | 每个数字都能在工具返回的数据里找到 | 放心用 |
-| 黄色 `含估算数字` | 有数字标了"约/大约",系统查不到精确来源 | 注意那是估算,不是统计值 |
+| 绿色 `数据核验通过` | 所有**关键数据**(金额/百分比/指数)都能在工具返回的数据里找到 | 放心用 |
+| 黄色 `含估算数字` | 有关键数据标了"约/大约",系统查不到精确来源 | 注意那是估算,不是统计值 |
+| —(不拦截) | 行数、条数、表号(如 `4.2.1_MLCC`)、年份这类数字 | 不参与核验,正常引用即可 |
 | 红色 `数据核验未通过` | 有数字完全没有来源,系统**不交付**这个答案,会重新算一次 | 若两次都失败,它会告诉你缺什么 |
 
 ### 5.2 怎么问更容易得到好答案

+ 49 - 5
docs/05-测试报告.md

@@ -22,10 +22,10 @@
 | 测试组 | 用例数 | 结果 | 覆盖 |
 |---|---|---|---|
 | Python 引擎与接口(pytest) | **85** | 全部通过 | 数值/权重、规则解析、入库与周四归月、23 张报表口径、对象库、血缘、`data_read`、`calculator`、台账、HTTP 接口 |
-| BFF 单元与接口(node:test) | **58** | 全部通过 | YAML 解析、Preset、数字抽取、核验裁决、工具注册与 `finalizeContent`、Agent Loop、HTTP 接口、SSE 对话、multipart |
+| BFF 单元与接口(node:test) | **65** | 全部通过 | YAML 解析、Preset、数字抽取、核验裁决、工具注册与 `finalizeContent`、Agent Loop、HTTP 接口、SSE 对话、multipart |
 | 前端单元 + 渲染(vitest) | **27** | 全部通过 | 数值/百分比/时间格式化、表名分类、图表数据构造、列推断,以及用 SSR 渲染 App / 消息 / 核验面板 / Markdown 组件 |
 | 端到端联调(真实服务 + 真实模型) | **33 项检查** | 全部通过 | 上传→处理→23 表→预览→血缘→下载→指数口径→自定义聚合→台账→**真实模型对话 + 核验**→前端托管 |
-| **合计** | **203** | **全部通过** | |
+| **合计** | **210** | **全部通过** | |
 
 一键复现:
 
@@ -113,19 +113,19 @@ sum/mean/median/min/max/count/growth/ratio/index/share 正确性;
 
 ---
 
-## 4. BFF 测试(58 项)
+## 4. BFF 测试(65 项)
 
 ### 4.1 `yaml.test.ts`(8)
 
 标量/嵌套/序列/块标量/Tab 报错,并与官方 `yaml` 包对**真实 `agent.cordis.yml`** 交叉校验
 (`name / model / temperature / tools / limits / verification / systemPrompt` 全部一致)。
 
-### 4.2 `extract.test.ts`(12)
+### 4.2 `extract.test.ts`(14)
 
 千分位金额、百分比归一化、万/亿换算、"约"识别、年份归 year、HS 归 code、
 数量归 quantity、去重、空文本,以及**报表名/代次里的数字被遮掉**(`4.2.3 (1-4)_MLCC`、`1.0-3.0_MLCC`、`DDR4` 不产生任何 claim;同一句话里的 400,316.13 仍能抽出)。
 
-### 4.3 `verify.test.ts`(10)
+### 4.3 `verify.test.ts`(15)
 
 | 场景 | 期望 |
 |---|---|
@@ -246,6 +246,50 @@ Agent Loop 完整一轮(工具调用→结果回灌→最终答案,且第二
 | 逐页截图 | 对话/抽屉/跳转/处理/文件/系统 | ✓ 6 张(`docs/images/`) |
 
 这一步抓出并修掉了"抽屉里年度显示成 2,026"的问题(与表格列同一类问题)。
+### 6.3 真实使用暴露的误拒:核验层审了不该审的数字
+
+**现象**(用户上报):一份 medium 数据集的完整分析报告被拒绝交付,提示"146 个数字,9 个无来源"。
+其中被拦的是 `4.2`、`5.2` 这类**表号**,不是数据。
+
+**根因**:初版把"出现在答案里的数字"一律当数据断言去查台账;`4.2.x`、`5.2.1&3&5_存储器` 这类
+报表编号、行首序号、`10% 封顶` 这类政策常数都被卷了进来。另有两个次生问题:
+
+* `728 | 价格指数加权样本` 里的行数被误判成"指数"(因为向后看 12 个字符能看到"指数");
+* `1,816.65 万美元` 这类**换算值**必须由 `calculator` 产出才算数,导致正常换算被判无来源。
+
+**修复**(`bff/src/verify/extract.ts` + `verify.ts`):
+
+1. 抽取前遮掉结构标记(表号 / `.x` / 区间 / 三段版本号 / `DDR3-5` / 行首序号 / `第 N 名`);
+2. 给每个数字打 `severity`:金额、百分比、指数、≥1000 数量、≥2 位小数、HS 编码 = `strict`;
+   无单位裸整数与政策常数 = `soft`(只提示,不拦截);
+3. 指数判定改为看**前缀**(`价格指数 1124.46`),而不是向后找关键词;
+4. 台账新增**近似反查**:四舍五入(`0.609412` ↔ `60.94%`)与单位换算
+   (`18,166,535.27` ↔ `1,816.65 万`)在 0.02% 容差内视为同一数字。
+
+**回归**:把那份真实答案固化为 `bff/test/fixtures/answer-medium.txt` + `.ledger.json`,
+新增 4 个用例:
+
+| 用例 | 断言 |
+|---|---|
+| 同一份答案 + 完整台账 | `accept`,0 个无来源;`4.2.x`/`5.2.1&3&5_存储器`/`1.0-3.0_MLCC` 不产生 claim;`10,571`、`728` 归为参考计数 |
+| 删掉其中一条金额(6,246,568.73) | `reject`,且**只**拦这一个数字 |
+| `0.609412` ↔ `60.94%` | `accept`(容差生效) |
+| `18,166,535.27` ↔ `1,816.65 万` / `1,900 万` | 前者 accept,后者 reject(差 4.6% 不放行) |
+
+另外提供取证工具 `scripts/verify_probe.mjs`:打印一段答案里每个候选数字的 kind/severity/状态,
+规则调整前先看清单。当前那份答案的统计是:**95 个候选数字 → 必审 69、结构豁免 3、参考 23**,
+必审集合里已经不含任何表号或序号。
+
+### 6.4 修好后用真实数据复测(medium,10,571 行)
+
+| 轮次 | 数字总数 | 必审 | 已溯源 | 结论 |
+|---|---|---|---|---|
+| 第 1 次(修符号前) | 318 | 220 | 297 | reject(2 个负数环比丢符号查不到) |
+| 第 2 次(修符号前) | 526 | 345 | 511 | reject(1 个负数环比) |
+| 第 3 次(修符号后) | **492** | **392** | **473** | **accept,15,926 字长报告正常交付** |
+
+第 3 次之后,同一份数据的长报告不再被误拦;结构性数字(表号/序号/年份)全部豁免,
+16 个行数类计数归为参考计数(不拦截)。
 ## 7. 手工验证过的场景
 
 | 场景 | 结果 |

+ 5 - 1
docs/06-工具增强与演示交付.md

@@ -29,7 +29,7 @@
 ## 验证与可复现命令
 
 - Python:194 项通过(原测试加旧版格式回归、生成式格式矩阵、金额/缺数/范围/精度测试)。命令:`.venv/bin/python -m pytest -c tools-service/pyproject.toml tools-service/tests`。
-- BFF:59 项通过;前端:27 项通过;前端/BFF 构建成功。
+- BFF:66 项通过(含合并云端最新核验修复后的回归);前端:27 项通过;前端/BFF 构建成功。
 - 浏览器实测:在真实遮掩工作区查询金额/数量区间,四个上下界及记录数均溯源,核验 accept;点击数字可查看原始区间、行号和行哈希。
 - 真实服务 + DeepSeek:33 项端到端检查通过,包含上传、处理 23 张表、下载、溯源、台账和核验通过后的答案交付。命令:`CDA_PYTHON="$PWD/.venv/bin/python" node scripts/e2e.mjs --keep`。
 - 旧脚本对比:固定 16 种写法的品牌、型号、国别、类目、应用和分类标志均与用户提供脚本一致;品牌与型号均提取出的测试用例由增强前 4/16 增至 11/16。这是有意选择的格式测试集合,不能外推为真实数据识别率。
@@ -46,3 +46,7 @@
 目前是本机单机 demo:长任务仍由服务进程中的后台线程执行,没有断点续跑或持久化任务队列;重启可能中断任务。XLSX 只读第一张表,旧 `.xls`、混合编码、无分隔定宽文本、自动换汇不在支持范围。真实全量的高唯一申报率、高基数结果维度和报表时间仍需取得原始数据后单独压测。
 
 测试仅有一项依赖弃用提醒:新版本 Starlette 推荐 httpx2;本轮所有 FastAPI TestClient 接口测试通过。
+
+## 云端同步(2026-11-18)
+
+上传前合并了云端 `857198f` 的核验修复,保留表号与负数识别、近似值溯源及界面更新。两个生成文件的冲突通过重新构建解决;未覆盖云端提交,未包含 `.env` 或真实运行数据。

BIN
docs/images/01-chat.png


BIN
docs/images/02-process.png


BIN
docs/images/03-files.png


BIN
docs/images/04-system.png


BIN
docs/images/05-trace-drawer.png


BIN
docs/images/06-row-jump.png


+ 45 - 1
scripts/ui_probe.mjs

@@ -1,4 +1,4 @@
-#!/usr/bin/env node
+#!/usr/bin/env node
 /**
  * 用 Chrome DevTools Protocol 驱动无头浏览器做"真实交互"验证(截图 + 点击)。
  *
@@ -85,12 +85,49 @@ class Cdp {
   }
 }
 
+/** 如果服务没起,就自己拉起来(方便 run_tests.ps1 一键跑)。 */
+async function ensureServices() {
+  const healthy = async () => {
+    try {
+      const response = await fetch(`${BASE}/api/health`, { signal: AbortSignal.timeout(2000) });
+      if (!response.ok) return false;
+      const payload = await response.json();
+      return Boolean(payload.ok);
+    } catch {
+      return false;
+    }
+  };
+  if (await healthy()) return null;
+  if (!BASE.includes('127.0.0.1:8787') && !BASE.includes('localhost:8787')) {
+    console.error(`✗ 服务未就绪:${BASE}/api/health(非默认地址时不自动启动)`);
+    process.exit(1);
+  }
+  console.log('  · 服务未启动,自动拉起(node scripts/start.mjs --no-open --skip-install)');
+  const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'start.mjs'), '--no-open', '--skip-install'], {
+    cwd: ROOT,
+    stdio: 'ignore',
+    detached: false,
+  });
+  for (let attempt = 0; attempt < 120; attempt += 1) {
+    await sleep(1000);
+    if (await healthy()) return child;
+  }
+  console.error('✗ 自动启动超时');
+  try {
+    child.kill();
+  } catch {
+    /* 忽略 */
+  }
+  process.exit(1);
+}
+
 async function main() {
   const browser = findBrowser();
   if (!browser) {
     console.error('✗ 找不到 Chrome/Edge,可手动截图;本脚本已跳过');
     process.exit(0);
   }
+  const services = await ensureServices();
   mkdirSync(OUT, { recursive: true });
 
   const child = spawn(
@@ -210,6 +247,13 @@ async function main() {
   } catch {
     /* 忽略 */
   }
+  if (services?.pid) {
+    try {
+      spawnSync('taskkill', ['/pid', String(services.pid), '/T', '/F'], { stdio: 'ignore' });
+    } catch {
+      /* 忽略 */
+    }
+  }
   console.log(`\n全部交互验证通过,截图在 ${OUT}`);
   return results;
 }

+ 52 - 0
scripts/verify_probe.mjs

@@ -0,0 +1,52 @@
+#!/usr/bin/env node
+/**
+ * 审查层探针:把一段真实答案里的每个"候选数字"打出来,并说明它会被怎么判定。
+ *
+ *   node scripts/verify_probe.mjs bff/test/fixtures/answer-medium.txt
+ *   node scripts/verify_probe.mjs <file> --ledger <ledger-values.json>
+ *
+ * 用途:改核验规则时先看这份清单,确认"该审的审、不该审的放"。
+ * 没有 ledger 文件时,所有数字都会显示为"无来源",重点看**分类与豁免**是否正确。
+ */
+import { readFileSync } from 'node:fs';
+import { extractNumericClaims } from '../bff/dist/src/verify/extract.js';
+import { verifyAnswer } from '../bff/dist/src/verify/verify.js';
+
+const args = process.argv.slice(2);
+const file = args.find((item) => !item.startsWith('--'));
+if (!file) {
+  console.error('用法: node scripts/verify_probe.mjs <答案文本文件> [--ledger values.json]');
+  process.exit(1);
+}
+const ledgerIndex = args.indexOf('--ledger');
+const ledgerFile = ledgerIndex >= 0 ? args[ledgerIndex + 1] : null;
+
+const text = readFileSync(file, 'utf8');
+const entries = ledgerFile ? JSON.parse(readFileSync(ledgerFile, 'utf8')) : [];
+const ledger = {
+  findValue(value, _sessionId) {
+    return entries.filter((entry) => String(entry.value_text) === String(value) || String(entry.value_num) === String(value));
+  },
+};
+
+const claims = extractNumericClaims(text);
+const result = verifyAnswer(text, { ledger, sessionId: 'probe', userText: '' });
+
+console.log(`答案长度 ${text.length} 字符,候选数字 ${claims.length} 个\n`);
+console.log('raw         | kind      | strict | status     | 说明');
+console.log('------------|-----------|--------|------------|------');
+result.claims.forEach((claim, index) => {
+  const raw = claim.raw.padEnd(11).slice(0, 11);
+  const kind = String(claim.kind).padEnd(9);
+  const strict = claim.severity === 'strict' ? '  yes  ' : '   no  ';
+  const status = String(claim.status).padEnd(10);
+  console.log(`${raw} | ${kind} | ${strict} | ${status} | ${claim.reason ?? ''}`);
+});
+
+console.log('\n裁决:', result.verdict, '|', result.summary);
+if (result.claims.some((claim) => claim.status === 'unverified')) {
+  console.log('\n⚠ 未通过的数字:');
+  for (const claim of result.claims.filter((item) => item.status === 'unverified')) {
+    console.log(`  - ${claim.raw}  [${claim.kind}/${claim.severity}]  ${claim.reason ?? ''}`);
+  }
+}

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
web/dist/assets/index-CR3nqj6D.css


تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
web/dist/assets/index-Cl9HL7vR.js


تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 0
web/dist/assets/index-DlGlAdTE.js


+ 2 - 2
web/dist/index.html

@@ -5,8 +5,8 @@
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <title>海关问数 Agent · 电子元器件进出口数据分析</title>
     <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%231f4fd1'/%3E%3Ctext x='32' y='43' font-size='30' text-anchor='middle' fill='white' font-family='sans-serif'%3E关%3C/text%3E%3C/svg%3E" />
-    <script type="module" crossorigin src="/assets/index-BqfzmH11.js"></script>
-    <link rel="stylesheet" crossorigin href="/assets/index-gwqomBW9.css">
+    <script type="module" crossorigin src="/assets/index-DlGlAdTE.js"></script>
+    <link rel="stylesheet" crossorigin href="/assets/index-CR3nqj6D.css">
   </head>
   <body>
     <div id="root"></div>

+ 13 - 2
web/src/api/types.ts

@@ -75,7 +75,7 @@ export interface ToolResultRecord {
 export interface ClaimChip {
   value: string;
   display: string;
-  status: 'verified' | 'flagged' | 'unverified' | 'exempt';
+  status: 'verified' | 'flagged' | 'unverified' | 'exempt' | 'reference';
   call_id?: string;
   object_id?: string;
   table?: string;
@@ -85,12 +85,23 @@ export interface ClaimChip {
 
 export interface Verification {
   verdict: 'accept' | 'flag' | 'reject';
-  claims: Array<{ raw: string; value: number; display: string; kind: string; status: string; reason?: string }>;
+  claims: Array<{
+    raw: string;
+    value: number;
+    display: string;
+    kind: string;
+    severity: 'strict' | 'soft';
+    status: string;
+    reason?: string;
+  }>;
+  strictClaims: Array<Record<string, unknown>>;
   verified: number;
   flagged: number;
   unverified: number;
   exempt: number;
+  reference: number;
   total: number;
+  strictTotal: number;
   summary: string;
   chips: ClaimChip[];
 }

+ 28 - 4
web/src/components/ChatMessageView.tsx

@@ -1,4 +1,4 @@
-import { useState, type ReactElement } from 'react';
+import { useState, type ReactElement } from 'react';
 import type { ChatMessage, ClaimChip, ToolResultRecord, Verification } from '../api/types';
 import { Badge, DataTable } from './Common';
 import { MiniChart } from './MiniChart';
@@ -108,12 +108,13 @@ export function VerificationPanel({ verification, onChipClick }: { verification:
               <tr>
                 <th>数字</th>
                 <th>状态</th>
+                <th>类型</th>
                 <th>来源</th>
               </tr>
             </thead>
             <tbody>
               {verification.claims.map((claim, index) => (
-                <tr key={index}>
+                <tr key={index} className={claim.severity === 'soft' ? 'soft-claim' : ''}>
                   <td>
                     <button
                       type="button"
@@ -133,8 +134,31 @@ export function VerificationPanel({ verification, onChipClick }: { verification:
                     </button>
                   </td>
                   <td>
-                    <Badge tone={claim.status === 'verified' ? 'success' : claim.status === 'flagged' ? 'warn' : claim.status === 'exempt' ? 'neutral' : 'danger'}>
-                      {claim.status === 'verified' ? '已溯源' : claim.status === 'flagged' ? '估算' : claim.status === 'exempt' ? '豁免' : '无来源'}
+                    <Badge
+                      tone={
+                        claim.status === 'verified'
+                          ? 'success'
+                          : claim.status === 'flagged'
+                            ? 'warn'
+                            : claim.status === 'exempt' || claim.status === 'reference'
+                              ? 'neutral'
+                              : 'danger'
+                      }
+                    >
+                      {claim.status === 'verified'
+                        ? '已溯源'
+                        : claim.status === 'flagged'
+                          ? '估算'
+                          : claim.status === 'exempt'
+                            ? '豁免'
+                            : claim.status === 'reference'
+                              ? '参考'
+                              : '无来源'}
+                    </Badge>
+                  </td>
+                  <td>
+                    <Badge tone={claim.severity === 'strict' ? 'info' : 'neutral'}>
+                      {claim.severity === 'strict' ? '必审' : '参考'}
                     </Badge>
                   </td>
                   <td className="mono">{claim.reason ?? '工具返回值'}</td>

+ 6 - 3
web/src/components/TraceDrawer.tsx

@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useState } from 'react';
 import type { ClaimChip } from '../api/types';
 import { api } from '../api/client';
 import { Badge, Spinner } from './Common';
@@ -76,8 +76,11 @@ export function TraceDrawer({ sessionId, chip, onClose, onOpenRow }: TraceDrawer
 
   if (!chip) return null;
 
-  const statusText = { verified: '已溯源', flagged: '估算', unverified: '无来源', exempt: '豁免' }[chip.status];
-  const statusTone = chip.status === 'verified' ? 'success' : chip.status === 'flagged' ? 'warn' : chip.status === 'unverified' ? 'danger' : 'neutral';
+  const statusText =
+    { verified: '已溯源', flagged: '估算', unverified: '无来源', exempt: '豁免', reference: '参考计数' }[String(chip.status)] ??
+    String(chip.status);
+  const statusTone =
+    chip.status === 'verified' ? 'success' : chip.status === 'flagged' ? 'warn' : chip.status === 'unverified' ? 'danger' : 'neutral';
 
   return (
     <div className="drawer-backdrop" onClick={onClose} role="presentation">

+ 5 - 0
web/src/styles/app.css

@@ -1698,3 +1698,8 @@ textarea:focus {
   gap: 8px;
   align-items: center;
 }
+
+/* 参考性计数(不参与核验):整行降低对比度 */
+.verification-table tr.soft-claim td {
+  color: var(--text-faint);
+}

+ 7 - 4
web/test/render.test.tsx

@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
 import { renderToStaticMarkup } from 'react-dom/server';
 import { ChatMessageView, Markdownish, TraceChips, VerificationPanel } from '../src/components/ChatMessageView';
 import App from '../src/App';
@@ -56,15 +56,18 @@ describe('组件渲染(服务端渲染,不需要浏览器)', () => {
         verification={{
           verdict: 'flag',
           claims: [
-            { raw: '400316.13', value: 400316.13, display: '400316.13', kind: 'money', status: 'verified' },
-            { raw: '14.92万', value: 149200, display: '14.92万', kind: 'money', status: 'flagged', reason: '台账中无精确来源,但已明确标注为估算' },
+            { raw: '400316.13', value: 400316.13, display: '400316.13', kind: 'money', severity: 'strict', status: 'verified' },
+            { raw: '14.92万', value: 149200, display: '14.92万', kind: 'money', severity: 'strict', status: 'flagged', reason: '台账中无精确来源,但已明确标注为估算' },
           ],
           verified: 1,
           flagged: 1,
           unverified: 0,
           exempt: 0,
+          reference: 0,
           total: 2,
-          summary: '通过但需提示:共 2 个数字,已溯源 1 个,估算 1 个',
+          strictTotal: 2,
+          strictClaims: [],
+          summary: '通过但需提示:共 2 个数字,必审 2 个,已溯源 1 个,估算 1 个',
           chips: [],
         }}
       />,

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است