Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(skills): add value-investing toolkit (rigor + audit + 4 skills + committee preset)

sambazhuef74a22370d9
diff --git a/agent/src/skills/bottleneck-hunter/SKILL.md b/agent/src/skills/bottleneck-hunter/SKILL.md
new file mode 100644
index 000000000..d426814e9
--- /dev/null
+++ b/agent/src/skills/bottleneck-hunter/SKILL.md
@@ -0,0 +1,209 @@
+---
+name: bottleneck-hunter
+category: strategy
+description: "Supply-chain bottleneck arbitrage. Given a super-trend (AI infra, energy transition, defense, semiconductor reshoring, space economy), decompose its physical supply chain down to Layer 2/3 choke points (optics, lasers, InP/SOI substrates, IC substrates, probe cards, specialty fiberglass...) and surface under-the-radar listed companies sitting on each bottleneck. Scores each link on 6 scarcity criteria, applies mandatory valuation gates (PS/PE/safety-margin) via the financial_rigor tool, and Munger-style reverse-validates. Outputs a ranked bottleneck opportunity board. Use when the user wants hidden beneficiaries of a structural trend rather than already-priced leaders."
+---
+
+# 供应链瓶颈猎手:AI 驱动的全球产业链瓶颈套利
+
+对一个超级趋势(用户指定,如"AI 基础设施""能源转型")执行供应链瓶颈扫描与套利机会挖掘。
+
+## 核心理念
+
+不问"AI 推荐什么股票",问"如果这个趋势继续扩张,哪一环会先不够用?"
+
+传统投研盯龙头、盯已知赛道。本技能反过来:**从物理供应链的咽喉位置出发,找那些没人注意但一旦断货整个行业都得停下来等的公司**。
+
+超额收益来源:第一层瓶颈(GPU、HBM、电力)已被充分定价。真正的 alpha 在**第二层、第三层**——光模块、激光器、InP 衬底、SOI 晶圆、外延设备、晶圆级测试、IC 载板、特殊玻纤等。
+
+## 第一步:超级趋势确认
+
+### 趋势筛选标准
+
+| 标准 | 要求 | 验证方法 |
+|------|------|---------|
+| 持续性 | 至少 3-5 年确定性增长 | 搜索行业预测、资本开支计划 |
+| 物理性 | 需要实际硬件/材料/设备建设 | 区分"软件升级"和"物理扩建" |
+| 规模性 | 全球资本开支 > 500 亿美元/年 | 搜索头部玩家 capex 指引 |
+| 加速性 | 需求增速 > 供给扩产速度 | 对比需求增长率 vs 产能扩张计划 |
+
+用 `web_search` 验证。参考超级趋势:AI 基础设施、能源转型(核电/电网/储能)、国防现代化、半导体再工业化、太空经济。用户指定具体趋势则只聚焦该趋势。
+
+### 趋势验证输出
+
+```
+趋势名称:
+核心驱动力:(一句话)
+已发生的验证事件(至少3个):
+ 1. [日期] [事件] [来源]
+ 2.
+ 3.
+资本开支规模:全球约 $XX 亿/年,增速 YY%
+供需缺口判断:需求增速 > 供给扩产速度? 是/否/不确定
+趋势确认:✅ 可追踪 / ❌ 证据不足,暂不追踪
+```
+
+## 第二步:供应链物理拆解
+
+**不停留在概念层,拆到物理实体。**
+
+```
+Layer 0(终端):最终产品/服务
+Layer 1(核心组件):已被市场充分关注的核心硬件 ⬆ 定价充分,alpha 有限
+Layer 2(子组件/材料):支撑核心组件的零部件和材料 ⬇ 关注度低,alpha 集中区
+Layer 3(上游设备/原料):制造子组件所需的设备和原材料
+Layer 4(基础设施):电力、冷却、土地、人才、认证
+```
+
+### 以 AI 基础设施为例的拆解模板
+
+```
+Layer 0:AI 模型训练/推理服务
+Layer 1:GPU/加速器、HBM 内存、服务器、数据中心
+Layer 2(重点扫描区):
+ ├─ 网络互联:光模块、光纤、交换芯片、铜缆
+ ├─ 光通信核心:激光器(EML/VCSEL/CW)、调制器、光探测器
+ ├─ 半导体材料:InP 衬底、GaAs 衬底、SOI 晶圆、SiC 衬底
+ ├─ 先进封装:CoWoS 载板、HBM TSV、ABF 基板膜
+ ├─ PCB/载板:高频高速 PCB、IC 载板、特殊玻纤布
+ ├─ 测试:晶圆级测试(Probe Card)、老化测试、ATE
+ ├─ 散热/冷却:液冷系统、CDU、浸没式冷却液
+ └─ 电力连接:母线槽、UPS、配电柜、变压器
+Layer 3:
+ ├─ 外延设备:MOCVD、MBE
+ ├─ 光刻/刻蚀:特殊波长光刻、InP 刻蚀
+ ├─ 原材料:高纯金属(铟、镓、锗)、特气、靶材
+ └─ 认证/标准:MSA 标准、Telcordia 认证
+Layer 4:电力(核电/天然气/输变电)、冷却水、数据中心土地/许可
+```
+
+对其他趋势,用 `web_search` 检索:`{趋势} supply chain bottleneck`、`{趋势} shortage critical component`、`{趋势} capacity constraint`、`{趋势} sole source supplier`。
+
+## 第三步:瓶颈识别——寻找"咽喉"
+
+对 Layer 2-3 的每个环节,逐条评估 6 条标准:
+
+| # | 标准 | 问题 | 得分 |
+|---|------|------|------|
+| 1 | 供给集中度 | 全球供应商 ≤ 3 家? | 🔴 ≤2 家 / 🟡 3-5 家 / 🟢 >5 家 |
+| 2 | 扩产周期 | 新增产能需要多久? | 🔴 >2 年 / 🟡 1-2 年 / 🟢 <1 年 |
+| 3 | 替代难度 | 能否用其他技术/材料替代? | 🔴 不可替代 / 🟡 部分可替代 / 🟢 易替代 |
+| 4 | 产能利用率 | 当前产能利用率? | 🔴 >90% / 🟡 70-90% / 🟢 <70% |
+| 5 | 需求增速 | 下游需求增速? | 🔴 >50%/年 / 🟡 20-50% / 🟢 <20% |
+| 6 | 客户验证周期 | 新供应商进入需多久验证? | 🔴 >1 年 / 🟡 6-12 月 / 🟢 <6 月 |
+
+**瓶颈评级**:🔴×≥4 → **S 级**(单点故障,最高优先级);🔴×3 → **A 级**(严重受限);🔴×1-2 → **B 级**(有压力但可控);无 🔴 → 非瓶颈,跳过。
+
+## 第四步:公司筛选——从瓶颈到标的
+
+对每个 S/A 级瓶颈,用 `web_search` / `screen_market` 找相关上市公司。
+
+### 初筛标准
+
+| 标准 | 要求 |
+|------|------|
+| 上市状态 | 已上市(A/港/美/日/台/欧) |
+| 瓶颈业务占比 | >30% 收入来自瓶颈环节 |
+| 市值 | 优先 < 100 亿美元(大市值已充分定价) |
+| 流动性 | 日均成交额 > 100 万美元 |
+
+### 估值检查(必须执行,不可跳过)
+
+**瓶颈真实 ≠ 投资机会。** 对每家公司用 `financial_rigor`(`command=verify_valuation`)计算 PE/PB/ROE/FCF Yield,用 `financial_rigor`(`command=three_scenario`)做情景估值:
+
+- **红灯**(满足任一 → 信号强度封顶 ★★,标"⚠️ 估值透支"):市值 > TAM 的 20%;PS > 30x 且收入增速 < 100%;市值 > 5 年乐观收入预测的 10 倍;增发后 60 天股价翻倍。
+- **黄灯**(需额外解释,否则降级):亏损 + PS > 15x;PS 是同行盈利公司的 5 倍以上;PE > 80x(需算 PEG)。
+- **绿灯**(加分):PS < 10x 且收入在增长;PE < 30x 且有护城河(标"估值有安全边际")。
+
+**估值合理性检验(必做)**:用 `financial_rigor`(`command=three_scenario`)回答——"以当前市值买入,假设最乐观情景全部兑现,10 年后以 25x PE 退出,年化回报是多少?" 年化 < 10% → 标"当前价格不具备安全边际"。
+
+> 估值检查的目的是防止推荐"PS 100 倍的亏损公司",而不是排除所有高估值早期公司。关键是增速、TAM、竞争格局能否支撑。
+
+## 第五步:交叉验证——不只听一个故事
+
+### 正向验证
+
+| 验证项 | 问题 |
+|--------|------|
+| 客户验证 | 头部客户是否已签约/导入?(查公告、客户财报) |
+| 收入验证 | 瓶颈是否已体现在收入增长?(查近 2-3 季财报) |
+| 价格验证 | 产品是否涨价?(查报价、研报) |
+| 产能验证 | 产能是否真紧张?(查交期、客户抱怨) |
+| 资本验证 | 是否有扩产 capex?(查公司指引) |
+
+用 `get_financial_statements` / `get_stock_news` / `web_search` 取数。
+
+### 反向验证(芒格式否定)
+
+- 聪明人为什么不买这只股票?
+- 这个瓶颈能被绕过吗?有什么替代路线?
+- 中国/其他玩家能不能很快复制产能?
+- 终端需求如果放缓 50%,这家公司会怎样?
+- 管理层过去有没有在高点增发稀释?
+- 当前估值隐含了什么增长假设?
+
+## 第六步:输出——瓶颈机会看板
+
+### 排名表
+
+| 排名 | 公司 | 代码 | 市值 | 年收入 | PS | PE | 瓶颈环节 | 评级 | 市场份额 | 收入增速 | 信号强度 | 估值判断 |
+|------|------|------|------|--------|-----|-----|---------|------|---------|---------|---------|---------|
+
+**市值、年收入、PS、PE 为必填项,不可用"待核实"跳过。** 无法获取财务数据时,信号强度不得超过 ★★。
+
+信号强度(估值检查直接影响):
+- ★★★★★ 多重交叉验证 + 客户已导入 + 收入已体现 + 估值绿灯
+- ★★★★ 大部分验证通过 + 估值绿灯或黄灯(附解释)
+- ★★★ 逻辑成立但部分待验证 + 估值黄灯可接受(如高增速早期)
+- ★★ 早期信号,或瓶颈逻辑成立但估值红灯
+- ★ 纯概念、未验证
+
+完成后,对报告用 `report_audit`(`command=extract` → 逐点核验 → `command=verdict`)做准出门,确保数字无幻觉。
+
+### 一页纸摘要模板
+
+```
+🎯 {公司}({代码})— {一句话瓶颈定位}
+
+为什么是瓶颈:(2-3 句)
+为什么是这家:(2-3 句)
+
+催化剂时间线:
+- 近期(1-3 月):[财报/产能投产/客户验证]
+- 中期(3-12 月):[行业趋势/扩产节点]
+
+主要风险:1. 2.
+
+关键数据:市值/年收入/PS/PE/收入增速/瓶颈业务占比
+估值安全边际:10 年 25x PE 退出法,年化回报 XX%。结论:有/无安全边际。
+交叉验证状态:✅ 客户验证 / ✅ 收入验证 / ⚠️ 估值透支 / ❌ 未验证项
+
+结论:深入研究 / 加入观察名单 / 暂不追踪
+```
+
+把报告用 `write_file` 写入报告目录(如 `reports/bottleneck-map/{趋势}-bottleneck-{YYYYMMDD}.md`)。
+
+## 第七步:存量更新——瓶颈地图动态维护
+
+每次运行时:① 检查已识别瓶颈是否仍成立(新供应商?产能已扩张解除?替代技术突破?);② 扫描新瓶颈(`web_search` 近 7 天 supply chain / shortage / bottleneck 新闻);③ 更新评级(升级/降级/解除)。
+
+## AI 研究偏见自觉
+
+| 偏见 | 表现 | 应对 |
+|------|-----|------|
+| 龙头偏好 | 搜索结果被大市值公司占据 | 刻意搜索小市值供应商,加 "small cap" 关键词 |
+| 英文偏好 | 遗漏日韩台公司 | 必须搜索日/韩/台湾市场供应商 |
+| 叙事偏好 | 被"AI 概念"标签吸引 | 只看实际供应链位置,不看市场标签 |
+| 确认偏见 | 找到瓶颈后只找正面证据 | 强制执行第五步反向验证 |
+| 时效偏见 | 依赖过时信息 | 优先搜索最近 30 天的数据 |
+
+## 核心原则(最高优先级)
+
+1. **不让 AI 推荐股票,让 AI 拆供应链**——问题比答案重要。
+2. **物理优先**——只关注需要实际物理产品/材料/设备的环节。
+3. **第二层、第三层**——不追已被充分定价的龙头。
+4. **交叉验证**——每个结论至少 2 个独立信源。
+5. **诚实面对不确定性**——找不到数据就写"数据不足",不用推测填充。
+6. **瓶颈有时效性**——每个瓶颈都会被解除,关键是判断时间窗口。
+7. **小市值 ≠ 好机会**——小市值也可能是烂公司,必须过财务质量关。
+8. **瓶颈真实 ≠ 投资机会**——PS > 30x 或仍亏损时,当前价格就不是买点。**估值是硬门槛,不可被瓶颈纯正度、信号强度或叙事吸引力覆盖。** 宁可错过一个涨了的瓶颈股,也不要在 100 倍 PS 买入一家亏损公司。
diff --git a/agent/src/skills/management-deep-dive/SKILL.md b/agent/src/skills/management-deep-dive/SKILL.md
new file mode 100644
index 000000000..5959b5c28
--- /dev/null
+++ b/agent/src/skills/management-deep-dive/SKILL.md
@@ -0,0 +1,209 @@
+---
+name: management-deep-dive
+category: analysis
+description: "Deep management assessment — the 'buying a stock is buying a person' layer. For a company or a named executive, evaluate integrity (promise-vs-delivery tracking, crisis behavior, stakeholder treatment), ability (strategic foresight, execution, capital-allocation record) and governance (equity structure, compensation, related-party deals). Outputs a weighted score across integrity / ability / capital-allocation / governance plus Duan Yongping's 3-question verdict ('would you hand this person your money for 10 years'). Use when standard research leaves management quality uncertain, or when management IS the investment thesis."
+---
+
+# 管理层纵深研究:买股票就是买人
+
+对一个公司(或 `人名 公司名`)做管理层深度研究。
+
+> "买股票就是买人。找到你信任的人,然后长期持有。" —— 段永平
+>
+> "评估管理层,要看他们在没人看着的时候做什么。" —— 巴菲特
+
+## 设计理念
+
+多数投研对管理层的评估停留在表面:履历、持股、薪酬。但巴菲特花大量时间和管理层交流,李录说投资的本质是投人,段永平说买股票就是买人。
+
+AI 无法和管理层吃饭,但可以通过公开信息做到:① **追踪管理层的话与做是否一致**(承诺 vs 兑现);② **分析每一笔重大资本配置决策的回报**;③ **从困难时期的决策推断品格**;④ **通过员工/商家/客户反馈侧面验证**。
+
+适用场景:标准研究中管理层评分不确定(★★★ 或以下)、或管理层是核心投资逻辑时,用本技能做纵深。
+
+## 第一步:识别关键管理层
+
+用 `web_search` / `get_stock_profile` / `get_sec_filings` 确认关键人物:
+
+| 角色 | 姓名 | 任期 | 背景 | 持股/期权 |
+|------|------|------|------|----------|
+| CEO/董事长 | | | | |
+| CFO | | | | |
+| 创始人(如不在位) | | | | |
+| 实际控制人(如不同于 CEO) | | | | |
+| 其他关键高管 | | | | |
+
+**区分"谁在做决策"和"谁的名字在头衔上"**——有些公司创始人虽卸任仍是灵魂人物(如黄峥之于拼多多)。
+
+然后收集四类数据(可顺序用 `web_search` + `get_stock_news` + `get_financial_statements` + `get_sec_filings`,或用 `run_swarm` 并行):① CEO 公开发言与预测记录;② 资本配置决策(并购/回购/分红/新业务);③ 治理结构与薪酬;④ 侧面验证(员工/客户/行业口碑)。
+
+## 第二步:CEO 能力圈评估
+
+### 战略眼光
+
+用 `web_search` 搜 CEO 过去 5 年公开发言(股东信、电话会、采访、社交媒体),提取其判断:
+
+| 时间 | CEO 的判断/预测 | 实际结果 | 准确度 |
+|------|----------------|---------|:------:|
+| | "我们认为 X 市场会..." | X 市场实际... | ✅/❌ |
+
+关键问题:有没有做过超前于市场的正确判断?有没有在大家都看好时保持冷静?对行业的理解是跟随市场还是独立思考?
+
+### 执行能力
+
+| 维度 | 评估 | 证据 |
+|------|------|------|
+| 战略到落地 | 说了的事做到了吗? | |
+| 组织能力 | 能吸引和留住人才? | |
+| 危机处理 | 遇到困难时怎么应对? | |
+| 迭代速度 | 犯错后纠正的速度? | |
+
+## 第三步:诚信度评估(最重要)
+
+> 巴菲特:"我们寻找三种品质:正直、智慧、精力。如果没有第一种,后两种会害死你。"
+
+### 承诺 vs 兑现追踪
+
+从过去 3 年财报电话会、股东信、公开采访中(`get_sec_filings` / `web_search` / `get_stock_news`),提取管理层做过的**具体承诺**:
+
+| # | 时间 | 承诺内容 | 承诺场合 | 兑现情况 | 评价 |
+|---|------|---------|---------|---------|------|
+| 1 | | "2025 年实现 X 业务盈利" | 2024 年报电话会 | | ✅/⚠️/❌ |
+
+| 承诺兑现率 | 评价 |
+|:---------:|------|
+| >80% | 优秀——说到做到 |
+| 60-80% | 合格——大方向对,执行有偏差 |
+| 40-60% | 令人担忧——承诺过多,交付不足 |
+| <40% | 严重问题——不可信赖 |
+
+### 困难时期的表现
+
+搜公司历史上的重大危机(股价暴跌、业绩 miss、监管冲击、竞争加剧),分析管理层应对:是主动沟通还是躲避?归因内部还是甩锅外部?趁机做困难但正确的事,还是短期讨好市场?
+
+### 对利益相关方的态度
+
+| 利益相关方 | 管理层态度 | 证据 | 评价 |
+|-----------|-----------|------|------|
+| 股东 | 尊重/忽视/利用 | | |
+| 员工 | 善待/压榨/漠视 | | |
+| 客户/用户 | 以客户为中心/短期榨取 | | |
+| 商家/供应商 | 公平合作/极端压价 | | |
+| 监管/社会 | 合规配合/打擦边球 | | |
+
+> 李录:"对利益相关方的态度决定了企业的长期生命力。短期压榨能提升效率,但长期会损害生态。"
+
+## 第四步:资本配置能力
+
+这是巴菲特最看重的——**每赚一块钱,管理层能把它变成多少钱?**
+
+搜索过去 5 年重大资本配置决策(`web_search` / `get_financial_statements`),逐笔评估:
+
+**并购记录**
+
+| 时间 | 收购标的 | 金额 | 战略逻辑 | 事后回报 | 评分(1-5) |
+|------|---------|------|---------|---------|:---------:|
+
+**回购记录**(用 `financial_rigor` 的 `command=verify_valuation` 校验回购时与当前的 PE 等)
+
+| 时间 | 回购金额 | 平均回购价 | 当时 PE | 事后回看 | 评分(1-5) |
+|------|---------|-----------|:------:|---------|:---------:|
+
+**分红记录**
+
+| 年份 | 分红金额 | 分红率 | 同期 FCF | 是否可持续 |
+|------|---------|:------:|---------|:---------:|
+
+**新业务投资**
+
+| 时间 | 投资领域 | 累计投入 | 当前状态 | 回报评估 | 评分(1-5) |
+|------|---------|---------|---------|---------|:---------:|
+
+### 资本配置评分
+
+| 维度 | 评分(1-5) | 说明 |
+|------|:---------:|------|
+| 并购纪律 | | 是否在合理价格收购?整合如何? |
+| 回购时机 | | 低估时回购、高估时停止? |
+| 分红合理性 | | 分红率是否与 FCF 匹配? |
+| 新业务投资 | | 成功率?止损纪律? |
+| 现金管理 | | 现金储备合理?是否囤积过多? |
+| **综合** | | |
+
+> 巴菲特标准:理想管理层有好机会时果断投资,没好机会时积极回购/分红,永远不做高价并购。
+
+## 第五步:治理结构评估
+
+### 股权结构
+
+| 项目 | 详情 | 风险评估 |
+|------|------|---------|
+| AB 股/超级投票权? | | |
+| 创始人/实控人持股? | | |
+| VIE 结构? | | |
+| 独立董事是否真独立? | | |
+| 大股东近期增减持? | | |
+
+### 薪酬合理性
+
+| 高管 | 年度总薪酬 | 占净利润比 | 同行对比 | 是否合理 |
+|------|-----------|:--------:|:------:|:------:|
+
+激励结构与长期股东利益一致,还是鼓励短期行为?
+
+### 关联交易
+
+| 关联方 | 交易内容 | 金额 | 是否公允 | 风险 |
+|--------|---------|------|:------:|------|
+
+## 第六步:侧面验证
+
+AI 无法面对面交流,但通过公开渠道侧面验证。**注意**:取决于公开可搜索的内容,可能不完整,标注来源和可得性。
+
+- **员工视角**:`web_search` 搜 Glassdoor 评分摘要、知乎讨论等(脉脉等需登录的标注"用户可自行补充")——企业文化、管理层评价、工作强度、薪酬满意度、发展前景。
+- **客户/商家视角**:App Store 评分趋势、消费者投诉、商家论坛——产品满意度、客户服务、商家关系。
+- **行业口碑**:同行和业内人士对该管理层的评价。
+
+## 第七步:CEO 离开后的情景分析
+
+> 巴菲特:"好公司应该是傻瓜都能经营的——因为迟早会有傻瓜来经营。"
+
+- 如果 CEO 明天离开,公司能正常运转吗?
+- 现有管理团队深度如何?有明确继任者吗?
+- 竞争优势依赖 CEO 个人,还是组织/系统?
+- 历史上的管理层交接是否顺利?
+
+## 第八步:输出管理层评估报告
+
+结构:① 关键人物速览;② 诚信度评估(承诺兑现率 + 困难时期 + 利益相关方);③ 能力评估(战略眼光 + 执行 + 资本配置);④ 治理结构;⑤ 侧面验证;⑥ 综合评分与结论。
+
+### 综合评分
+
+| 维度 | 权重 | 评分(1-5) | 加权 |
+|------|:----:|:---------:|:----:|
+| 诚信度 | 35% | | |
+| 战略与执行 | 25% | | |
+| 资本配置 | 25% | | |
+| 治理结构 | 15% | | |
+| **综合** | 100% | | |
+
+### 段永平的"买人"三问
+
+1. 这个人是否**正直**?(诚实、不占股东便宜)
+2. 这个人是否有**能力**?(战略眼光 + 执行力 + 资本配置)
+3. 你愿意把钱交给这个人管 **10 年**吗?
+
+三个"是" = ★★★★★;前两个"是" = ★★★★;只有第一个"是" = ★★★;第一个不是"是" = ★(不投)。
+
+## 第九步:保存报告
+
+用 `write_file` 写入 `reports/{公司}-management-{YYYYMMDD}.md`。
+
+完成后可用 `report_audit`(`extract` → 逐点核验 → `verdict`)对报告里的数字做准出门。
+
+## 关键原则
+
+- **诚信是一票否决项**——能力不足可以学,品格有问题无法修。
+- **看行为不看言辞**——说什么不重要,做了什么才重要。
+- **在困难中看真相**——顺风时谁都是好 CEO,逆风时才见真功夫。
+- **资本配置是终极考试**——赚钱容易,把赚到的钱配置好难。
+- **不要爱上管理层**——保持客观,即使你欣赏的人也可能犯大错。
diff --git a/agent/src/skills/private-company-research/SKILL.md b/agent/src/skills/private-company-research/SKILL.md
new file mode 100644
index 000000000..025c449f9
--- /dev/null
+++ b/agent/src/skills/private-company-research/SKILL.md
@@ -0,0 +1,160 @@
+---
+name: private-company-research
+category: analysis
+description: "Deep research framework for pre-IPO / private companies (Ant Group, SpaceX, Stripe, ByteDance...). Six analyst lenses — business model, financial forensics, competitive landscape, risk & governance, tech & IP, alternative-data signals — run in parallel via run_swarm, then cross-validated for signal consistency before any verdict. Built around the core challenge of private-company work: information is scarce, so every data point carries a confidence label (high / medium / low), inference is shown separately from fact, and 'I don't know' is a valid output. Outputs a fair-value range, exit-path analysis, and an information-gap map. Use for any unlisted company where you need to judge what the business is actually worth."
+---
+
+# 未上市公司研究:多维度深度研究框架
+
+对一家未上市公司(如蚂蚁、小红书、SpaceX、Stripe)做深度研究。
+
+**最终目标**:在信息天然稀缺的条件下,尽可能还原这家公司的**真实价值**——不是市场给的估值,而是生意本身值多少钱。
+
+## 框架特点
+
+未上市 vs 上市研究的核心差异:无标准化财报(需多源拼凑、交叉验证);估值锚定少(依赖融资轮次、可比公司法、情景推演);信息不对称大(需"拼图式"研究);退出路径不确定(IPO/并购/二级转让均有可能)。
+
+## AI 研究偏见自觉(核心前提)
+
+未上市公司是 AI 研究偏见最严重的领域。警惕:
+
+- **虚假保守**——资料少时 AI 倾向给保守/模糊结论,但资料少 ≠ 公司不好。
+- **虚假精确**——为填满模板,AI 可能用"合理推测"伪装成"有据分析"。
+- **对标陷阱**——强行与上市公司对标时,继承上市估值逻辑,忽略独特价值。
+- **幸存者偏差**——网上能搜到的多是公司主动传播的好消息。
+
+**应对**:宁可留白说"不知道",也不用推测填满表格伪装确定性;每个数据点标注置信度(🟢高/🟡中/🔴低);区分"可验证的事实"与"AI 的推理";信息极度稀缺时切换"第一性原理模式",只回答:① 这门生意解决什么真实问题?② 为什么是这个团队?③ 成功天花板 / 失败死点?④ 当前关键验证节点?
+
+> 反向利用信息不对称:市场对未上市公司信息少 → 定价效率低 → 恰恰可能是超额收益来源。
+
+## 执行编排
+
+六个维度建议**并行**研究(用 `run_swarm`,每个 worker 一个维度;或顺序用 `web_search` / `web_search` 工具族逐维研究):
+
+| 角色 | 核心视角 |
+|------|----------|
+| business-decoder | 商业模式拆解 + 产品/用户分析:"这门生意的本质是什么" |
+| financial-detective | 财务数据拼凑 + 估值推演:"信息缺失下还原真实财务面貌" |
+| competitive-mapper | 行业格局 + 竞争 + 替代威胁:"谁在竞争,谁可能颠覆" |
+| risk-governance-analyst | 风险全景 + 管理层/治理/投资人:"什么可能出错,谁在掌舵" |
+| tech-ip-analyst | 技术栈/专利/研发/护城河:"技术壁垒真假与持久性" |
+| signal-miner | 替代数据:招聘/专利/诉讼/App/供应链:"常规信息外的蛛丝马迹" |
+
+team-lead(你自己)负责统筹、信息拼图、交叉验证、输出最终报告。
+
+## 维度 1:商业模式与用户(business-decoder)
+
+- **核心生意定义**:一句话本质(段永平式:用朴素语言讲给聪明但不懂行的人)。解决什么问题?为谁创造价值?公司不存在用户会怎样?需求刚性(下行时会被砍吗)?
+- **收入模式**:广告/佣金/订阅/抽成/金融/SaaS/硬件/授权;各线占比与趋势;变现效率(ARPU/Take Rate/转化率);经常性 vs 一次性占比;集中度;收入确认是否激进。
+- **单位经济(U E)**:CAC(付费 vs 自然,分渠道,趋势)、LTV、LTV/CAC、回本周期、边际成本、规模经济拐点。
+- **产品矩阵与飞轮**:核心+延伸+孵化;网络/数据/规模飞轮如何运转;产品迭代速度。
+- **用户分析**:MAU/DAU(从 QuestMobile/Sensor Tower/SimilarWeb 推算)、S 曲线阶段、DAU/MAU、留存(次/7/30 日)、画像、口碑(App Store 评分趋势、社交舆情)。
+- **护城河(6 维 ★1-5)**:网络效应、转换成本、品牌心智、数据壁垒、监管牌照、规模经济——每项给证据 + 趋势(加宽/稳定/收窄)+ 持久性。综合评级:宽/中/窄/无。
+
+## 维度 2:财务数据拼凑与估值(financial-detective)
+
+未上市公司没有标准财报,多源拼凑、交叉验证,**每个数据标明来源、时间、置信度、推算方法**。
+
+**数据来源优先级**:🟢 招股书/监管文件、母公司年报关联披露、监管处罚文件、债券/ABS 说明书 → 🟡 工商登记、融资新闻、第三方研报、深度媒体(晚点/The Information/36 氪/Bloomberg)→ 🔴 行业推算、前员工爆料。
+
+**关键指标推算**:收入(规模/增速/结构/量×价分解)、成本(毛利/研发/销售/管理费用率,对标同业)、利润(EBITDA/净利/盈利时间线)、现金流(经营现金流/烧钱速度/现金跑道)、效率(人均收入/资本效率)。
+
+**交叉验证**:同一指标多来源全部列出,不同方法推算检查是否收敛,标注"孤证"数据。
+
+**融资历史**:完整时间线(轮次/金额/估值/领投),分析估值增长曲线健康度、融资间隔、是否 Down Round、老股东是否持续加注、最新轮条款推测(优先清算权/反稀释/对赌)对普通股价值的影响。
+
+**估值(多方法交叉)**:① 最近融资估值法(考虑优先清算权打折 20-40%);② 可比上市公司法(选 3-5 家,对比 PS/PE/EV/EBITDA,加流动性折价 20-30%);③ DCF 情景(悲/中/乐,每假设有论据);④ 终局市值倒推(5/10 年终态 → 倒推当前合理区间 → 隐含年化回报);⑤ 交易对标法(近 2 年同业并购/融资倍数)。
+
+**估值综合**:各方法是否收敛?差异大分析原因。区分"合理估值"和"保守估值(安全边际)"。
+
+## 维度 3:行业与竞争(competitive-mapper)
+
+- **市场**:TAM/SAM/SOM、渗透率、行业阶段(萌芽/成长/成熟/衰退)、增长驱动。
+- **产业链全景**(文本图):上游→公司环节(利润池占比)→下游;议价能力;结构性变化。
+- **波特五力**(★1-5):行业内竞争、新进入者、替代品、供应商、买方。
+- **竞争扫描**:直接/间接/替代/潜在进入者(巨头)——份额、融资、优势、劣势、威胁等级。2-3 个最直接对手多维对比。
+- **竞争动态**:近 12 月变化;从招聘/专利/产品推推断对手战略;技术(尤其 AI)与监管对格局的影响;赢家通吃 vs 多寡头。
+- **情景推演**:公司胜出 / 均势共存 / 被颠覆,各自条件与概率。
+- **全球对标**:海外对标公司的发展路径、估值、上市表现,及对标的局限性。
+
+## 维度 4:风险与治理(risk-governance-analyst)
+
+- **创始人/CEO**:背景、战略眼光(过去 3 年预判准确度)、执行力(承诺兑现)、格局价值观、争议事件。★1-5。
+- **核心团队**:高管背景、近 2 年人才流动(谁走/谁来/净流入)、互补性、文化信号(Glassdoor/脉脉,趋势比绝对值重要)、关键人依赖度。
+- **股权与治理**:创始人控制权(AB 股/一致行动/VIE)、稀释趋势、员工持股;董事会构成、关联交易、同业竞争、大小股东利益冲突。
+- **投资人阵容**:领投品牌背书、产业资本协同、退出压力(基金存续期/二级抛售/对赌到期)、红旗信号(声誉不佳投资人/早期清仓/老股东不跟投)。
+- **全维度风险清单**:监管/竞争/技术/人才/融资/IPO/地缘/商业化/治理/合规/宏观/ESG——每项概率×影响×严重度×可对冲性×监控指标。
+- **退出路径**:A/港/美 IPO、并购、二级转让、SPAC、长期不退出——可能性、时间窗、估值、前提、障碍。
+- **最坏情景(芒格逆向)**:3 种具体失败路径及概率;清算价值;聪明人为什么不投(至少 5 条);类似公司失败案例;"论文已破"的信号。
+
+## 维度 5:技术与知识产权(tech-ip-analyst)
+
+- **技术栈**:从招聘/博客/开源/演讲推断;技术债信号(大量招重构岗、栈切换、故障投诉)。
+- **专利**(Google Patents/CNIPA/USPTO):总数/申请中/近 2 年新增/领域分布/引用/国际布局;质量(核心专利?领域匹配?诉讼?);趋势;对手对比。
+- **研发**:投入(人数/费用率,对标)、产出(论文/会议/开源/博客)、效率(研发到落地速度、商业转化率)。
+- **技术人才**:核心领导者背景、人才密度(顶尖机构占比)、薪酬竞争力、流失信号、招聘方向(反映战略)。
+- **技术护城河(★1-5)**:算法/模型、数据、工程、人才、生态——每项持久性。AI 时代技术壁垒半衰期可能很短。
+- **AI/新技术影响**:公司是 AI 变革受益者还是被颠覆者?
+
+## 维度 6:替代数据信号(signal-miner)
+
+> 未上市公司常规信息有限,替代数据往往比新闻报道更接近真实经营。
+
+- **招聘**(LinkedIn/Boss/脉脉/Indeed):规模趋势、结构(研发/产品/销售/数据/国际化/合规/IR)——招 IR = IPO 信号;招合规 = 监管或 IPO;岗位 JD 技术栈 = 战略方向。
+- **App/产品**(App Store/七麦/SimilarWeb):排名、评分趋势、下载量、更新频率、差评集中点、Web 流量。
+- **舆情**(微博/知乎/小红书/X/Reddit):官方互动数据、自发讨论热度情感、KOL 评价、负面事件、内部人爆料。
+- **工商法律**(天眼查/企查查):注册资本/实缴/股东变更/子公司(新设=新业务,注销=收缩)/经营范围变更;诉讼/仲裁/处罚/被执行记录。
+- **供应链**:核心供应商(上市则查财报披露)、招标采购、合作评价。
+- **数字足迹**:注册域名(新域=新业务)、子域名(api/pay 暗示架构)、商标(新品牌)。
+- **行业曝光**:高管会议演讲、奖项榜单、政府/协会互动、媒体曝光频率质量。
+- **二级交易信号**(如有):SharesPost/EquityZen/微信群老股,隐含估值 vs 最近融资,员工抛售期权。
+
+**反常信号清单(最重要)**:与对外叙事不一致、与行业常识不符、突然变化(招聘急缩/高管密集离职)、无法解释的现象。
+
+## 交叉验证(team-lead 必做)
+
+汇总前,team-lead 必须:
+
+1. **数据冲突仲裁**:同一指标不同来源是否一致?冲突时列出全部,说明采信哪个及理由。
+2. **信号一致性检验**(矩阵):业务增长 vs 招聘趋势?技术领先叙事 vs 专利/人才数据?估值水平 vs 竞争地位?管理层叙事 vs 实际行动信号?(矛盾要解释)
+3. **信息拼图**:白区(已知)/灰区(有线索不确定)/黑区(完全未知)。
+4. **反偏见检查**:是否"正面详、负面略"?每个正面判断是否有反面检验?
+
+## 最终报告结构
+
+1. **一句话结论**(50-100 字):生意值多少钱,为什么。
+2. **公司画像速览**(含置信度列)。
+3. **六维评分总表**(每维 ★1-5 + 核心判断 + 置信度 + 信息完整度),综合评分。
+4. **关键数据拼图**(仅交叉验证后的,含来源数量 + 置信度)。
+5. **信号一致性矩阵**。
+6. **各维度分析摘要**(每维 3-5 条最重要发现)。
+7. **真实价值评估**:生意本质 + 护城河评分卡(7 维)+ 估值(5 方法)+ **综合真实价值区间**(保守/合理/乐观 + 当前市场估值 + 安全边际%)。
+8. **投资论点**:看多 5-7 条 vs 看空 5-7 条(每条附来源),哪方更有说服力。
+9. **风险矩阵**(Top 3 + 应对)。
+10. **退出路径评估**。
+11. **投资决策表**(一页纸:核心逻辑 3 句 + 价值区间 + 关键假设与验证节点 + 致命风险与"论文已破"信号 + 结论 + 预期回报/时间)。
+12. **信息盲区地图**(维度 / 已知 / 缺失 / 缺失影响 / 获取建议):缺失是否影响核心结论?影响则明确"在 X 缺失下,结论置信度为 Y"。
+13. **持续跟踪清单**(事项/频率/来源/指标/预警阈值)。
+14. **总结段落**(150-250 字)。
+
+把报告用 `write_file` 写入 `reports/{公司}/{公司}-private-{YYYYMMDD}.md`。可用 `report_audit` 对其中的数字做准出门。
+
+## 数据标注规范(严格执行)
+
+- 每个关键数据标注**来源**(具体到媒体 + 文章)、**时间**(年月)、**置信度**(🟢招股书/官方 / 🟡可信媒体研报 / 🔴推算传闻)。
+- 冲突数据**全部列出**并说明差异和采信判断。
+- **区分事实与推理**:事实正常字体;推理/推算用*斜体*并标注推算方法。
+- 无法获取的信息明确标"数据缺失",不编造。
+
+## 重要原则
+
+1. **6 维度并行**(用 `run_swarm` 同一条消息并行,或顺序)。
+2. **推算要透明**——展示计算逻辑和每步假设,不凭空给数字。
+3. **交叉验证**——关键数据至少 2 来源,冲突都列出。
+4. **信号一致性检验**——汇总阶段必做跨维度一致性检查。
+5. **结论要明确**——不回避投资/观望/回避建议,但说明置信度。
+6. **中英文搜索**——未上市公司信息分布中英文媒体。
+7. **诚实留白**——区分"有据分析"与"推测填充",允许"此维度数据不足,无法给出有意义结论"。
+8. **替代数据不是噪音**——招聘/专利/诉讼/App 可能比新闻更接近真实经营。
+9. **真实价值导向**——目标是判断生意值多少钱,不是输出好看报告。信息不足以估值时,直接说"信息不足,无法给出可靠估值"。
+10. **资料少 ≠ 公司不好**——AI 分析篇幅短 ≠ 投资确定性低;信息极度稀缺时切第一性原理模式。
diff --git a/agent/src/skills/thesis-tracker/SKILL.md b/agent/src/skills/thesis-tracker/SKILL.md
new file mode 100644
index 000000000..4d1efc1ea
--- /dev/null
+++ b/agent/src/skills/thesis-tracker/SKILL.md
@@ -0,0 +1,159 @@
+---
+name: thesis-tracker
+category: strategy
+description: "Buy-side discipline system. For each holding, maintain a written investment thesis — core thesis in 5 sentences, falsifiable assumptions, red lines, valuation anchors — and re-check it each quarter against new earnings/events. Scores thesis health 1-10 from assumption breakage and red-line triggers, and recommends hold / add / trim / exit. Use it right after buying a stock (to write the thesis) and every earnings season (to check it). Bridges the research→buy→monitor gap that most investors skip."
+---
+
+# 投资论文追踪:买入后的纪律系统
+
+对一只持仓执行投资论文追踪。首次对一个公司使用 → 建立论文;后续使用 → 季度检查。
+
+**支持输入**:公司名(自动判断建立/追踪);`公司名 建立论文`(强制重建);`公司名 季度检查`(基于最新财报)。
+
+> "买入只是开始。真正的工作是持有期间的持续跟踪。" —— 李录
+>
+> "当事实改变时,我就改变想法。你呢?" —— 凯恩斯
+
+## 设计理念
+
+大多数投资者的流程是:研究 → 买入 → 祈祷。缺少买入后的系统化跟踪,导致:该卖时舍不得卖("再等等,会涨回来");不该卖时恐慌卖出("跌了 20%,是不是我错了");忘记当初为什么买("我买这个是因为什么来着?")。
+
+巴菲特和李录的做法是:**买入前就写下卖出条件**,然后每个季度检查论文是否完整。
+
+## 第一步:判断操作模式
+
+检查该公司是否已存在论文文件(用 `read_file` 读 `reports/{公司}-thesis.md`):不存在 → **建立论文**(模式 A);存在 → **追踪检查**(模式 B)。
+
+---
+
+## 模式 A:建立投资论文
+
+### A0:数据收集
+
+用 `web_search` 获取当前股价、估值指标(PE/PB/股息率)、最新财报核心数据。如果已有该公司的研究报告,优先 `read_file` 读取。用 `financial_rigor`(`command=verify_valuation`)校验估值数据,`financial_rigor`(`command=verify_market_cap`)核验市值。
+
+### A1:核心论文(必须用 200 字以内写清楚)
+
+投资论文必须回答以下 5 个问题,每个一句话:
+
+```
+我以 ___元 买入 ___公司,因为:
+1. 这门生意的本质是___,我理解它的赚钱方式。
+2. 它的护城河是___,而且在变宽/稳定。
+3. 管理层___,值得信赖的原因是___。
+4. 当前价格相当于内在价值的___折,安全边际来自___。
+5. 即使我错了,下行风险可控,因为___。
+```
+
+**5 句话写不完整 = 论文本身有问题,说明买入决策不够清晰。**
+
+### A2:核心假设清单
+
+把论文拆成可验证的具体假设(通常 3-7 个。太少=思考不深,太多=论文不聚焦):
+
+| # | 核心假设 | 验证方式 | 验证频率 | 当前状态 |
+|---|---------|---------|---------|---------|
+| 1 | 例:收入增速维持 15%+ | 季报收入增速 | 每季度 | 🟢 成立 |
+| 2 | 例:毛利率稳定在 60%+ | 季报毛利率 | 每季度 | 🟢 成立 |
+| 3 | 例:管理层持续回购 | 回购公告/现金流表 | 每季度 | 🟢 成立 |
+| 4 | 例:竞争对手未取得突破 | 行业数据/竞对财报 | 每半年 | 🟢 成立 |
+
+### A3:红线清单(触发任何一条 = 必须重新评估)
+
+| # | 红线条件 | 严重程度 | 触发后动作 |
+|---|---------|---------|-----------|
+| 1 | 管理层诚信出问题(造假、关联交易) | 致命 | 立即清仓 |
+| 2 | 核心业务连续 2 季度收入下滑 | 严重 | 减仓 50%,重新评估 |
+| 3 | 护城河被明确突破(竞对获得同等能力) | 严重 | 深度研究,考虑退出 |
+| 4 | 监管根本性改变商业模式 | 严重 | 重新评估内在价值 |
+| 5 | 管理层大规模非计划减持 | 警告 | 深入调查原因 |
+
+> 段永平:"卖出只有三个理由:1. 发现买错了;2. 公司基本面变了;3. 找到了更好的。"
+
+### A4:估值锚点
+
+| 指标 | 买入时 | 乐观目标 | 中性目标 | 悲观情景 |
+|------|-------|---------|---------|---------|
+| 股价 | | | | |
+| PE(TTM) | | | | |
+| 市值 | | | | |
+| 内在价值估算 | | | | |
+| 安全边际 | | | | |
+
+### A5:保存论文
+
+用 `write_file` 把论文写入 `reports/{公司}-thesis.md`,包含:建立日期、买入价格和仓位、核心论文(5 句)、核心假设清单、红线清单、估值锚点、追踪记录表(初始为空)。
+
+---
+
+## 模式 B:追踪检查
+
+### B1:读取现有论文
+
+用 `read_file` 读 `reports/{公司}-thesis.md`,加载核心论文、假设清单、红线清单、上次检查记录。
+
+### B2:收集最新数据
+
+用 `web_search` / `get_stock_news` / `get_financial_statements` 收集:① 最新财报(如有新季报/年报);② 近期重大事件(管理层变动、监管、竞争);③ 当前股价和估值;④ 内部人交易(大股东增减持)。
+
+### B3:逐条检查核心假设
+
+| # | 核心假设 | 上次状态 | 最新证据 | 当前状态 | 变化 |
+|---|---------|---------|---------|---------|------|
+| 1 | 收入增速 15%+ | 🟢 成立 | Q4 收入增速 12% | 🟡 边际弱化 | ⚠️ |
+| 2 | 毛利率 60%+ | 🟢 成立 | 毛利率 61.2% | 🟢 成立 | — |
+
+状态定义:
+- 🟢 **成立**——最新数据支持
+- 🟡 **边际弱化**——仍在可接受范围,但趋势不利
+- 🔴 **受损**——数据明确不支持
+- ⚫ **破裂**——假设已被推翻
+
+### B4:红线检查
+
+逐条检查红线清单,任何一条触发 → 在报告中醒目标注 + 明确行动建议。
+
+### B5:估值更新
+
+用 `financial_rigor`(`command=verify_valuation`)重新计算 PE/PB/ROE 等,对比买入时与上次检查:
+
+| 指标 | 买入时 | 上次检查 | 当前 | 变化 |
+|------|-------|---------|------|------|
+| 股价 | | | | |
+| PE(TTM) | | | | |
+| 内在价值估算 | | | | |
+| 安全边际 | | | | |
+
+### B6:输出追踪报告
+
+结构:① 论文健康度评分(满分 10);② 核心假设检查表;③ 红线检查表;④ 本期关键变化(≤ 500 字);⑤ 估值更新;⑥ 结论与行动建议;⑦ 下次检查重点。
+
+**健康度公式**:`10 - (⚫破裂假设数 × 3) - (🔴受损假设数 × 2) - (🟡弱化假设数 × 1) - (红线触发数 × 5)`,最低 1 分,最高 10 分。
+
+| 评分 | 含义 | 建议动作 |
+|:----:|------|---------|
+| 9-10 | 所有假设成立,论文比买入时更强 | 考虑加仓 |
+| 7-8 | 核心假设成立,个别边际弱化 | 继续持有 |
+| 5-6 | 1-2 个假设受损,但核心逻辑未变 | 持有但提高警惕 |
+| 3-4 | 多个假设受损,论文基础动摇 | 考虑减仓 |
+| 1-2 | 红线触发或核心假设破裂 | 强烈建议卖出 |
+
+**结论必须明确回答**:① 论文还完整吗?(完整 / 边际弱化 / 受损 / 破裂);② 该怎么做?(加仓 / 持有 / 减仓 / 清仓);③ 下次检查时间(下一个季报后 / 特定事件后)。
+
+### B7:更新论文文件
+
+用 `write_file` 把本次检查记录追加到 `reports/{公司}-thesis.md` 的追踪记录表:
+
+| 检查日期 | 健康度 | 核心变化 | 动作建议 |
+|---------|:------:|---------|---------|
+| 2026-04-09 | 7/10 | 收入增速放缓至 12%,但利润率改善 | 持有 |
+
+---
+
+## 关键原则
+
+- **买入前就写好卖出条件**——冷静时做的决策比恐慌时做的好。
+- **论文要具体到可验证**——"公司很好"不是论文,"ROE > 25% 且趋势稳定"才是。
+- **红线一旦触发就行动**——最怕"再等等看",这是亏大钱的开始。
+- **论文破裂 ≠ 股价下跌**——股价跌 30% 不一定要卖,论文破裂才要卖。
+- **诚实面对错误**——论文建错了就承认,不要为了面子硬撑。
diff --git a/agent/src/swarm/presets/value_investing_committee.yaml b/agent/src/swarm/presets/value_investing_committee.yaml
new file mode 100644
index 000000000..c532ebf2d
--- /dev/null
+++ b/agent/src/swarm/presets/value_investing_committee.yaml
@@ -0,0 +1,189 @@
+name: value_investing_committee
+title: "Value Investing Committee (Buffett / Munger / Duan / Li Lu)"
+description: "Four adversarial master perspectives — Buffett (moat & price), Munger (inversion & risk), Duan Yongping (good business & trustworthy management), Li Lu (10-year certainty & civilizational trend) — run in parallel on one company, then a chair synthesizes consensus and contradictions into a verdict. Inspired by the ai-berkshire master-视角 framework. Use for deep value-investing deliberation on a single named company."
+
+agents:
+ - id: buffett
+ role: Warren Buffett — Moat & Price
+ system_prompt: |
+ 你是沃伦·巴菲特。你只投有"经济特许权"(economic franchise)的好生意,在合理价格买入,长期持有。
+
+ ## 任务
+ 评估 {company}({market})是不是一门好生意,以及当前价格是否提供安全边际。
+
+ {upstream_context}
+
+ ## 你必须回答
+ 1. **能力圈**——这门生意你看得懂吗?能用一句话向一个聪明但不懂行的人讲清楚吗?
+ 2. **护城河**——经济特许权在哪?(品牌/网络效应/转换成本/成本优势/监管牌照)。护城河是在变宽还是变窄?
+ 3. **诚实管理层**——管理层是否诚实、有能力、以股东利益为先?(可 load_skill("management-deep-dive") 深入)
+ 4. **所有者盈余**——真正的内生现金创造能力(净利润 + 折旧摊销 - 维持性资本开支)是多少?
+ 5. **安全边际**——用 financial_rigor 的 three_scenario / verify_valuation 算内在价值,当前价格相对内在价值打几折?买入价是否有足够安全边际?
+
+ ## 原则
+ - 第一条:不要亏钱。第二条:记住第一条。
+ - 别人贪婪我恐惧,别人恐惧我贪婪。
+ - 以合理价格买入好生意,远胜于以便宜价格买入平庸生意。
+ - 不确定就放过(pass),能力圈外的机会不是机会。
+
+ 用 load_skill / get_financial_statements / get_market_data / financial_rigor 取数并精确验证(不接受"待核实"跳过数字)。
+ tools: [bash, read_file, write_file, load_skill, get_market_data, get_financial_statements, web_search, financial_rigor]
+ skills: [fundamental-filter, valuation-model, quality-screen, management-deep-dive]
+ max_iterations: 50
+ timeout_seconds: 1800
+ max_retries: 1
+
+ - id: munger
+ role: Charlie Munger — Inversion & Risk
+ system_prompt: |
+ 你是查理·芒格。你的核心方法是**逆向思考**——"反过来想,总是反过来想"。你不问"能赚多少",你问"怎么会死"。
+
+ ## 任务
+ 对 {company}({market})做逆向分析:列出所有可能让它失败、归零或长期跑输的路径。
+
+ {upstream_context}
+
+ ## 你必须回答
+ 1. **怎么会死?**——列出至少 5 条具体的失败路径(技术替代、监管、竞争、管理层堕落、杠杆、地缘...)。每条给概率(高/中/低)和触发信号。
+ 2. **极端情景下的下行**——最坏情况下股东能收回多少?(清算价值 / 永久性资本损失的概率)
+ 3. **聪明人为什么不买?**——列出市场可能已经看到、而 bullish 叙事回避的风险。
+ 4. **历史教训**——类似定位/阶段的公司,有哪些失败了?为什么?
+ 5. **避免愚蠢**——即便不上车,也要避免哪些"明显的愚蠢"(如在高 PS 亏损期追高、忽略关联交易)?
+
+ ## 原则
+ - 反过来想,总是反过来想。
+ - 如果我知道我会死在哪,我就永远不去那个地方。
+ - 宁要模糊的正确,不要精确的错误。
+ - 承认自己不知道的,比假装知道更重要。
+
+ 用 financial_rigor 验证任何关键数字;用 load_skill("risk-analysis") 系统化风险。
+ tools: [bash, read_file, write_file, load_skill, get_market_data, get_financial_statements, web_search, financial_rigor]
+ skills: [risk-analysis, financial-statement, fundamental-filter]
+ max_iterations: 50
+ timeout_seconds: 1800
+ max_retries: 1
+
+ - id: duan_yongping
+ role: Duan Yongping — Good Business & Trustworthy People
+ system_prompt: |
+ 你是段永平。你的投资哲学是"本分":只投自己看得懂的好生意,买股票就是买人,集中持有,长期不做短线。
+
+ ## 任务
+ 评估 {company}({market})是不是一门"对的生意",以及管理层是否值得把钱交给他 10 年。
+
+ {upstream_context}
+
+ ## 你必须回答
+ 1. **这是不是好生意?**——商业模式简单吗?有没有"不做这个生意用户会很痛苦"的刚需?能不能长期赚高 ROE 而不需要持续融资?
+ 2. **买股票就是买人**——创始人/CEO 正直吗?有能力吗?你愿意把钱交给他管 10 年吗?(load_skill("management-deep-dive") 深入)
+ 3. **企业文化**——是本分文化(以用户/消费者为中心、不占合作伙伴便宜),还是短期榨取文化?
+ 4. **集中度**——如果你只能持有 3 只股票,这家能进你的组合吗?为什么?
+ 5. **价格**——好公司 + 合理价格 > 平庸公司 + 便宜价格。当前估值下,这是"好价格"吗?
+
+ ## 原则
+ - 买股票就是买公司,买公司就是买未来的现金流。
+ - 不懂不做。看不懂就放过。
+ - 集中投资:把鸡蛋放在少数几个篮子里,然后看好它们。
+ - 卖出只有三个理由:发现买错了 / 基本面变了 / 找到更好的。
+
+ 可 load_skill("thesis-tracker") 建立投资论文与红线。
+ tools: [bash, read_file, write_file, load_skill, get_market_data, get_financial_statements, web_search, financial_rigor]
+ skills: [management-deep-dive, fundamental-filter, thesis-tracker, quality-screen]
+ max_iterations: 50
+ timeout_seconds: 1800
+ max_retries: 1
+
+ - id: li_lu
+ role: Li Lu — 10-Year Certainty & Civilizational Trend
+ system_prompt: |
+ 你是李录。你追求"十倍确定性"而非"十倍收益":在文明级别的长期趋势上,找能持续创造价值 10 年以上的公司。
+
+ ## 任务
+ 评估 {company}({market})所处的文明级趋势,以及它 10 年后是否还会存在且更强。
+
+ {upstream_context}
+
+ ## 你必须回答
+ 1. **10 年后还在吗?**——这门生意 10 年后会更强、不变、还是被颠覆?确定性的来源是什么?
+ 2. **文明级趋势**——它处在什么长期趋势上(AI 基础设施、能源转型、消费升级、中国现代化...)?趋势的确定性有多高?(可 load_skill("bottleneck-hunter") 看它是否坐在供应链咽喉上)
+ 3. **复利机器**——它能不能把赚到的钱以高回报率再投资,形成持续复利?
+ 4. **管理层是长期主义者吗?**——在短期压力下是否仍做长期正确的事?
+ 5. **公允价值**——用 financial_rigor 的 three_scenario 做 10 年情景估值;以当前价买入、10 年后 25x PE 退出,年化回报是多少?
+
+ ## 原则
+ - 投资的本质是预测未来 10 年这家公司的现金创造能力。
+ - 在有十倍确定性的方向上,不必追求十倍收益。
+ - 长期来看,股票回报等于企业资本回报率。
+ - 文明趋势 + 优秀组织 + 合理价格 = 长期复利。
+
+ 用 load_skill("bottleneck-hunter") 判断供应链卡位;用 financial_rigor 做精确估值。
+ tools: [bash, read_file, write_file, load_skill, get_market_data, get_financial_statements, web_search, financial_rigor]
+ skills: [bottleneck-hunter, valuation-model, thesis-tracker, global-macro]
+ max_iterations: 50
+ timeout_seconds: 1800
+ max_retries: 1
+
+ - id: chair
+ role: Committee Chair — Consensus & Contradictions
+ system_prompt: |
+ 你是投资委员会主席。四位大师(Buffett / Munger / Duan Yongping / Li Lu)已对 {company}({market})各自给出视角。你的任务不是简单拼凑,而是找出**共识**与**矛盾**。
+
+ {upstream_context}
+
+ ## 你必须输出
+ 1. **共识**(所有大师都同意的,最高置信度)——例如"护城河真实""管理层值得信任""估值透支"等。
+ 2. **矛盾**(谁和谁分歧在哪)——例如 Buffett 觉得便宜、Munger 觉得有归零风险;Duan 看好管理层、Li Lu 担心 10 年确定性。**说明分歧的根本原因**(口径差 / 时间框架差 / 风险偏好差)。
+ 3. **综合裁决**——在共识 + 矛盾的基础上,给出投资 / 观望 / 回避 建议,以及置信度(信息充足度)。
+ 4. **致命风险与"论文已破"信号**——综合 Munger 的失败路径,给出 3 个止损触发条件。
+ 5. **一页纸决策表**——核心逻辑 3 句 / 价值区间 / 关键假设与验证节点 / 结论。
+
+ ## 原则
+ - 对抗张力是设计使然:Buffett 说"够便宜",Munger 问"怎么会死",Duan 说"好生意",Li Lu 问"10 年还在吗"——综合时不要回避矛盾,而要解释矛盾。
+ - 诚实地报告信息缺口:如果四位大师在某些维度信息不足,明确说"在 X 缺失下,结论置信度为 Y"。
+ - 用 report_audit(extract → verdict)对最终报告里的关键数字做准出门,确保无幻觉数字。
+
+ 输出完整 Markdown 报告并用 write_file 保存。
+ tools: [bash, read_file, write_file, report_audit]
+ skills: [report-generate, investment-checklist]
+ max_iterations: 50
+ timeout_seconds: 1800
+ max_retries: 1
+
+tasks:
+ - id: task-buffett
+ agent_id: buffett
+ prompt_template: "评估 {company}({market})是不是一门好生意,当前价格是否提供安全边际。"
+ depends_on: []
+
+ - id: task-munger
+ agent_id: munger
+ prompt_template: "对 {company}({market})做逆向分析——列出所有可能让它失败、归零或长期跑输的路径。"
+ depends_on: []
+
+ - id: task-duan
+ agent_id: duan_yongping
+ prompt_template: "评估 {company}({market})是不是一门好生意,管理层是否值得把钱交给他 10 年。"
+ depends_on: []
+
+ - id: task-li
+ agent_id: li_lu
+ prompt_template: "评估 {company}({market})10 年后是否还会存在且更强,所处的文明级趋势与确定性。"
+ depends_on: []
+
+ - id: task-chair
+ agent_id: chair
+ prompt_template: "综合四位大师的视角,找出共识与矛盾,给出投资委员会最终裁决。"
+ depends_on: [task-buffett, task-munger, task-duan, task-li]
+ input_from:
+ buffett: task-buffett
+ munger: task-munger
+ duan: task-duan
+ li: task-li
+
+variables:
+ - name: company
+ description: "Target company name or ticker (e.g.: 腾讯, NVDA, 茅台)"
+ required: true
+ - name: market
+ description: "Market (e.g.: A-shares, Hong Kong, US)"
+ required: true
diff --git a/agent/src/tools/financial_rigor_tool.py b/agent/src/tools/financial_rigor_tool.py
new file mode 100644
index 000000000..95ed6b7d2
--- /dev/null
+++ b/agent/src/tools/financial_rigor_tool.py
@@ -0,0 +1,574 @@
+"""Agent tool: financial-rigor checks with exact decimal arithmetic.
+
+A thin ``BaseTool`` wrapper around six pure-stdlib verification routines that
+guard investment research against numerical error and hallucinated metrics.
+Auto-discovered and registered via ``BaseTool.__subclasses__()``.
+
+All arithmetic uses ``decimal.Decimal`` under a shared 28-digit context, so
+results are free of IEEE-754 drift and are reproducible and auditable. The
+tool takes raw numbers only — it does not fetch data. Pair it with the
+market-data / financial-statement tools: fetch there, verify here.
+
+Sub-commands (selected via ``command``):
+
+- ``verify_market_cap`` — price × shares vs a reported cap; verdict at 1%/5%.
+- ``verify_valuation`` — PE / PB / ROE / P/FCF / FCF yield / dividend yield /
+ PS derived from raw per-share inputs.
+- ``cross_validate`` — one field across several sources, flag deviations over
+ a tolerance (default 2%), expose the median consensus.
+- ``benford`` — Benford's-law first-digit check on a list of values; needs
+ ≥50 samples; reports MAD / chi-square / conformity.
+- ``calc`` — safe exact evaluation of an arithmetic expression string
+ (AST-whitelisted: numbers and +, -, *, / only).
+- ``three_scenario`` — bull / base / bear target prices from EPS-growth and
+ target-PE assumptions.
+
+Read-only: returns JSON verdicts, writes nothing.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import math
+from decimal import Context, Decimal, ROUND_HALF_EVEN
+from typing import Any
+
+from src.agent.tools import BaseTool
+
+_CTX = Context(prec=28, rounding=ROUND_HALF_EVEN)
+
+# Benford's-law expected first-digit frequencies.
+_BENFORD = {d: math.log10(1 + 1 / d) for d in range(1, 10)}
+
+# AST operator handlers for the ``calc`` evaluator. Only numbers and
+# +, -, *, / (with optional unary sign) are honoured; anything else raises.
+_AST_BINOPS = {
+ ast.Add: _CTX.add,
+ ast.Sub: _CTX.subtract,
+ ast.Mult: _CTX.multiply,
+ ast.Div: _CTX.divide,
+}
+_AST_UNARYOPS = {
+ ast.UAdd: lambda d: d,
+ ast.USub: lambda d: -d,
+}
+
+
+def _err(msg: str) -> str:
+ """Build the standard error JSON envelope."""
+ return json.dumps({"status": "error", "error": msg}, ensure_ascii=False)
+
+
+def _exact(value: Any) -> Decimal:
+ """Convert any numeric to an exact Decimal, avoiding float binary traps."""
+ if isinstance(value, Decimal):
+ return value
+ return Decimal(str(value))
+
+
+def _fmt(value: float) -> str:
+ """Render a large number with K / M / B / T suffixes for readability."""
+ abs_v = abs(value)
+ if abs_v >= 1e12:
+ return f"{value / 1e12:.2f}T"
+ if abs_v >= 1e9:
+ return f"{value / 1e9:.2f}B"
+ if abs_v >= 1e6:
+ return f"{value / 1e6:.2f}M"
+ if abs_v >= 1e3:
+ return f"{value / 1e3:.2f}K"
+ return f"{value:,.2f}"
+
+
+def _eval_arith_node(node: ast.AST) -> Decimal:
+ """Recursively evaluate an arithmetic AST node in the Decimal domain.
+
+ Args:
+ node: An AST node from a parsed expression.
+
+ Returns:
+ The exact Decimal value of the node.
+
+ Raises:
+ ValueError: If the node is not a supported numeric/arithmetic form.
+ """
+ if isinstance(node, ast.Constant):
+ # bool is a subclass of int — reject it explicitly.
+ if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
+ raise ValueError("only numeric constants are allowed")
+ return _exact(node.value)
+ if isinstance(node, ast.BinOp):
+ op_fn = _AST_BINOPS.get(type(node.op))
+ if op_fn is None:
+ raise ValueError(f"unsupported operator: {type(node.op).__name__}")
+ return op_fn(_eval_arith_node(node.left), _eval_arith_node(node.right))
+ if isinstance(node, ast.UnaryOp):
+ op_fn = _AST_UNARYOPS.get(type(node.op))
+ if op_fn is None:
+ raise ValueError(f"unsupported unary operator: {type(node.op).__name__}")
+ return op_fn(_eval_arith_node(node.operand))
+ raise ValueError(f"disallowed element in expression: {type(node).__name__}")
+
+
+def _safe_arith(expr: str) -> Decimal:
+ """Evaluate a numeric arithmetic expression in the exact-Decimal domain.
+
+ The expression is parsed and evaluated recursively with Decimal arithmetic,
+ so ``0.1 + 0.2`` is exactly ``0.3`` — no IEEE-754 drift, and no ``eval``.
+ Only numbers and the operators ``+ - * /`` (with optional unary sign) are
+ permitted; any other AST node raises ``ValueError``.
+
+ Args:
+ expr: Arithmetic expression string, e.g. ``"510 * 9.11e9"``.
+
+ Returns:
+ The exact Decimal result.
+
+ Raises:
+ ValueError: If the expression is malformed or contains a disallowed
+ element.
+ """
+ try:
+ tree = ast.parse(expr, mode="eval")
+ except SyntaxError as exc:
+ raise ValueError(f"malformed expression: {exc}") from exc
+ return _eval_arith_node(tree.body)
+
+
+# ---------------------------------------------------------------------------
+# Core verification routines (pure, return structured dicts, no I/O)
+# ---------------------------------------------------------------------------
+
+def verify_market_cap(
+ price: Any, shares: Any, reported_cap: Any, currency: str = "",
+) -> dict[str, Any]:
+ """Verify ``market cap = price × shares`` against a reported value.
+
+ Args:
+ price: Current share price.
+ shares: Total share count.
+ reported_cap: The market-cap figure being checked.
+ currency: Optional currency label for display only.
+
+ Returns:
+ Verdict dict. ``verdict`` is ``pass`` (≤1%), ``warn`` (1–5%) or
+ ``fail`` (>5%).
+ """
+ p, s, r = _exact(price), _exact(shares), _exact(reported_cap)
+ calculated = _CTX.multiply(p, s)
+ deviation = abs(float(calculated - r) / float(r)) * 100 if r != 0 else 0.0
+ if deviation > 5:
+ verdict = "fail"
+ elif deviation > 1:
+ verdict = "warn"
+ else:
+ verdict = "pass"
+ return {
+ "price": float(p),
+ "shares": float(s),
+ "currency": currency,
+ "calculated_market_cap": float(calculated),
+ "calculated_market_cap_display": _fmt(float(calculated)),
+ "reported_market_cap": float(r),
+ "deviation_pct": round(deviation, 4),
+ "verdict": verdict,
+ }
+
+
+def verify_valuation(
+ price: Any,
+ eps: Any | None = None,
+ bvps: Any | None = None,
+ fcf_per_share: Any | None = None,
+ dividend: Any | None = None,
+ revenue_per_share: Any | None = None,
+) -> dict[str, Any]:
+ """Derive valuation ratios from raw per-share inputs (exact decimal).
+
+ Each optional input, when supplied and non-zero, contributes its metric(s).
+ ROE additionally requires both ``eps`` and ``bvps``.
+
+ Args:
+ price: Current share price.
+ eps: Earnings per share (TTM).
+ bvps: Book value per share.
+ fcf_per_share: Free cash flow per share.
+ dividend: Dividend per share.
+ revenue_per_share: Revenue per share.
+
+ Returns:
+ Dict with ``price`` and a ``metrics`` map (PE, PB, ROE_pct, P_FCF,
+ FCF_yield_pct, dividend_yield_pct, PS — whichever apply).
+ """
+ p = _exact(price)
+ metrics: dict[str, float] = {}
+ if eps is not None:
+ e = _exact(eps)
+ if e != 0:
+ metrics["PE"] = float(_CTX.divide(p, e))
+ metrics["earnings_yield_pct"] = float(_CTX.divide(e, p) * 100)
+ if bvps is not None:
+ b = _exact(bvps)
+ if b != 0:
+ metrics["PB"] = float(_CTX.divide(p, b))
+ if eps is not None and _exact(eps) != 0:
+ metrics["ROE_pct"] = float(_CTX.divide(_exact(eps), b) * 100)
+ if fcf_per_share is not None:
+ f = _exact(fcf_per_share)
+ if f != 0:
+ metrics["P_FCF"] = float(_CTX.divide(p, f))
+ metrics["FCF_yield_pct"] = float(_CTX.divide(f, p) * 100)
+ if dividend is not None:
+ d = _exact(dividend)
+ if p != 0:
+ metrics["dividend_yield_pct"] = float(_CTX.divide(d, p) * 100)
+ if revenue_per_share is not None:
+ rps = _exact(revenue_per_share)
+ if rps != 0:
+ metrics["PS"] = float(_CTX.divide(p, rps))
+ return {"price": float(p), "metrics": metrics}
+
+
+def cross_validate(
+ field_name: str,
+ source_values: dict[str, Any],
+ unit: str = "",
+ tolerance_pct: float = 2.0,
+) -> dict[str, Any]:
+ """Compare one field across sources, flag deviations over a tolerance.
+
+ The median of the supplied values is used as the reference, and each
+ source's percent deviation from it is reported.
+
+ Args:
+ field_name: Field being compared (e.g. ``"revenue"``).
+ source_values: Mapping of source name to numeric value.
+ unit: Optional unit label for display.
+ tolerance_pct: Percent deviation above which a source is inconsistent.
+
+ Returns:
+ Dict with ``median_reference``/``consensus``, ``all_consistent`` and a
+ per-source breakdown.
+ """
+ values = {k: _exact(v) for k, v in source_values.items()}
+ nums = sorted(float(v) for v in values.values())
+ n = len(nums)
+ if n == 0:
+ median = 0.0
+ elif n % 2 == 1:
+ median = nums[n // 2]
+ else:
+ median = (nums[n // 2 - 1] + nums[n // 2]) / 2
+ per_source: list[dict[str, Any]] = []
+ all_consistent = True
+ for src, val in values.items():
+ dev = abs(float(val) - median) / median * 100 if median != 0 else 0.0
+ consistent = dev <= tolerance_pct
+ all_consistent = all_consistent and consistent
+ per_source.append({
+ "source": src,
+ "value": float(val),
+ "deviation_pct": round(dev, 4),
+ "consistent": consistent,
+ })
+ return {
+ "field": field_name,
+ "unit": unit,
+ "tolerance_pct": tolerance_pct,
+ "median_reference": median,
+ "consensus": median,
+ "all_consistent": all_consistent,
+ "per_source": per_source,
+ }
+
+
+def benford_check(values: list[Any]) -> dict[str, Any]:
+ """First-digit Benford's-law check on a list of financial values.
+
+ Args:
+ values: Numeric values to inspect.
+
+ Returns:
+ Dict with ``sample_size``, ``reliable`` (False when ``n < 50``), and —
+ when reliable — ``mad`` (Nigrini's MAD), ``chi2``, ``conformity`` and a
+ per-digit ``distribution``.
+ """
+ digits: list[int] = []
+ for raw in values:
+ v = abs(float(raw))
+ if v > 0:
+ sig = 10 ** (math.log10(v) - math.floor(math.log10(v)))
+ d = int(sig)
+ if 1 <= d <= 9:
+ digits.append(d)
+ n = len(digits)
+ if n < 50:
+ return {
+ "sample_size": n,
+ "reliable": False,
+ "note": "Benford analysis needs >= 50 samples to be meaningful",
+ }
+ counts = {d: 0 for d in range(1, 10)}
+ for d in digits:
+ counts[d] += 1
+ observed = {d: counts[d] / n for d in range(1, 10)}
+ mad = sum(abs(observed[d] - _BENFORD[d]) for d in range(1, 10)) / 9
+ chi2 = sum(
+ (counts[d] - _BENFORD[d] * n) ** 2 / (_BENFORD[d] * n) for d in range(1, 10)
+ )
+ if mad < 0.006:
+ conformity = "close"
+ elif mad < 0.012:
+ conformity = "acceptable"
+ elif mad < 0.015:
+ conformity = "marginal"
+ else:
+ conformity = "nonconforming"
+ distribution = [
+ {
+ "digit": d,
+ "observed": round(observed[d], 4),
+ "expected": round(_BENFORD[d], 4),
+ "deviation": round(observed[d] - _BENFORD[d], 4),
+ }
+ for d in range(1, 10)
+ ]
+ return {
+ "sample_size": n,
+ "reliable": True,
+ "mad": round(mad, 6),
+ "chi2": round(chi2, 4),
+ "conformity": conformity,
+ "is_conforming": mad < 0.015,
+ "distribution": distribution,
+ }
+
+
+def exact_calc(expr: str) -> dict[str, Any]:
+ """Evaluate an arithmetic expression with exact decimal arithmetic.
+
+ Args:
+ expr: Arithmetic expression string (numbers and ``+ - * /`` only).
+
+ Returns:
+ Dict with ``result`` (float) and ``result_exact`` (Decimal string).
+
+ Raises:
+ ValueError: If the expression is malformed or contains a disallowed
+ element (surfaced by the caller as a tool error).
+ """
+ d = _safe_arith(expr)
+ return {"expr": expr, "result": float(d), "result_exact": str(d)}
+
+
+def three_scenario_valuation(
+ current_price: Any,
+ current_eps: Any,
+ shares_billion: Any,
+ growth_optimistic: Any,
+ growth_neutral: Any,
+ growth_pessimistic: Any,
+ pe_optimistic: Any,
+ pe_neutral: Any,
+ pe_pessimistic: Any,
+ years: int = 3,
+ currency: str = "",
+) -> dict[str, Any]:
+ """Bull / base / bear target prices from EPS-growth and target-PE assumptions.
+
+ Future EPS = ``current_eps × (1 + growth) ** years``; target price = future
+ EPS × target PE. All math is exact decimal.
+
+ Args:
+ current_price: Current share price.
+ current_eps: Current EPS.
+ shares_billion: Share count in billions.
+ growth_optimistic / growth_neutral / growth_pessimistic: Annual EPS
+ growth rate per scenario (e.g. ``0.15`` for 15%).
+ pe_optimistic / pe_neutral / pe_pessimistic: Target PE per scenario.
+ years: Forecast horizon in years.
+ currency: Optional currency label.
+
+ Returns:
+ Dict with the assumptions and a ``scenarios`` list, each carrying its
+ ``future_eps``, ``target_price`` and ``upside_pct``.
+ """
+ p, eps, shares = _exact(current_price), _exact(current_eps), _exact(shares_billion)
+ spec = [
+ ("bull", growth_optimistic, pe_optimistic),
+ ("base", growth_neutral, pe_neutral),
+ ("bear", growth_pessimistic, pe_pessimistic),
+ ]
+ scenarios: list[dict[str, Any]] = []
+ for name, growth, pe in spec:
+ g, target_pe = _exact(growth), _exact(pe)
+ future_eps = eps
+ for _ in range(int(years)):
+ future_eps = _CTX.multiply(future_eps, _CTX.add(Decimal("1"), g))
+ target_price = _CTX.multiply(future_eps, target_pe)
+ upside = float(target_price - p) / float(p) * 100 if p != 0 else 0.0
+ scenarios.append({
+ "scenario": name,
+ "annual_growth": float(g),
+ "target_pe": float(target_pe),
+ "future_eps": float(future_eps),
+ "target_price": float(target_price),
+ "upside_pct": round(upside, 2),
+ })
+ return {
+ "current_price": float(p),
+ "current_eps": float(eps),
+ "shares_billion": float(shares),
+ "years": int(years),
+ "currency": currency,
+ "scenarios": scenarios,
+ }
+
+
+class FinancialRigorTool(BaseTool):
+ """Exact-decimal financial verification across six sub-commands."""
+
+ name = "financial_rigor"
+ description = (
+ "Verify financial-data accuracy with exact decimal arithmetic (no float "
+ "drift). Takes raw numbers only — does not fetch data. Pair it with the "
+ "market-data / financial-statement tools: fetch there, verify here. Six "
+ "sub-commands selected via `command`: 'verify_market_cap' (price x shares "
+ "vs reported cap, verdict at 1%/5%), 'verify_valuation' (PE/PB/ROE/P-FCF/"
+ "yields/PS from raw per-share inputs), 'cross_validate' (one field across "
+ "sources, flag deviations > tolerance_pct, expose median consensus), "
+ "'benford' (Benford first-digit fabrication check, needs >=50 samples), "
+ "'calc' (safe exact arithmetic on an expression string), 'three_scenario' "
+ "(bull/base/bear target prices from EPS-growth and target-PE assumptions)."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "enum": [
+ "verify_market_cap", "verify_valuation", "cross_validate",
+ "benford", "calc", "three_scenario",
+ ],
+ "description": "Which verification to run.",
+ },
+ "price": {"type": "number", "description": "Share price."},
+ "shares": {
+ "type": "number",
+ "description": "verify_market_cap: total share count; "
+ "three_scenario: share count in billions.",
+ },
+ "reported_cap": {"type": "number", "description": "Reported market cap."},
+ "currency": {"type": "string", "description": "Currency label (display only)."},
+ "eps": {"type": "number", "description": "Earnings per share."},
+ "bvps": {"type": "number", "description": "Book value per share."},
+ "fcf_per_share": {"type": "number", "description": "Free cash flow per share."},
+ "dividend": {"type": "number", "description": "Dividend per share."},
+ "revenue_per_share": {"type": "number", "description": "Revenue per share."},
+ "field": {"type": "string", "description": "cross_validate: field name."},
+ "source_values": {
+ "type": "object",
+ "description": "cross_validate: mapping of source name to value.",
+ },
+ "unit": {"type": "string", "description": "cross_validate: unit label."},
+ "tolerance_pct": {
+ "type": "number", "default": 2.0,
+ "description": "cross_validate: max acceptable percent deviation.",
+ },
+ "values": {
+ "type": "array", "items": {"type": "number"},
+ "description": "benford: list of financial values to inspect.",
+ },
+ "expr": {
+ "type": "string",
+ "description": "calc: arithmetic expression (numbers and + - * /).",
+ },
+ "growth": {
+ "type": "array", "items": {"type": "number"},
+ "minItems": 3, "maxItems": 3,
+ "description": "three_scenario: annual EPS growth [bull, base, bear].",
+ },
+ "pe": {
+ "type": "array", "items": {"type": "number"},
+ "minItems": 3, "maxItems": 3,
+ "description": "three_scenario: target PE [bull, base, bear].",
+ },
+ "years": {"type": "integer", "default": 3, "description": "three_scenario horizon."},
+ },
+ "required": ["command"],
+ }
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Dispatch to the requested sub-command and return a JSON envelope.
+
+ Args:
+ **kwargs: ``command`` plus the inputs for that sub-command.
+
+ Returns:
+ JSON string — ``status="ok"`` with the verdict on success,
+ ``status="error"`` with a message otherwise.
+ """
+ command = str(kwargs.get("command") or "").strip()
+ try:
+ if command == "verify_market_cap":
+ for key in ("price", "shares", "reported_cap"):
+ if kwargs.get(key) is None:
+ return _err(f"{key} is required for verify_market_cap")
+ result: dict[str, Any] = verify_market_cap(
+ kwargs["price"], kwargs["shares"], kwargs["reported_cap"],
+ currency=str(kwargs.get("currency") or ""),
+ )
+ elif command == "verify_valuation":
+ if kwargs.get("price") is None:
+ return _err("price is required for verify_valuation")
+ result = verify_valuation(
+ kwargs["price"], kwargs.get("eps"), kwargs.get("bvps"),
+ kwargs.get("fcf_per_share"), kwargs.get("dividend"),
+ kwargs.get("revenue_per_share"),
+ )
+ elif command == "cross_validate":
+ if not kwargs.get("field") or not kwargs.get("source_values"):
+ return _err("field and source_values are required for cross_validate")
+ result = cross_validate(
+ str(kwargs["field"]), kwargs["source_values"],
+ unit=str(kwargs.get("unit") or ""),
+ tolerance_pct=float(kwargs.get("tolerance_pct") or 2.0),
+ )
+ elif command == "benford":
+ vals = kwargs.get("values")
+ if not isinstance(vals, list) or not vals:
+ return _err("values (non-empty list) is required for benford")
+ result = benford_check(vals)
+ elif command == "calc":
+ if not kwargs.get("expr"):
+ return _err("expr is required for calc")
+ result = exact_calc(str(kwargs["expr"]))
+ elif command == "three_scenario":
+ for key in ("price", "eps", "shares", "growth", "pe"):
+ if kwargs.get(key) is None:
+ return _err(f"{key} is required for three_scenario")
+ growth = kwargs["growth"]
+ pe = kwargs["pe"]
+ if not isinstance(growth, list) or len(growth) != 3:
+ return _err("growth must be a list of 3 numbers [bull, base, bear]")
+ if not isinstance(pe, list) or len(pe) != 3:
+ return _err("pe must be a list of 3 numbers [bull, base, bear]")
+ result = three_scenario_valuation(
+ kwargs["price"], kwargs["eps"], kwargs["shares"],
+ growth[0], growth[1], growth[2],
+ pe[0], pe[1], pe[2],
+ years=int(kwargs.get("years") or 3),
+ currency=str(kwargs.get("currency") or ""),
+ )
+ else:
+ return _err(f"unknown command: {command}")
+ except Exception as exc: # noqa: BLE001 - surface a clean tool error
+ return json.dumps(
+ {"status": "error", "command": command, "error": str(exc)},
+ ensure_ascii=False,
+ )
+ return json.dumps(
+ {"status": "ok", "command": command, **result}, ensure_ascii=False,
+ )
diff --git a/agent/src/tools/report_audit_tool.py b/agent/src/tools/report_audit_tool.py
new file mode 100644
index 000000000..04e48e0a9
--- /dev/null
+++ b/agent/src/tools/report_audit_tool.py
@@ -0,0 +1,422 @@
+"""Agent tool: research-report data audit (extract → verify → verdict).
+
+A ``BaseTool`` wrapper around the report-audit routines that guard published
+research against hallucinated numbers. Auto-discovered and registered via
+``BaseTool.__subclasses__()``.
+
+Two-phase quality gate:
+
+1. ``extract`` — parse a markdown report, collect its numeric data points
+ (tables, ``label: value`` lines, ``亿 / 万亿 / x / 倍 / %`` units), and
+ draw a random sample (default 15%, clamped to [3, 30]).
+2. ``verdict`` — compare each sampled point's reported value against one or two
+ authoritative fetched values at a 1% tolerance; a single failed point fails
+ the whole report, mixed results warn.
+
+The tool takes text/results only — it does not fetch data itself. Pair it with
+market-data / financial-statement tools: read the report, extract here, fetch
+there, then verdict here. Read-only: returns JSON, writes nothing.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+from random import Random
+from typing import Any
+
+from src.agent.tools import BaseTool
+
+# ---------------------------------------------------------------------------
+# Markdown data-point extraction (handles Chinese financial reports)
+# ---------------------------------------------------------------------------
+
+_KV_LABEL_RE = re.compile(
+ r"(?P<label>[一-龥A-Za-z][^|\n::*]{1,30})[::]\s*[~约]?\$?"
+ r"(?P<num>[\d,,.]+)\s*"
+ r"(?P<unit>亿[元美港]?元?|万亿|[xX倍]|%|[BMT])?"
+)
+
+_NUMUNIT_RE = re.compile(r"[~约]?\$?([\d,,.]+)\s*(亿[元美港]?元?|万亿|[xX倍]|%|[BMT])?")
+_TABLE_SEP_RE = re.compile(r"^\|[\-\s|:]+\|$")
+
+_SKIP_LABELS = {
+ "来源", "sources", "source", "说明", "注意", "备注", "数据来源",
+ "n/a", "—", "-", "/", "合计", "total", "单位", "趋势",
+}
+
+_QUARTER_RE = re.compile(r"(20\d{2}|Q[1-4]|\d{4}\s*Q[1-4])")
+
+
+def _clean_num(s: str) -> float | None:
+ """Normalise a numeric string with commas (ASCII or wide) to float."""
+ s = s.replace(",", "").replace(",", "").strip()
+ try:
+ return float(s)
+ except ValueError:
+ return None
+
+
+def _is_valid_label(label: str) -> bool:
+ """True if a label looks like a meaningful financial field name."""
+ label = label.strip()
+ if len(label) < 2:
+ return False
+ if re.fullmatch(r"[\d\s年季度Q]+", label):
+ return False
+ if re.match(r"^[+\-*#|~$>_`]", label):
+ return False
+ if "**" in label or "`" in label or "__" in label:
+ return False
+ if re.fullmatch(r"[+-]?\d+(\.\d+)?%", label):
+ return False
+ if label.lower() in _SKIP_LABELS:
+ return False
+ return True
+
+
+def _parse_md_tables(lines: list[str]) -> list[tuple[str, str, float, str, int, str]]:
+ """Parse markdown tables into (row_label, col_header, value, unit, lineno, raw)."""
+ results: list[tuple[str, str, float, str, int, str]] = []
+ i = 0
+ while i < len(lines):
+ line = lines[i].strip()
+ if "|" in line and not _TABLE_SEP_RE.match(line):
+ headers_raw = [h.strip().strip("*_").strip() for h in line.split("|")]
+ headers_raw = [h for h in headers_raw if h]
+ if i + 1 < len(lines) and _TABLE_SEP_RE.match(lines[i + 1].strip()):
+ i += 2 # skip the separator row
+ while i < len(lines):
+ dline = lines[i].strip()
+ if not dline or not dline.startswith("|"):
+ break
+ cells = [c.strip().strip("*_~").strip() for c in dline.split("|")]
+ cells = [c for c in cells if c != ""]
+ if len(cells) < 2:
+ i += 1
+ continue
+ row_label = cells[0]
+ for col_idx, cell in enumerate(cells[1:], start=1):
+ col_header = (
+ headers_raw[col_idx]
+ if col_idx < len(headers_raw)
+ else f"col{col_idx}"
+ )
+ m = _NUMUNIT_RE.search(cell)
+ if m:
+ val = _clean_num(m.group(1))
+ unit = (m.group(2) or "").strip()
+ if val and val != 0 and val < 1e15:
+ results.append((row_label, col_header, val, unit, i + 1, dline))
+ i += 1
+ continue
+ i += 1
+ return results
+
+
+def extract_data_points(md_text: str) -> list[dict[str, Any]]:
+ """Extract recognizable financial data points from a markdown report.
+
+ Covers multi-column tables and ``label: value unit`` lines. De-duplicates
+ by (label, value, unit).
+
+ Args:
+ md_text: Full markdown text of the report.
+
+ Returns:
+ List of point dicts: ``{id, label, reported_value, unit, raw_text,
+ line_number}``.
+ """
+ points: list[dict[str, Any]] = []
+ seen: set[str] = set()
+
+ def _add(label: str, val: float | None, unit: str, lineno: int, raw: str) -> None:
+ label = re.sub(r"[*_`]+", "", label).strip()
+ if not _is_valid_label(label):
+ return
+ if val is None or val == 0 or val > 1e15:
+ return
+ if _QUARTER_RE.fullmatch(label.strip()):
+ return
+ key = f"{label}|{round(val, 4)}|{unit}"
+ if key in seen:
+ return
+ seen.add(key)
+ points.append({
+ "id": len(points) + 1,
+ "label": label,
+ "reported_value": val,
+ "unit": unit,
+ "raw_text": raw[:120],
+ "line_number": lineno,
+ })
+
+ lines = md_text.split("\n")
+ in_code = False
+
+ # 1. Multi-column tables.
+ _YOY_HEADERS = {"YOY", "YOY增速", "增速", "同比", "变化", "趋势", "说明", "备注"}
+ for row_label, col_header, val, unit, lineno, raw in _parse_md_tables(lines):
+ if not _is_valid_label(row_label):
+ continue
+ if col_header.upper() in _YOY_HEADERS:
+ continue
+ label = f"{row_label} · {col_header}" if (col_header and col_header != row_label) else row_label
+ _add(label, val, unit, lineno, raw)
+
+ # 2. ``label: value unit`` lines.
+ for lineno, line in enumerate(lines, start=1):
+ stripped = line.strip()
+ if stripped.startswith("```"):
+ in_code = not in_code
+ continue
+ if in_code or stripped.startswith("> ") or re.match(r"^#{1,6}\s", stripped):
+ continue
+ if "|" in stripped:
+ continue # handled as a table above
+ for m in _KV_LABEL_RE.finditer(stripped):
+ _add(
+ m.group("label"),
+ _clean_num(m.group("num")),
+ (m.group("unit") or "").strip(),
+ lineno,
+ stripped,
+ )
+
+ return points
+
+
+def sample_points(
+ points: list[dict[str, Any]], ratio: float = 0.15, seed: int | None = None,
+) -> list[dict[str, Any]]:
+ """Draw a random sample, clamped to [3, 30], ordered by line number.
+
+ Args:
+ points: Data points returned by :func:`extract_data_points`.
+ ratio: Sampling fraction.
+ seed: Optional seed for reproducibility.
+
+ Returns:
+ Sampled points sorted by ``line_number``.
+ """
+ n = max(3, min(30, math.ceil(len(points) * ratio)))
+ n = min(n, len(points))
+ if n == 0:
+ return []
+ rng = Random(seed)
+ sampled = rng.sample(points, n)
+ return sorted(sampled, key=lambda p: p["line_number"])
+
+
+# ---------------------------------------------------------------------------
+# Verdict
+# ---------------------------------------------------------------------------
+
+_TOLERANCE = 0.01 # 1% absolute relative tolerance
+
+
+def _pct_diff(reported: float, fetched: float) -> float:
+ """Absolute relative percent difference (inf when reported is 0 and fetched isn't)."""
+ if reported == 0:
+ return 0.0 if fetched == 0 else float("inf")
+ return abs(reported - fetched) / abs(reported)
+
+
+def render_verdict(results: list[dict[str, Any]], report_name: str = "") -> dict[str, Any]:
+ """Render a PASS/FAIL verdict from per-point verification results.
+
+ Each result with a ``fetched_value`` is judged against the reported value
+ at :data:`_TOLERANCE`. A second source (``fetched_value2``) may be supplied;
+ both sources must pass for a point to pass, both fail to fail, otherwise the
+ point warns (treated as a caliber mismatch, not a failure).
+
+ Args:
+ results: List of verification objects — ``{id, label, reported_value,
+ unit, fetched_value, fetched_source, (optional) fetched_value2,
+ fetched_source2, ...}``.
+ report_name: Optional report name for display.
+
+ Returns:
+ Verdict dict: ``verdict`` is ``PASS`` (zero failures) or ``FAIL``.
+ """
+ fail_items: list[dict[str, Any]] = []
+ warn_items: list[dict[str, Any]] = []
+ pass_count = 0
+ total = 0
+
+ for item in results:
+ fetched = item.get("fetched_value")
+ if fetched is None:
+ continue # not verified — skip, do not count
+ total += 1
+ reported = float(item.get("reported_value", 0))
+ label = item.get("label", "?")
+ unit = item.get("unit", "")
+ source = item.get("fetched_source", "?")
+ fetched = float(fetched)
+ diff1 = _pct_diff(reported, fetched)
+
+ fetched2 = item.get("fetched_value2")
+ source2 = item.get("fetched_source2", "")
+ pass1 = diff1 <= _TOLERANCE
+
+ if fetched2 is None:
+ # Single source: pass or fail outright.
+ if pass1:
+ pass_count += 1
+ else:
+ fail_items.append({
+ "id": item.get("id"), "label": label,
+ "reported": reported, "unit": unit,
+ "fetched": fetched, "source": source,
+ "fetched2": None, "source2": source2,
+ "diff1_pct": round(diff1 * 100, 2), "diff2_pct": None,
+ "raw_text": item.get("raw_text", ""),
+ "line_number": item.get("line_number", 0),
+ })
+ else:
+ # Two sources: PASS only if both agree within tolerance; FAIL if
+ # both miss; otherwise WARN (a caliber / GAAP mismatch, not a fail).
+ f2 = float(fetched2)
+ diff2 = _pct_diff(reported, f2)
+ pass2 = diff2 <= _TOLERANCE
+ if pass1 and pass2:
+ pass_count += 1
+ elif not pass1 and not pass2:
+ fail_items.append({
+ "id": item.get("id"), "label": label,
+ "reported": reported, "unit": unit,
+ "fetched": fetched, "source": source,
+ "fetched2": f2, "source2": source2,
+ "diff1_pct": round(diff1 * 100, 2),
+ "diff2_pct": round(diff2 * 100, 2),
+ "raw_text": item.get("raw_text", ""),
+ "line_number": item.get("line_number", 0),
+ })
+ else:
+ warn_items.append({
+ "id": item.get("id"), "label": label,
+ "reported": reported, "unit": unit,
+ "diff1_pct": round(diff1 * 100, 2),
+ "diff2_pct": round(diff2 * 100, 2),
+ })
+
+ fail_count = len(fail_items)
+ verdict = "PASS" if fail_count == 0 else "FAIL"
+ return {
+ "verdict": verdict,
+ "report_name": report_name,
+ "total": total,
+ "pass_count": pass_count,
+ "warn_count": len(warn_items),
+ "fail_count": fail_count,
+ "fail_items": fail_items,
+ "warn_items": warn_items,
+ }
+
+
+class ReportAuditTool(BaseTool):
+ """Research-report data audit gate (extract sample → verdict)."""
+
+ name = "report_audit"
+ description = (
+ "Audit a research report's numeric data points for accuracy before "
+ "publishing. Two sub-commands via `command`: 'extract' parses a "
+ "markdown report and returns a random sample (~15%, clamped 3-30) of "
+ "its financial data points to verify; 'verdict' compares each sampled "
+ "point's reported value against one or two authoritative fetched values "
+ "at 1% tolerance and returns a PASS/FAIL gate (one failure fails the "
+ "report). Workflow: read the report, extract here, verify each sample "
+ "point against market-data/financial-statement tools, then verdict here."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "command": {
+ "type": "string",
+ "enum": ["extract", "verdict"],
+ "description": "Which audit phase to run.",
+ },
+ "report_text": {
+ "type": "string",
+ "description": "extract: full markdown text of the report to audit.",
+ },
+ "ratio": {
+ "type": "number", "default": 0.15,
+ "description": "extract: fraction of data points to sample.",
+ },
+ "seed": {
+ "type": "integer",
+ "description": "extract: random seed for reproducible sampling.",
+ },
+ "results": {
+ "type": "array", "items": {"type": "object"},
+ "description": "verdict: list of {id, label, reported_value, unit, "
+ "fetched_value, fetched_source, (optional) "
+ "fetched_value2, fetched_source2}.",
+ },
+ "report_name": {
+ "type": "string",
+ "description": "verdict: report name for display.",
+ },
+ },
+ "required": ["command"],
+ }
+ is_readonly = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Dispatch to ``extract`` or ``verdict`` and return a JSON envelope.
+
+ Args:
+ **kwargs: ``command`` plus the inputs for that phase.
+
+ Returns:
+ JSON string — ``status="ok"`` with the result on success,
+ ``status="error"`` with a message otherwise.
+ """
+ command = str(kwargs.get("command") or "").strip()
+ try:
+ if command == "extract":
+ report_text = kwargs.get("report_text")
+ if not isinstance(report_text, str) or not report_text.strip():
+ return _err("report_text (non-empty markdown) is required for extract")
+ ratio = float(kwargs.get("ratio") or 0.15)
+ seed = kwargs.get("seed")
+ seed = int(seed) if seed is not None else None
+ points = extract_data_points(report_text)
+ sampled = sample_points(points, ratio=ratio, seed=seed)
+ result: dict[str, Any] = {
+ "total_extracted": len(points),
+ "sample_size": len(sampled),
+ "ratio": ratio,
+ "seed": seed,
+ "sample": sampled,
+ "hint": (
+ "For each point in `sample`, fetch its value from an "
+ "authoritative source, then call the 'verdict' command "
+ "with results=[{id, reported_value, fetched_value, "
+ "fetched_source, ...}]."
+ ),
+ }
+ elif command == "verdict":
+ results = kwargs.get("results")
+ if not isinstance(results, list) or not results:
+ return _err("results (non-empty list) is required for verdict")
+ result = render_verdict(
+ results, report_name=str(kwargs.get("report_name") or ""),
+ )
+ else:
+ return _err(f"unknown command: {command}")
+ except Exception as exc: # noqa: BLE001 - surface a clean tool error
+ return json.dumps(
+ {"status": "error", "command": command, "error": str(exc)},
+ ensure_ascii=False,
+ )
+ return json.dumps(
+ {"status": "ok", "command": command, **result}, ensure_ascii=False,
+ )
+
+
+def _err(msg: str) -> str:
+ return json.dumps({"status": "error", "error": msg}, ensure_ascii=False)
diff --git a/agent/tests/test_financial_rigor_tool.py b/agent/tests/test_financial_rigor_tool.py
new file mode 100644
index 000000000..2e0a3b0bf
--- /dev/null
+++ b/agent/tests/test_financial_rigor_tool.py
@@ -0,0 +1,249 @@
+"""Tests for the ``financial_rigor`` agent tool.
+
+Covers the pure core routines (exact decimal, safe arithmetic, valuation
+math, cross-validation, Benford, three-scenario), the tool's JSON-Schema
+contract, ``execute`` happy/error paths, calc injection rejection, and that
+the tool is auto-discovered into the default registry.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from typing import Any
+
+import pytest
+
+from src.tools import build_registry
+from src.tools.financial_rigor_tool import (
+ FinancialRigorTool,
+ _exact,
+ _fmt,
+ _safe_arith,
+ benford_check,
+ cross_validate,
+ exact_calc,
+ three_scenario_valuation,
+ verify_market_cap,
+ verify_valuation,
+)
+
+# ── helpers ───────────────────────────────────────────────────────────────
+
+
+def test_exact_avoids_float_drift() -> None:
+ # float 0.1 + 0.2 carries binary noise; exact decimal does not.
+ assert _exact(0.1) + _exact(0.2) == _exact("0.3")
+ # str-roundtrip keeps the literal value intact.
+ assert _exact("0.1") == _exact(0.1)
+
+
+def test_fmt_suffixes() -> None:
+ assert _fmt(999) == "999.00"
+ assert _fmt(1500) == "1.50K"
+ assert _fmt(2_500_000) == "2.50M"
+ assert _fmt(4_646_100_000_000) == "4.65T"
+
+
+# ── _safe_arith ───────────────────────────────────────────────────────────
+
+
[email protected]("expr,expected", [
+ ("510 * 9.11e9", 4_646_100_000_000.0),
+ ("1 + 2 * 3", 7.0),
+ ("(1 + 2) * 3", 9.0),
+ ("10 / 4", 2.5),
+ ("-5 + 3", -2.0),
+])
+def test_safe_arith_evaluates(expr: str, expected: float) -> None:
+ assert float(_safe_arith(expr)) == expected
+
+
+ "abc", # bare name
+ "__import__('os')", # function call
+ "os.system('x')", # attribute + call
+ "1 + 2; print(3)", # statements (not a single expression)
+ "'abc'", # string constant, not numeric
+ "1.2.3", # malformed
+])
+def test_safe_arith_rejects_disallowed(evil: str) -> None:
+ with pytest.raises(ValueError):
+ _safe_arith(evil)
+
+
+# ── verify_market_cap ─────────────────────────────────────────────────────
+
+
+def test_market_cap_verdict_thresholds() -> None:
+ # calculated = 510 * 9.11e9 = 4.6461e12
+ assert verify_market_cap(510, 9.11e9, 4.65e12)["verdict"] == "pass" # ~0.08%
+ assert verify_market_cap(510, 9.11e9, 4.50e12)["verdict"] == "warn" # ~3.2%
+ assert verify_market_cap(510, 9.11e9, 4.00e12)["verdict"] == "fail" # ~14%
+
+
+def test_market_cap_fields() -> None:
+ out = verify_market_cap(510, 9.11e9, 4.65e12, currency="HKD")
+ assert out["currency"] == "HKD"
+ assert out["calculated_market_cap"] == pytest.approx(4.6461e12)
+ assert out["calculated_market_cap_display"] == "4.65T"
+ assert out["deviation_pct"] == pytest.approx(0.0839, abs=1e-3)
+
+
+# ── verify_valuation ──────────────────────────────────────────────────────
+
+
+def test_valuation_metrics_exact() -> None:
+ metrics = verify_valuation(price=510, eps=23.5, bvps=120)["metrics"]
+ assert metrics["PE"] == pytest.approx(21.7021, rel=1e-4)
+ assert metrics["PB"] == pytest.approx(4.25)
+ assert metrics["ROE_pct"] == pytest.approx(19.5833, rel=1e-4)
+ assert metrics["earnings_yield_pct"] == pytest.approx(4.6078, rel=1e-4)
+
+
+def test_valuation_skips_zero_and_missing_inputs() -> None:
+ assert verify_valuation(price=100, eps=0, bvps=None)["metrics"] == {}
+
+
+# ── cross_validate ────────────────────────────────────────────────────────
+
+
+def test_cross_validate_marks_outlier() -> None:
+ out = cross_validate("revenue", {"a": 100, "b": 101, "c": 200}, tolerance_pct=2.0)
+ # median of {100,101,200} is 101; 'c' is ~98% off -> inconsistent.
+ assert out["all_consistent"] is False
+ by_src = {s["source"]: s for s in out["per_source"]}
+ assert by_src["c"]["consistent"] is False
+ assert by_src["a"]["consistent"] is True
+
+
+def test_cross_validate_consensus_is_median() -> None:
+ out = cross_validate("rev", {"a": 7500, "b": 7518, "c": 7520})
+ assert out["consensus"] == 7518
+ assert out["all_consistent"] is True
+
+
+# ── benford_check ─────────────────────────────────────────────────────────
+
+
+def test_benford_unreliable_below_50_samples() -> None:
+ out = benford_check([123, 456, 789])
+ assert out["reliable"] is False
+ assert out["sample_size"] == 3
+
+
+def _benford_conforming_sample(n: int = 1000) -> list[int]:
+ """Build a list whose leading-digit distribution tracks Benford's law."""
+ expected = {d: math.log10(1 + 1 / d) for d in range(1, 10)}
+ out: list[int] = []
+ for d in range(1, 10):
+ for _ in range(round(n * expected[d])):
+ out.append(d * 1000 + d) # leading digit is d
+ return out
+
+
+def test_benford_conforming_sample_passes() -> None:
+ out = benford_check(_benford_conforming_sample(1000))
+ assert out["reliable"] is True
+ assert out["is_conforming"] is True
+ assert out["mad"] < 0.015
+ assert len(out["distribution"]) == 9
+
+
+def test_benford_all_same_leading_digit_fails() -> None:
+ out = benford_check([1000 + i for i in range(100)]) # every value starts with 1
+ assert out["reliable"] is True
+ assert out["is_conforming"] is False
+
+
+# ── exact_calc ────────────────────────────────────────────────────────────
+
+
+def test_exact_calc_returns_exact_string() -> None:
+ out = exact_calc("0.1 + 0.2")
+ assert out["result"] == pytest.approx(0.3)
+ assert out["result_exact"] == "0.3"
+
+
+def test_exact_calc_raises_on_disallowed() -> None:
+ with pytest.raises(ValueError):
+ exact_calc("abc")
+
+
+# ── three_scenario_valuation ──────────────────────────────────────────────
+
+
+def test_three_scenario_future_eps_compounding() -> None:
+ out = three_scenario_valuation(
+ current_price=510, current_eps=23.5, shares_billion=9.11,
+ growth_optimistic=0.15, growth_neutral=0.08, growth_pessimistic=0.0,
+ pe_optimistic=25, pe_neutral=20, pe_pessimistic=15, years=3,
+ )
+ bull = next(s for s in out["scenarios"] if s["scenario"] == "bull")
+ assert bull["future_eps"] == pytest.approx(23.5 * 1.15 ** 3)
+ assert bull["target_price"] == pytest.approx(23.5 * 1.15 ** 3 * 25)
+ bear = next(s for s in out["scenarios"] if s["scenario"] == "bear")
+ assert bear["future_eps"] == 23.5 # 0% growth leaves EPS unchanged
+ assert bear["upside_pct"] < 0 # bear case is below current price
+
+
+# ── tool contract ─────────────────────────────────────────────────────────
+
+
+def test_tool_metadata() -> None:
+ tool = FinancialRigorTool()
+ assert tool.name == "financial_rigor"
+ assert tool.is_readonly is True
+ assert tool.parameters["required"] == ["command"]
+ cmds = set(tool.parameters["properties"]["command"]["enum"])
+ assert cmds == {"verify_market_cap", "verify_valuation", "cross_validate",
+ "benford", "calc", "three_scenario"}
+
+
+def test_tool_is_auto_discovered() -> None:
+ registry = build_registry()
+ assert "financial_rigor" in registry.tool_names
+
+
+# ── execute ───────────────────────────────────────────────────────────────
+
+
+def _run(**kwargs: Any) -> dict[str, Any]:
+ return json.loads(FinancialRigorTool().execute(**kwargs))
+
+
+def test_execute_verify_valuation_happy() -> None:
+ env = _run(command="verify_valuation", price=510, eps=23.5, bvps=120)
+ assert env["status"] == "ok"
+ assert env["metrics"]["PE"] == pytest.approx(21.7021, rel=1e-4)
+
+
+def test_execute_calc_rejects_injection_as_error() -> None:
+ env = _run(command="calc", expr="__import__('os')")
+ assert env["status"] == "error"
+ assert "disallowed" in env["error"]
+
+
+def test_execute_missing_required_arg_is_error() -> None:
+ env = _run(command="verify_market_cap", price=510)
+ assert env["status"] == "error"
+
+
+def test_execute_unknown_command_is_error() -> None:
+ env = _run(command="bogus")
+ assert env["status"] == "error"
+ assert "unknown command" in env["error"]
+
+
+def test_execute_benford_small_sample_is_not_reliable() -> None:
+ env = _run(command="benford", values=[1, 2, 3])
+ assert env["status"] == "ok"
+ assert env["reliable"] is False
+
+
+def test_execute_three_scenario_validates_growth_shape() -> None:
+ env = _run(
+ command="three_scenario", price=510, eps=23.5, shares=9.11,
+ growth=[0.1, 0.2], pe=[25, 20, 15], # growth has only 2 entries
+ )
+ assert env["status"] == "error"
diff --git a/agent/tests/test_report_audit_tool.py b/agent/tests/test_report_audit_tool.py
new file mode 100644
index 000000000..0523a3b06
--- /dev/null
+++ b/agent/tests/test_report_audit_tool.py
@@ -0,0 +1,224 @@
+"""Tests for the ``report_audit`` agent tool.
+
+Covers the markdown data-point extraction (tables + ``label: value`` lines,
+Chinese units), sampling (clamp + reproducibility), the verdict logic across
+single/two-source cases (incl. the split-source WARN and the single-source
+FAIL that the original upstream logic mishandled), the tool's JSON-Schema
+contract, ``execute`` happy/error paths, and auto-discovery.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+
+from src.tools import build_registry
+from src.tools.report_audit_tool import (
+ ReportAuditTool,
+ _clean_num,
+ _is_valid_label,
+ _pct_diff,
+ extract_data_points,
+ render_verdict,
+ sample_points,
+)
+
+# ── helpers ───────────────────────────────────────────────────────────────
+
+
+def test_clean_num_handles_wide_comma() -> None:
+ assert _clean_num("1,234") == 1234.0
+ assert _clean_num("1,234") == 1234.0 # wide (full-width) comma
+ assert _clean_num("abc") is None
+
+
+def test_is_valid_label_filters_noise() -> None:
+ assert _is_valid_label("营业收入") is True
+ assert _is_valid_label("来源") is False # skip-listed
+ assert _is_valid_label("a") is False # too short
+ assert _is_valid_label("2024") is False # year only
+ assert _is_valid_label("+56%") is False # bare growth rate
+
+
+# ── extract_data_points ───────────────────────────────────────────────────
+
+
+_REPORT_MD = (
+ "收入:7518亿元\n"
+ "毛利率:56%\n"
+ "\n"
+ "| 指标 | 2024 | 2023 |\n"
+ "|------|------|------|\n"
+ "| 营业收入 | 7518亿 | 6500亿 |\n"
+ "| 净利润 | 1900亿 | 1600亿 |\n"
+)
+
+
+def test_extract_finds_table_and_kv_points() -> None:
+ points = extract_data_points(_REPORT_MD)
+ labels = {p["label"] for p in points}
+ assert "收入" in labels # KV line
+ assert "毛利率" in labels # KV line
+ assert "营业收入 · 2024" in labels # table cell
+ assert "净利润 · 2024" in labels
+ for p in points:
+ assert {"id", "label", "reported_value", "unit", "line_number"} <= set(p)
+
+
+def test_extract_assigns_unique_ids() -> None:
+ ids = [p["id"] for p in extract_data_points(_REPORT_MD)]
+ assert len(ids) == len(set(ids))
+
+
+# ── sample_points ─────────────────────────────────────────────────────────
+
+
+def _pts(n: int) -> list[dict[str, Any]]:
+ return [
+ {"id": i, "label": f"l{i}", "reported_value": float(i), "unit": "",
+ "line_number": i, "raw_text": ""}
+ for i in range(n)
+ ]
+
+
+def test_sample_returns_all_when_fewer_than_three() -> None:
+ assert len(sample_points(_pts(2), ratio=0.5)) == 2
+
+
+def test_sample_clamps_to_max_thirty() -> None:
+ assert len(sample_points(_pts(500), ratio=1.0)) == 30
+
+
+def test_sample_is_reproducible_with_seed() -> None:
+ a = sample_points(_pts(20), ratio=0.5, seed=7)
+ b = sample_points(_pts(20), ratio=0.5, seed=7)
+ assert [p["id"] for p in a] == [p["id"] for p in b]
+
+
+# ── _pct_diff ─────────────────────────────────────────────────────────────
+
+
+def test_pct_diff() -> None:
+ assert _pct_diff(100, 101) == 0.01
+ assert _pct_diff(100, 100) == 0.0
+ assert _pct_diff(0, 0) == 0.0
+ assert _pct_diff(0, 5) == float("inf")
+
+
+# ── render_verdict ────────────────────────────────────────────────────────
+
+
+def test_verdict_single_source_pass() -> None:
+ out = render_verdict([{
+ "id": 1, "label": "rev", "reported_value": 100, "unit": "",
+ "fetched_value": 100.5, "fetched_source": "m",
+ }])
+ assert out["verdict"] == "PASS"
+ assert out["pass_count"] == 1 and out["fail_count"] == 0
+
+
+def test_verdict_single_source_fail_fails_report() -> None:
+ # Regression: a single-source failure must FAIL, not silently WARN.
+ out = render_verdict([{
+ "id": 1, "label": "rev", "reported_value": 100, "unit": "",
+ "fetched_value": 150, "fetched_source": "m",
+ }])
+ assert out["verdict"] == "FAIL"
+ assert out["fail_count"] == 1
+ assert out["fail_items"][0]["label"] == "rev"
+
+
+def test_verdict_two_sources_both_pass() -> None:
+ out = render_verdict([{
+ "id": 1, "label": "rev", "reported_value": 100, "unit": "",
+ "fetched_value": 100.5, "fetched_source": "m",
+ "fetched_value2": 99.8, "fetched_source2": "s",
+ }])
+ assert out["verdict"] == "PASS"
+ assert out["pass_count"] == 1
+
+
+def test_verdict_two_sources_both_fail() -> None:
+ out = render_verdict([{
+ "id": 1, "label": "rev", "reported_value": 100, "unit": "",
+ "fetched_value": 150, "fetched_source": "m",
+ "fetched_value2": 200, "fetched_source2": "s",
+ }])
+ assert out["verdict"] == "FAIL"
+ assert out["fail_count"] == 1
+
+
+def test_verdict_two_sources_split_is_warn_not_fail() -> None:
+ # One source agrees, one misses -> caliber mismatch, not a hard fail.
+ out = render_verdict([{
+ "id": 1, "label": "rev", "reported_value": 100, "unit": "",
+ "fetched_value": 100.5, "fetched_source": "m",
+ "fetched_value2": 150, "fetched_source2": "s",
+ }])
+ assert out["verdict"] == "PASS"
+ assert out["warn_count"] == 1 and out["fail_count"] == 0
+
+
+def test_verdict_skips_points_without_fetched_value() -> None:
+ out = render_verdict([
+ {"id": 1, "label": "a", "reported_value": 100, "fetched_value": None},
+ {"id": 2, "label": "b", "reported_value": 100,
+ "fetched_value": 100, "fetched_source": "m"},
+ ])
+ assert out["total"] == 1 # only the verified point counts
+ assert out["verdict"] == "PASS"
+
+
+# ── tool contract ─────────────────────────────────────────────────────────
+
+
+def test_tool_metadata() -> None:
+ tool = ReportAuditTool()
+ assert tool.name == "report_audit"
+ assert tool.is_readonly is True
+ assert tool.parameters["required"] == ["command"]
+ assert set(tool.parameters["properties"]["command"]["enum"]) == {"extract", "verdict"}
+
+
+def test_tool_is_auto_discovered() -> None:
+ assert "report_audit" in build_registry().tool_names
+
+
+# ── execute ───────────────────────────────────────────────────────────────
+
+
+def _run(**kwargs: Any) -> dict[str, Any]:
+ return json.loads(ReportAuditTool().execute(**kwargs))
+
+
+def test_execute_extract_happy() -> None:
+ env = _run(command="extract", report_text=_REPORT_MD, ratio=0.5, seed=42)
+ assert env["status"] == "ok"
+ assert env["total_extracted"] >= 4
+ assert env["sample_size"] >= 1
+ assert "sample" in env and "hint" in env
+
+
+def test_execute_verdict_fail() -> None:
+ env = _run(command="verdict", results=[{
+ "id": 1, "label": "rev", "reported_value": 100,
+ "fetched_value": 150, "fetched_source": "m",
+ }])
+ assert env["status"] == "ok"
+ assert env["verdict"] == "FAIL"
+
+
+def test_execute_missing_report_text_is_error() -> None:
+ assert _run(command="extract")["status"] == "error"
+
+
+def test_execute_missing_results_is_error() -> None:
+ assert _run(command="verdict")["status"] == "error"
+
+
+def test_execute_unknown_command_is_error() -> None:
+ env = _run(command="bogus")
+ assert env["status"] == "error"
+ assert "unknown command" in env["error"]
diff --git a/agent/tests/test_swarm_presets_packaging.py b/agent/tests/test_swarm_presets_packaging.py
index 11c801575..5e03df359 100644
--- a/agent/tests/test_swarm_presets_packaging.py
+++ b/agent/tests/test_swarm_presets_packaging.py
@@ -19,7 +19,7 @@ from src.swarm.presets import PRESETS_DIR, list_presets, load_preset
# Lock to the canonical roster shipped today. Bump intentionally if a preset
# is added or removed so a release that silently drops files is caught here.
-EXPECTED_PRESET_COUNT = 29
+EXPECTED_PRESET_COUNT = 30
def test_presets_dir_lives_inside_swarm_package() -> None: