@v587d/capital-generation 2.31.7 → 2.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -0
- package/README.md +14 -5
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/analysis/artifact.d.ts +35 -0
- package/lib/analysis/artifact.js +250 -0
- package/lib/analysis/registry.d.ts +16 -2
- package/lib/analysis/registry.js +133 -23
- package/lib/analysis/runtime.d.ts +46 -19
- package/lib/analysis/runtime.js +485 -116
- package/lib/analysis/schemas.d.ts +46 -0
- package/lib/analysis/schemas.js +260 -7
- package/lib/analysis/snapshot.d.ts +10 -3
- package/lib/analysis/snapshot.js +298 -46
- package/lib/analysis/storage.d.ts +29 -1
- package/lib/analysis/storage.js +39 -6
- package/lib/analysis/tools.js +270 -29
- package/lib/analysis/types.d.ts +257 -3
- package/lib/analysis/types.js +31 -1
- package/lib/analysis/validation.d.ts +37 -1
- package/lib/analysis/validation.js +315 -1
- package/lib/chart/tool.js +1 -0
- package/lib/data-collector/store.d.ts +7 -1
- package/lib/data-collector/store.js +14 -0
- package/lib/python-runtime/child-env.d.ts +4 -2
- package/lib/python-runtime/child-env.js +21 -14
- package/lib/python-runtime/manager.d.ts +8 -0
- package/lib/python-runtime/manager.js +30 -14
- package/lib/sources/tencent-http.js +9 -3
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +2 -1
- package/plugin-page/README.en.md +1 -1
- package/plugin-page/README.zh.md +1 -1
- package/preset/capital-generation/agent.patch.yml +1 -1
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
- package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
- package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
- package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
- package/python/analysis/lib/__init__.py +9 -0
- package/python/analysis/lib/errors.py +12 -0
- package/python/analysis/lib/eventstudy.py +164 -0
- package/python/analysis/lib/frames.py +95 -0
- package/python/analysis/lib/gaps.py +54 -0
- package/python/analysis/lib/jsonio.py +61 -0
- package/python/analysis/lib/metrics.py +147 -0
- package/python/analysis/lib/pit.py +84 -0
- package/python/analysis/lib/prices.py +140 -0
- package/python/analysis/lib/timeaxis.py +142 -0
- package/python/analysis/lib/version.py +3 -0
- package/python/analysis/modules/comps_valuation/module.py +26 -59
- package/python/analysis/modules/earnings_bridge/module.py +20 -77
- package/python/analysis/modules/event_study/LICENSE +21 -0
- package/python/analysis/modules/event_study/module.json +217 -0
- package/python/analysis/modules/event_study/module.py +979 -0
- package/python/analysis/modules/financial_quality/module.py +25 -88
- package/python/analysis/modules/hello/module.py +4 -0
- package/python/analysis/modules/kline_quality/module.py +26 -132
- package/python/analysis/modules/portfolio_stress/module.py +27 -112
- package/python/analysis/modules/returns_risk/module.json +108 -25
- package/python/analysis/modules/returns_risk/module.py +68 -227
- package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
- package/python/analysis/modules/simple_backtest/module.json +244 -36
- package/python/analysis/modules/simple_backtest/module.py +1146 -459
- package/python/analysis/modules/statement_integrity/module.py +35 -87
- package/python/analysis/modules/technical_indicators/module.py +33 -152
- package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
- package/python/worker.py +5 -0
- package/watchlist/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,66 @@
|
|
|
7
7
|
- **第三位(patch)**:不破坏既有工具 / 配置 / 会话的新增与修复(如 2.1.1、2.1.2)。
|
|
8
8
|
- **第二位(minor)**:有需要用户知晓的行为变更,且段内附迁移说明(如 2.1.0 的图表呈现通道重做、2.2.0 的数据源与检索来源扩容、2.4.0 的**必须换宿主版本**、2.9.0 的选择器收敛与质检前置——本插件自己的工具与数据契约没变,所以只抬第二位)。
|
|
9
9
|
|
|
10
|
+
## [2.32.0] - 2026-11-28
|
|
11
|
+
|
|
12
|
+
分析层升级:高级分析师给出的每个数可以沿 `Claim → Calculation → ModuleRun → Snapshot → StagedInput → ContentHash`
|
|
13
|
+
逐层回放;历史模拟 2.0 与事件研究 1.0 上线。
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **事件研究 1.0**(高级分析师第 12 颗模块):按公告发布时间与交易日历对齐事件日,输出 AR、CAR、多事件平均 CAR、
|
|
18
|
+
事件前趋势、有效样本、事件日聚集与替代解释;盘前/盘中按当日 bar,盘后与休市按下一交易日,只有日期时保守顺延并标注;
|
|
19
|
+
停牌/缺 bar 顺延不拼收益;缺基准或有效样本为 0 时明确 `blocked`。只描述历史相对表现,不证明因果。
|
|
20
|
+
- **历史模拟 2.0**:A 股 T+1、涨跌停、停牌、整手、分段费用与滑点,输出逐日成交账本、模拟等级与内建审计;
|
|
21
|
+
`run_analysis` 回执带 `simulation`,`submit_analysis` 用 `simulation_run_ref` 绑定。
|
|
22
|
+
- 分析快照升级为 V2:只存输入引用与逐份 sha256/字节数,不再嵌 rows;`as_known_then` 做时点可知(PIT)检查。
|
|
23
|
+
- 结论产物升级为 V2:不可变 revision、内容哈希、跨版本 `changes[]`、分析凭据(`methods` / `data_cutoff` /
|
|
24
|
+
`event_sample_size` 等)。
|
|
25
|
+
- 计算值由宿主从 `result.json` 绑定:模型只能提交 `analysis_run_ref + metric_key`,不能自己写数值;失败、取消、
|
|
26
|
+
超时的 run 也留终态记录。
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
|
|
30
|
+
- 分析子进程环境改为 allowlist,每次运行独立 HOME/TMP;模块执行面固定为 `analyze(request, context)`。
|
|
31
|
+
- 新增错误码(闭集):`analysis_snapshot_too_large`、`analysis_snapshot_corrupt`、`analysis_snapshot_legacy`、
|
|
32
|
+
`analysis_input_hash_mismatch`、`analysis_point_in_time_conflict`、`analysis_event_time_missing`、
|
|
33
|
+
`analysis_adjustment_unknown`、`analysis_calendar_mismatch`、`analysis_run_not_found`、
|
|
34
|
+
`analysis_run_binding_mismatch`、`analysis_method_version_mismatch`、`analysis_metric_binding_invalid`、
|
|
35
|
+
`analysis_metric_undefined`、`analysis_artifact_revision_conflict`、`analysis_simulation_insufficient_data`、
|
|
36
|
+
`analysis_simulation_overclaim`、`analysis_event_insufficient_data`、`analysis_event_overclaim`、
|
|
37
|
+
`analysis_queue_timeout`。
|
|
38
|
+
|
|
39
|
+
### Migration
|
|
40
|
+
|
|
41
|
+
- **升级后 7 天内的旧分析快照只读**:旧版本创建的快照(无 `schema_version`)仍可加载回看,但不能再运行或提交新结论;
|
|
42
|
+
需要时用新版本重建快照后重跑。V1 结论产物只读可加载,不再参与 revision 系列。
|
|
43
|
+
- 回滚开关 `CG_ANALYSIS_V2=0`(只给支持/运维,不写入设置卡):关闭后新快照按 V1 形状写,既有 V2 文件保留可读。
|
|
44
|
+
- 工具面变化需要**重建并重启 dsh 进程**:`run_analysis` 回执新增 `simulation` / `event_study` / `sensitivity`,
|
|
45
|
+
`submit_analysis` 新增 `simulation_run_ref` / `event_study_run_ref` 参数,`credential.event_sample_size` 开始有值。
|
|
46
|
+
|
|
47
|
+
### Notes
|
|
48
|
+
|
|
49
|
+
- 回归:`npm test` **2015 pass / 0 fail**;`npm run check:dsh` 40/40;`npm run smoke:boot` 通过。
|
|
50
|
+
- 真实 DSH 会话验收(前视事件研究 / 涨跌停停牌模拟 / 多事件 CAR)通过;离线最终答复审计脚本
|
|
51
|
+
`npm run audit:answers` 只报告无来源数字率,不作发版门禁。
|
|
52
|
+
- 版本:根包 + 四个随包嵌套包 + `LOCAL_FETCH_CLIENT_VERSION` / `WIND_CLIENT_VERSION` 同步 2.32.0。
|
|
53
|
+
|
|
54
|
+
## [2.31.8] - 2026-11-28
|
|
55
|
+
|
|
56
|
+
修复全量契约巡检新暴露的腾讯分笔时间回退与盘中成交额误核对。
|
|
57
|
+
|
|
58
|
+
### Fixed
|
|
59
|
+
|
|
60
|
+
- `tencent_ticks` 以 `seq` 为权威顺序,容忍上游单笔时间戳向后修正;序号回退仍响亮失败。
|
|
61
|
+
- 成交额核对只在行情快照日期为上海当天且已收盘时执行,避免把上一交易日快照与当日/上一交易日分笔
|
|
62
|
+
错配比较;收盘后的真实缺量仍会失败。
|
|
63
|
+
|
|
64
|
+
### Notes
|
|
65
|
+
|
|
66
|
+
- 真实腾讯分笔复测:4,729 行、`missing_seq=0`,通过。
|
|
67
|
+
- 回归:`npm test` **1921 pass / 0 fail**。
|
|
68
|
+
- 版本:根包 + 四个随包嵌套包 + `LOCAL_FETCH_CLIENT_VERSION` / `WIND_CLIENT_VERSION` 同步 2.31.8。
|
|
69
|
+
|
|
10
70
|
## [2.31.7] - 2026-11-28
|
|
11
71
|
|
|
12
72
|
修复 GitHub Actions 全量契约巡检暴露的 5 条 Fuyao 契约不一致,并把腾讯已解析结构错误纳入 `GUARD`。
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-green" alt="License"></a>
|
|
4
4
|
<a href="https://github.com/v587d/capital-generation"><img src="https://img.shields.io/badge/Financial%20Market-CN%20%7C%20HK%20%7C%20US-orange" alt="Market·CN+HK+US"></a>
|
|
5
5
|
<a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DSH%20Baseline-0.2.2--rc.5-blue" alt="DSH@0.2.2-rc.5"></a>
|
|
6
|
-
<a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.
|
|
6
|
+
<a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.32.0-9cf" alt="Version"></a>
|
|
7
7
|
<a href="https://www.npmjs.com/package/@v587d/capital-generation"><img src="https://img.shields.io/npm/v/%40v587d%2Fcapital-generation" alt="npm version"></a>
|
|
8
8
|
</p>
|
|
9
9
|
|
|
@@ -20,6 +20,13 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
|
|
|
20
20
|
|
|
21
21
|
## 「🎉 高级分析师」 已上线,欢迎试用并提 issue 💕 [快速了解](#senior-analyst)
|
|
22
22
|
|
|
23
|
+
## 「🎉 2.32.0 更新要点」
|
|
24
|
+
|
|
25
|
+
- **结论可以回放了**:高级分析师的结论按「数据快照 → 模块运行 → 计算 → 结论」逐层留档,每个数字都能追到一次真实运行;同一份分析的多次提交会保留版本,能看到这次改了哪个结论、哪组假设或哪批数据。
|
|
26
|
+
- **历史模拟升级**:均线规则的样本内模拟按 A 股 T+1、涨跌停、停牌、整手与分段费用约束成交,附逐日成交账本、模拟等级与审计。它只说明历史样本里发生了什么,不代表策略可执行,也不预测收益。
|
|
27
|
+
- **新增事件研究**:按公告发布时间与交易日历对齐事件日,计算异常收益、累计异常收益与多事件平均结果,并披露有效样本、事件日聚集与替代解释。它只描述历史关联,不证明因果。
|
|
28
|
+
- **升级要做的事**:重启 dsh 进程后在插件页更新到本版;升级前创建的分析快照会变成只读(仍可回看),要继续分析请重建快照后重跑。分析层现在更严格,证据不足时会明确写「部分完成 / 证据不足」,不会为了凑结论而编数字。
|
|
29
|
+
|
|
23
30
|
## 快速上手
|
|
24
31
|
|
|
25
32
|
> [!NOTE]
|
|
@@ -160,18 +167,19 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
|
|
|
160
167
|
- **数据质检:** 结构化数据不会直接进入模型上下文。每份数据先由分析师检查结构、时间轴、缺失与基础统计,再按受控方式汇总;原始数据行始终留在工具层。
|
|
161
168
|
|
|
162
169
|
<a id="senior-analyst" name="senior-analyst"></a>
|
|
163
|
-
- **高级分析师(研究结论复核):** 需要判断的问题不再由取数角色顺手给结论,而是交给「高级分析师」在固定分析模块里算完再下判断。判断类问题包括财务质量复核、收益与风险对比、关键假设的情景与敏感性,以及事件影响、趋势、估值这类需要结论的问题。内置
|
|
170
|
+
- **高级分析师(研究结论复核):** 需要判断的问题不再由取数角色顺手给结论,而是交给「高级分析师」在固定分析模块里算完再下判断。判断类问题包括财务质量复核、收益与风险对比、关键假设的情景与敏感性,以及事件影响、趋势、估值这类需要结论的问题。内置 12 颗分析模块:
|
|
164
171
|
|
|
165
172
|
| 输入 | 模块 | 能回答什么 |
|
|
166
173
|
| :--- | :--- | :--- |
|
|
167
174
|
| 三张报表 | 财务质量、三表勾稽 | 利润的含金量、ROE 驱动、现金转换与偿债;资产 = 负债 + 权益、现金流对账、留存收益滚动是否对得上 |
|
|
168
175
|
| 两期利润表 | 盈利归因 | 净利润变化拆成收入、净利率、税率各自贡献了多少 |
|
|
169
|
-
| 价格序列 | 收益风险、K
|
|
176
|
+
| 价格序列 | 收益风险、K 线清洗、技术指标、历史模拟 | 收益/波动/回撤/夏普与基准 beta;坏 K 线逐行剔除;均线与振荡指标复盘;均线规则的样本内历史模拟(A 股 T+1/涨跌停/停牌/整手约束、分段费用、成交账本、模拟等级与审计) |
|
|
177
|
+
| 公告/事件 + 价格 + 基准 | 事件研究 | 按发布时间与交易日历对齐事件日,在预先声明的事件窗里算异常收益 AR、累计异常收益 CAR 与多事件平均 CAR,披露事件前趋势、有效样本、事件日聚集与替代解释(只描述相对表现,不证明因果) |
|
|
170
178
|
| peers 横截面 | 可比倍数 | P/E、P/B、P/S、EV/EBITDA 的中位数,以及一只标的相对同行的位置 |
|
|
171
179
|
| 多持仓 + 窗口 | 组合回放 | 给定权重在历史区间里的组合收益、逐持仓贡献与集中度 |
|
|
172
180
|
| 假设参数 | 情景与敏感性、DCF 敏感性 | 净利润 = 营收 × 净利率 这类恒等式在不同假设下的取值;DCF 模型值与 WACC×终值增长网格(**不是目标价**) |
|
|
173
181
|
|
|
174
|
-
**结论要能复核。** 结论里的每个数字都要对得回数据集、统计结果或模块计算,插件会逐个数字校验,对不上就退回要求改(这只保证数字有出处,不证明判断本身正确);产物要带正反论据和至少一条能推翻主判断的失效条件,并写明证据充分度、局限与未解决的缺口,有替代解释、冲突点或情景时也要一并列出;证据不足时只给「部分完成」或「证据不足」,不硬凑结论。每次复核都会在工作区留一份结构化产物(`capital-analysis/runs
|
|
182
|
+
**结论要能复核。** 结论里的每个数字都要对得回数据集、统计结果或模块计算,插件会逐个数字校验,对不上就退回要求改(这只保证数字有出处,不证明判断本身正确);产物要带正反论据和至少一条能推翻主判断的失效条件,并写明证据充分度、局限与未解决的缺口,有替代解释、冲突点或情景时也要一并列出;证据不足时只给「部分完成」或「证据不足」,不硬凑结论。每次复核都会在工作区留一份结构化产物(`capital-analysis/runs/`),带版本与内容哈希,可以回看与复算;它属于保留数据,清理数据缓存时不会删除。升级到 2.32.0 后,旧版本创建的分析快照与结论产物只读可回看,需要继续分析时请重建快照后重跑。
|
|
175
183
|
|
|
176
184
|
**边界:** 高级分析师不取数、不读原始数据行、不出图、不写最终答复;它把结论层材料交回自动模式,由自动模式写最终答复、登记图表。它也不给买卖、仓位或目标价建议。模块是仓库内审查过的固定模块,模型只能选模块和参数,不能改模块代码或提交脚本。这些模块跑在插件自带的 Python 运行时里(见上面的「专业分析环境」),没准备环境时会提示先安装,其余功能照常。
|
|
177
185
|
|
|
@@ -226,11 +234,12 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
|
|
|
226
234
|
## 常见问题
|
|
227
235
|
|
|
228
236
|
- **安装后找不到模式?** 确认插件出现在「插件」→ 已安装列表;Web / CLI profile 安装后要重启该 profile,并在新会话选择模式。选择器里应看到自动模式、行情专家、资讯专员;分析师、高级分析师和绘图专员是自动模式的内部角色,不会出现在这里。
|
|
237
|
+
- **升级后旧的分析结论还能看吗?** 能。旧分析快照与结论产物只读保留,可以回看与核对;但要继续运行模块或提交新结论,需要用新版重建快照后重跑。分析产物留在工作区,清理数据缓存时不会删除。
|
|
229
238
|
- **高级分析师是什么角色,什么时候介入?** 它是自动模式里的结论层:需要判断的问题(财务质量、收益与风险、事件影响、趋势、估值、情景)交给它,在固定分析模块里算指标、写结论,结论带正反论据与失效条件。它不取数、不出图、不写最终答复,也不给买卖、仓位或目标价建议;单点事实查询不会派它,复杂问题因为多一层复核会比单纯查数慢一些。证据不足时它会写明「部分完成」或「证据不足」,不硬凑结论。首次使用前记得在插件页准备「分析环境」,否则它会报告环境未就绪。
|
|
230
239
|
- **配置在哪?** 打开「插件」→ 已安装的 **Capital Generation**,插件介绍下方就是「数据源 / 投研自动化 / 精选 Skills / 包含的组件 / 分析环境」五格,五把密钥都在第一格;第二格可指定任务统一使用的默认工作区,也能改自动检查间隔与最长运行时间等上限;第五格准备 Python 分析环境;不在 DSH 的普通「设置」页面,也不用点进任何一行组件。保存密钥后新建会话再试。
|
|
231
240
|
- **升级到 2.9.0 后,分析师和绘图专员去哪了?** 这一版把它们收进自动模式内部,不再出现在选择器与预设管理里,避免误开一个没有取数入口的空会话。旧会话仍能按原身份恢复;新任务直接用自动模式提出即可。
|
|
232
241
|
- **宿主更新后插件显示异常、三个模式消失?** 插件只支持**同一 minor** 的宿主(本版是 `>=0.2.2-rc.5 <0.2.3-0`):宿主跨到 0.2.3 及以上时,旧插件会被启动拒载(插件页显示「异常」)。先把宿主升到与插件同一条 minor,再在插件页更新插件;应急可用版本豁免(有崩溃风险,见 CHANGELOG 的 Migration)。日志里出现「宿主 dsh … 未逐项验证」说明你跑在同一 minor 的未验证补丁版上——能跑,但遇异常请先升级插件并把那行日志附在 issue 里。
|
|
233
|
-
- **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.
|
|
242
|
+
- **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.32.0` 或 `@2.32.0`。
|
|
234
243
|
- **刚发布的新版本装不到?** 桌面端取包时会跳过**刚发布不久**的版本(宿主侧包管理器的发布冷却策略,实测会静默装成上一个版本),国内镜像的同步也可能滞后一段时间。急着用最新代码,改用仓库地址安装最直接;但仓库地址安装的是 git 依赖,插件页不显示「版本」检查。
|
|
235
244
|
- **插件页的「版本」段怎么用?** 只有用包名从 npm 安装的版本才有;它只列比当前新的版本。回旧版要先卸载,再安装 `@v587d/capital-generation@版本号`(桌面端地址末尾加 `#v版本号`);旧版必须匹配当前 DSH 基线,对应关系见 [CHANGELOG 的 Migration](CHANGELOG.md)。
|
|
236
245
|
- **网页抓取失败?** 配置卡片中的「允许启动本地提取网页内容」默认开启:AnySearch 提取失败时可尝试本机直连。关闭后,本机直连的具名来源查询也不可用;请检查该开关和网络连接。
|
package/automation/package.json
CHANGED
package/chart-ui/package.json
CHANGED
package/config/package.json
CHANGED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { SessionLike } from '../data-collector/store.js';
|
|
2
|
+
import { type AnalysisFileWriter } from './storage.js';
|
|
3
|
+
import { type AnalysisArtifact, type ArtifactChange, type ArtifactV2, type Claim, type LoadedArtifact, type TemporalMode } from './types.js';
|
|
4
|
+
/** Hash of a persisted artifact; `artifact_hash` itself is excluded so the field can be verified. */
|
|
5
|
+
export declare function artifactHashOf(record: Readonly<Record<string, unknown>>): string;
|
|
6
|
+
/** V1 claim types are read-only vocabulary: map them for display, never write them back. */
|
|
7
|
+
export declare function claimTypeForDisplay(type: unknown): Claim['type'];
|
|
8
|
+
/**
|
|
9
|
+
* Read the latest artifact. A V1 file is returned as a mapped display view (`legacy: true`,
|
|
10
|
+
* revision 0) so callers never diff against inherited numbering; a V2 file is hash-verified, and a
|
|
11
|
+
* mismatch is a real tamper signal rather than a warning.
|
|
12
|
+
*/
|
|
13
|
+
export declare function loadArtifact(writer: AnalysisFileWriter, session: SessionLike, analysisId: string, signal?: AbortSignal): Promise<LoadedArtifact | undefined>;
|
|
14
|
+
/**
|
|
15
|
+
* What changed between two accepted revisions (plan §5.7 / M4-4). The categories are fixed:
|
|
16
|
+
* `data_update` (inputs/runs), `method_change` (modules/metrics/methodology), `assumption_change`
|
|
17
|
+
* (assumption sources, scenarios, limitations), `conclusion_change` (headline/thesis/claims/status).
|
|
18
|
+
*/
|
|
19
|
+
export declare function diffArtifacts(previous: AnalysisArtifact, next: AnalysisArtifact): ArtifactChange[];
|
|
20
|
+
/** Build the immutable record written to `artifacts/rev-<n>.json`; the hash is computed last. */
|
|
21
|
+
export declare function buildArtifactRecord(input: {
|
|
22
|
+
analysisId: string;
|
|
23
|
+
revision: number;
|
|
24
|
+
supersedes?: string;
|
|
25
|
+
artifact: AnalysisArtifact;
|
|
26
|
+
changes: readonly ArtifactChange[];
|
|
27
|
+
createdAt: number;
|
|
28
|
+
}): ArtifactV2;
|
|
29
|
+
/** The receipt credential (plan §5.8). Every field is host-derived from the persisted revision. */
|
|
30
|
+
export declare function artifactCredential(input: {
|
|
31
|
+
artifactRef: string;
|
|
32
|
+
record: Pick<ArtifactV2, 'artifact_hash' | 'revision' | 'status' | 'validation' | 'methods_used' | 'unresolved_gaps' | 'limitations' | 'simulation' | 'event_study'>;
|
|
33
|
+
temporalMode: TemporalMode;
|
|
34
|
+
dataCutoff?: string;
|
|
35
|
+
}): Record<string, unknown>;
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Artifact V2 persistence: content hash, latest-version loader (V1 display mapping), revision diff
|
|
3
|
+
* and the submit credential. `artifacts/rev-<n>.json` is immutable; `artifact.json` is the pointer.
|
|
4
|
+
* The hash covers the file minus `artifact_hash`, canonically via `stableStringify`.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { stableStringify } from './snapshot.js';
|
|
8
|
+
import { artifactLatestPath, readJsonFile, schemaVersionOf } from './storage.js';
|
|
9
|
+
import { AnalysisError, ARTIFACT_SCHEMA_VERSION, LEGACY_CLAIM_TYPES, } from './types.js';
|
|
10
|
+
const sha256 = (text) => createHash('sha256').update(text, 'utf8').digest('hex');
|
|
11
|
+
/** Hash of a persisted artifact; `artifact_hash` itself is excluded so the field can be verified. */
|
|
12
|
+
export function artifactHashOf(record) {
|
|
13
|
+
const { artifact_hash: _stored, ...rest } = record;
|
|
14
|
+
return sha256(stableStringify(rest));
|
|
15
|
+
}
|
|
16
|
+
/** V1 claim types are read-only vocabulary: map them for display, never write them back. */
|
|
17
|
+
export function claimTypeForDisplay(type) {
|
|
18
|
+
if (type === 'fact' || type === 'inference' || type === 'assumption' || type === 'scenario')
|
|
19
|
+
return type;
|
|
20
|
+
if (type === 'observation' || type === 'hypothesis')
|
|
21
|
+
return LEGACY_CLAIM_TYPES[type];
|
|
22
|
+
throw new AnalysisError('analysis_snapshot_corrupt', `产物里的 claim type 无法识别:${String(type).slice(0, 40)}`);
|
|
23
|
+
}
|
|
24
|
+
function claimsForDisplay(value) {
|
|
25
|
+
if (!Array.isArray(value))
|
|
26
|
+
return [];
|
|
27
|
+
return value.map((item) => {
|
|
28
|
+
const claim = (item !== null && typeof item === 'object' ? item : {});
|
|
29
|
+
return { ...claim, type: claimTypeForDisplay(claim.type) };
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const stringList = (value) => Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
|
|
33
|
+
const textOf = (value) => (typeof value === 'string' ? value : '');
|
|
34
|
+
const statusOf = (value) => value === 'completed' || value === 'partial' || value === 'blocked' ? value : 'partial';
|
|
35
|
+
const evidenceLevelOf = (value) => value === 'sufficient' || value === 'limited' || value === 'insufficient' ? value : 'limited';
|
|
36
|
+
/** Submission-shaped view of a V2 file (`artifact_id` → `analysis_id`), for validation and diff. */
|
|
37
|
+
function submissionViewOf(record) {
|
|
38
|
+
return {
|
|
39
|
+
analysis_id: record.artifact_id,
|
|
40
|
+
task_id: record.task_id,
|
|
41
|
+
snapshot_id: record.snapshot_id,
|
|
42
|
+
status: record.status,
|
|
43
|
+
evidence_level: record.evidence_level,
|
|
44
|
+
headline: record.headline,
|
|
45
|
+
thesis: record.thesis,
|
|
46
|
+
support_claims: record.support_claims ?? [],
|
|
47
|
+
counter_claims: record.counter_claims ?? [],
|
|
48
|
+
alternative_explanations: record.alternative_explanations ?? [],
|
|
49
|
+
contradictions: record.contradictions ?? [],
|
|
50
|
+
calculations: record.calculations ?? [],
|
|
51
|
+
scenarios: record.scenarios ?? [],
|
|
52
|
+
invalidation_conditions: record.invalidation_conditions ?? [],
|
|
53
|
+
unresolved_gaps: record.unresolved_gaps ?? [],
|
|
54
|
+
limitations: record.limitations ?? [],
|
|
55
|
+
methods_used: record.methods_used ?? [],
|
|
56
|
+
peer_exchanges: record.peer_exchanges ?? [],
|
|
57
|
+
...(record.simulation === undefined ? {} : { simulation: record.simulation }),
|
|
58
|
+
...(record.event_study === undefined ? {} : { event_study: record.event_study }),
|
|
59
|
+
validation: record.validation,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** V1 artifact as a display view: claim types mapped, missing V2 fields defaulted. */
|
|
63
|
+
function legacyViewOf(stored, analysisId) {
|
|
64
|
+
return {
|
|
65
|
+
analysis_id: textOf(stored.analysis_id) || analysisId,
|
|
66
|
+
task_id: textOf(stored.task_id),
|
|
67
|
+
snapshot_id: textOf(stored.snapshot_id) || analysisId,
|
|
68
|
+
status: statusOf(stored.status),
|
|
69
|
+
evidence_level: evidenceLevelOf(stored.evidence_level),
|
|
70
|
+
headline: textOf(stored.headline),
|
|
71
|
+
thesis: textOf(stored.thesis),
|
|
72
|
+
support_claims: claimsForDisplay(stored.support_claims),
|
|
73
|
+
counter_claims: claimsForDisplay(stored.counter_claims),
|
|
74
|
+
alternative_explanations: stringList(stored.alternative_explanations),
|
|
75
|
+
contradictions: stringList(stored.contradictions),
|
|
76
|
+
calculations: Array.isArray(stored.calculations) ? stored.calculations : [],
|
|
77
|
+
scenarios: Array.isArray(stored.scenarios) ? stored.scenarios : [],
|
|
78
|
+
invalidation_conditions: stringList(stored.invalidation_conditions),
|
|
79
|
+
unresolved_gaps: stringList(stored.unresolved_gaps),
|
|
80
|
+
limitations: stringList(stored.limitations),
|
|
81
|
+
methods_used: Array.isArray(stored.methods_used)
|
|
82
|
+
? stored.methods_used
|
|
83
|
+
: [],
|
|
84
|
+
peer_exchanges: Array.isArray(stored.peer_exchanges)
|
|
85
|
+
? stored.peer_exchanges
|
|
86
|
+
: [],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Read the latest artifact. A V1 file is returned as a mapped display view (`legacy: true`,
|
|
91
|
+
* revision 0) so callers never diff against inherited numbering; a V2 file is hash-verified, and a
|
|
92
|
+
* mismatch is a real tamper signal rather than a warning.
|
|
93
|
+
*/
|
|
94
|
+
export async function loadArtifact(writer, session, analysisId, signal) {
|
|
95
|
+
const stored = await readJsonFile(writer, session, artifactLatestPath(analysisId), signal);
|
|
96
|
+
if (stored === undefined)
|
|
97
|
+
return undefined;
|
|
98
|
+
if (schemaVersionOf(stored) !== 2) {
|
|
99
|
+
return { analysis_id: analysisId, revision: 0, legacy: true, artifact: legacyViewOf(stored, analysisId) };
|
|
100
|
+
}
|
|
101
|
+
const revision = stored.revision;
|
|
102
|
+
if (typeof revision !== 'number' || !Number.isInteger(revision) || revision < 1) {
|
|
103
|
+
throw new AnalysisError('analysis_snapshot_corrupt', `artifact.json 缺少合法 revision:${analysisId}`);
|
|
104
|
+
}
|
|
105
|
+
const storedHash = stored.artifact_hash;
|
|
106
|
+
if (typeof storedHash !== 'string' || storedHash === '') {
|
|
107
|
+
throw new AnalysisError('analysis_snapshot_corrupt', `artifact.json 缺少 artifact_hash:${analysisId}`);
|
|
108
|
+
}
|
|
109
|
+
const recomputed = artifactHashOf(stored);
|
|
110
|
+
if (recomputed !== storedHash) {
|
|
111
|
+
throw new AnalysisError('analysis_input_hash_mismatch', `artifact.json 的 artifact_hash 与内容不符(记录 ${storedHash.slice(0, 12)}…,重算 ${recomputed.slice(0, 12)}…)`);
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
analysis_id: analysisId,
|
|
115
|
+
revision,
|
|
116
|
+
legacy: false,
|
|
117
|
+
artifact: submissionViewOf(stored),
|
|
118
|
+
artifact_hash: storedHash,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
const sameJson = (left, right) => stableStringify(left) === stableStringify(right);
|
|
122
|
+
const head = (value, length = 40) => String(value ?? '').slice(0, length);
|
|
123
|
+
const numbers = (value) => (Array.isArray(value) ? value.join(', ') : '');
|
|
124
|
+
/**
|
|
125
|
+
* What changed between two accepted revisions (plan §5.7 / M4-4). The categories are fixed:
|
|
126
|
+
* `data_update` (inputs/runs), `method_change` (modules/metrics/methodology), `assumption_change`
|
|
127
|
+
* (assumption sources, scenarios, limitations), `conclusion_change` (headline/thesis/claims/status).
|
|
128
|
+
*/
|
|
129
|
+
export function diffArtifacts(previous, next) {
|
|
130
|
+
const changes = [];
|
|
131
|
+
const push = (category, detail) => {
|
|
132
|
+
changes.push({ category, detail });
|
|
133
|
+
};
|
|
134
|
+
if (previous.snapshot_id !== next.snapshot_id) {
|
|
135
|
+
push('data_update', `快照由 ${head(previous.snapshot_id)} 变为 ${head(next.snapshot_id)}`);
|
|
136
|
+
}
|
|
137
|
+
const before = new Map(previous.calculations.map((item) => [item.calculation_id, item]));
|
|
138
|
+
const after = new Map(next.calculations.map((item) => [item.calculation_id, item]));
|
|
139
|
+
for (const [id, item] of after) {
|
|
140
|
+
const old = before.get(id);
|
|
141
|
+
if (old === undefined) {
|
|
142
|
+
push('method_change', `新增计算 ${id}(${item.metric_key ?? item.metric})`);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (old.metric !== item.metric || old.module_id !== item.module_id || old.module_version !== item.module_version) {
|
|
146
|
+
push('method_change', `计算 ${id} 的指标或模块版本已变化(${old.module_id}@${old.module_version} → ${item.module_id}@${item.module_version})`);
|
|
147
|
+
}
|
|
148
|
+
if (!sameJson([old.analysis_run_ref, old.params_digest, old.input_refs], [item.analysis_run_ref, item.params_digest, item.input_refs])) {
|
|
149
|
+
push('data_update', `计算 ${id} 绑定的 run、参数或输入已变化`);
|
|
150
|
+
}
|
|
151
|
+
if ((old.assumption_source ?? null) !== (item.assumption_source ?? null)) {
|
|
152
|
+
push('assumption_change', `计算 ${id} 的假设来源由 ${String(old.assumption_source ?? '未声明')} 变为 ${String(item.assumption_source ?? '未声明')}`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
for (const id of before.keys()) {
|
|
156
|
+
if (!after.has(id))
|
|
157
|
+
push('method_change', `移除计算 ${id}(${before.get(id)?.metric_key ?? ''})`);
|
|
158
|
+
}
|
|
159
|
+
if (!sameJson(previous.methods_used, next.methods_used)) {
|
|
160
|
+
push('method_change', `methods_used 由 [${numbers(previous.methods_used.map((item) => `${item.module_id}@${item.module_version}`))}] 变为 [${numbers(next.methods_used.map((item) => `${item.module_id}@${item.module_version}`))}]`);
|
|
161
|
+
}
|
|
162
|
+
if (!sameJson(previous.simulation, next.simulation)) {
|
|
163
|
+
push('method_change', '模拟等级、约束或审计结论已变化');
|
|
164
|
+
}
|
|
165
|
+
if (!sameJson(previous.event_study, next.event_study)) {
|
|
166
|
+
push('method_change', '事件研究窗口、方法或有效样本已变化');
|
|
167
|
+
}
|
|
168
|
+
if (!sameJson(previous.scenarios, next.scenarios)) {
|
|
169
|
+
push('assumption_change', '情景假设已变化');
|
|
170
|
+
}
|
|
171
|
+
if (!sameJson(previous.support_claims.filter((item) => item.type === 'assumption').map((item) => item.statement).sort(), next.support_claims.filter((item) => item.type === 'assumption').map((item) => item.statement).sort())) {
|
|
172
|
+
push('assumption_change', '假设型论据已变化');
|
|
173
|
+
}
|
|
174
|
+
if (!sameJson(previous.limitations, next.limitations)) {
|
|
175
|
+
push('assumption_change', '限制说明已变化');
|
|
176
|
+
}
|
|
177
|
+
if (!sameJson(previous.unresolved_gaps, next.unresolved_gaps)) {
|
|
178
|
+
push('data_update', `未解决的数据缺口由 ${previous.unresolved_gaps.length} 条变为 ${next.unresolved_gaps.length} 条`);
|
|
179
|
+
}
|
|
180
|
+
if (previous.status !== next.status || previous.evidence_level !== next.evidence_level) {
|
|
181
|
+
push('conclusion_change', `结论状态由 ${previous.status}/${previous.evidence_level} 变为 ${next.status}/${next.evidence_level}`);
|
|
182
|
+
}
|
|
183
|
+
if (previous.headline !== next.headline)
|
|
184
|
+
push('conclusion_change', '主判断(headline)已改写');
|
|
185
|
+
if (previous.thesis !== next.thesis)
|
|
186
|
+
push('conclusion_change', '论证(thesis)已改写');
|
|
187
|
+
const claimsOf = (artifact) => [...artifact.support_claims, ...artifact.counter_claims]
|
|
188
|
+
.filter((item) => item.type !== 'assumption')
|
|
189
|
+
.map((item) => [item.claim_id, item.type, item.statement, item.number_anchors]);
|
|
190
|
+
if (!sameJson(claimsOf(previous), claimsOf(next))) {
|
|
191
|
+
push('conclusion_change', '正反论据已变化');
|
|
192
|
+
}
|
|
193
|
+
if (!sameJson(previous.invalidation_conditions, next.invalidation_conditions)) {
|
|
194
|
+
push('conclusion_change', '失效条件已变化');
|
|
195
|
+
}
|
|
196
|
+
return changes;
|
|
197
|
+
}
|
|
198
|
+
/** Build the immutable record written to `artifacts/rev-<n>.json`; the hash is computed last. */
|
|
199
|
+
export function buildArtifactRecord(input) {
|
|
200
|
+
const { artifact } = input;
|
|
201
|
+
const unsigned = {
|
|
202
|
+
schema_version: ARTIFACT_SCHEMA_VERSION,
|
|
203
|
+
artifact_id: input.analysisId,
|
|
204
|
+
task_id: artifact.task_id,
|
|
205
|
+
snapshot_id: artifact.snapshot_id,
|
|
206
|
+
revision: input.revision,
|
|
207
|
+
...(input.supersedes === undefined ? {} : { supersedes: input.supersedes }),
|
|
208
|
+
status: artifact.status,
|
|
209
|
+
evidence_level: artifact.evidence_level,
|
|
210
|
+
headline: artifact.headline,
|
|
211
|
+
thesis: artifact.thesis,
|
|
212
|
+
support_claims: artifact.support_claims,
|
|
213
|
+
counter_claims: artifact.counter_claims,
|
|
214
|
+
alternative_explanations: artifact.alternative_explanations,
|
|
215
|
+
contradictions: artifact.contradictions,
|
|
216
|
+
calculations: artifact.calculations,
|
|
217
|
+
scenarios: artifact.scenarios,
|
|
218
|
+
invalidation_conditions: artifact.invalidation_conditions,
|
|
219
|
+
unresolved_gaps: artifact.unresolved_gaps,
|
|
220
|
+
limitations: artifact.limitations,
|
|
221
|
+
methods_used: artifact.methods_used,
|
|
222
|
+
peer_exchanges: artifact.peer_exchanges,
|
|
223
|
+
...(artifact.simulation === undefined ? {} : { simulation: artifact.simulation }),
|
|
224
|
+
...(artifact.event_study === undefined ? {} : { event_study: artifact.event_study }),
|
|
225
|
+
changes: input.changes,
|
|
226
|
+
validation: artifact.validation ?? { status: 'pass', issues: [] },
|
|
227
|
+
created_at: input.createdAt,
|
|
228
|
+
};
|
|
229
|
+
return { ...unsigned, artifact_hash: artifactHashOf(unsigned) };
|
|
230
|
+
}
|
|
231
|
+
/** The receipt credential (plan §5.8). Every field is host-derived from the persisted revision. */
|
|
232
|
+
export function artifactCredential(input) {
|
|
233
|
+
const { record } = input;
|
|
234
|
+
const grade = record.simulation?.grade;
|
|
235
|
+
const sampleSize = record.event_study?.sample_size;
|
|
236
|
+
return {
|
|
237
|
+
artifact_ref: input.artifactRef,
|
|
238
|
+
artifact_hash: record.artifact_hash,
|
|
239
|
+
revision: record.revision,
|
|
240
|
+
status: record.status,
|
|
241
|
+
validation_status: record.validation.status,
|
|
242
|
+
methods: [...new Set(record.methods_used.map((item) => `${item.module_id}@${item.module_version}`))].sort(),
|
|
243
|
+
data_cutoff: input.dataCutoff ?? null,
|
|
244
|
+
temporal_mode: input.temporalMode,
|
|
245
|
+
gaps: record.unresolved_gaps.length,
|
|
246
|
+
limitations: record.limitations.length,
|
|
247
|
+
simulation_grade: typeof grade === 'string' ? grade : null,
|
|
248
|
+
event_sample_size: typeof sampleSize === 'number' && Number.isInteger(sampleSize) ? sampleSize : null,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
@@ -1,12 +1,26 @@
|
|
|
1
1
|
import type { ModuleManifest } from './types.js';
|
|
2
2
|
export interface AnalysisModuleEntry {
|
|
3
3
|
readonly manifest: ModuleManifest;
|
|
4
|
-
/** Absolute directory handed to the worker; always inside the package. */
|
|
4
|
+
/** Absolute directory handed to the worker; always inside the package (or a test fixture). */
|
|
5
5
|
readonly dir: string;
|
|
6
6
|
readonly entrypoint: string;
|
|
7
7
|
}
|
|
8
|
+
/** Provenance of the bytes that produce a result; part of `run_fingerprint`. */
|
|
9
|
+
export interface ModuleCodeFacts {
|
|
10
|
+
readonly module_code_hash: string;
|
|
11
|
+
readonly entrypoint_sha256: string;
|
|
12
|
+
readonly manifest_sha256: string;
|
|
13
|
+
/** `python/analysis/lib/**` tree digest; `null` while the shared-primitives package does not exist. */
|
|
14
|
+
readonly lib_digest: string | null;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Hash the module bytes for the run fingerprint. Cached per directory: module code is fixed for the
|
|
18
|
+
* life of the process; `resetAnalysisModuleCache` clears it for fixture rewrites.
|
|
19
|
+
*/
|
|
20
|
+
export declare function moduleCodeFacts(entry: Pick<AnalysisModuleEntry, 'dir' | 'entrypoint' | 'manifest'>): ModuleCodeFacts;
|
|
21
|
+
export declare function normalizeManifest(value: unknown, moduleId: string): ModuleManifest;
|
|
8
22
|
/** Registered modules, manifest-normalized. Throws when a registered module cannot be read. */
|
|
9
23
|
export declare function listAnalysisModules(): readonly AnalysisModuleEntry[];
|
|
10
24
|
export declare function analysisModuleById(moduleId: string): AnalysisModuleEntry | undefined;
|
|
11
|
-
/** Test-only: drop the manifest
|
|
25
|
+
/** Test-only: drop the manifest and code-hash caches so a fixture rewrite is visible. */
|
|
12
26
|
export declare function resetAnalysisModuleCache(): void;
|