diff --git a/research/finance_program_v1/README.md b/research/finance_program_v1/README.md index f705054..286e7d1 100644 --- a/research/finance_program_v1/README.md +++ b/research/finance_program_v1/README.md @@ -1,69 +1,37 @@ -# Finance Program:non-training 与第一版 Planner SFT +# 金融 Program 主干:原版 F66 + Planner SFT -本目录保留 non-training、教师轨迹采集、第一版学生 Planner SFT 的代码,以及完整金融 **Val422** 的同接口配对评估结果。它是独立研究快照,不替换仓库原应用。 +本目录围绕一个实验问题组织:**同一 F66 Program/Skill 框架下,只训练 Planner,是否能改善未训练 Planner 的分类与终止表现?** 主干是 Teacher200 → Planner-only LoRA SFT → `base` / `sft` 固定来源配对评估。 -## 完整 Val422 结果 +本次整理基于 GitHub 原版 `b6fde9b80802593ad8ab30bdfae66fc28483a849`,只整理金融 Program。运行代码的改动限排版和注释;提示词、Skill body、原控制流、预算、adapter 路由、训练目标和已有结果保持原版语义。2026-11-09 本地 recovery 修复版不在此目录。 -两组均为 Qwen3.5-9B,在相同 F66 Program/Skill 框架、输入与执行预算下比较: +## 先读哪些文件 -- **ProgSkill / `base`**:未微调 Planner,仍调用 Skill,**不是直接回答的纯 Base-LLM**。 -- **DCG-SFT / `sft`**:只加载第一版 Planner SFT A;所有模型型 Skill 继续使用原始基座并禁用 adapter。 +1. [完整实验协议](docs/EXPERIMENT_PROTOCOL.md):条件、数据、训练、推理、评分和可比范围。 +2. [代码职责与数据流](docs/ARCHITECTURE.md):从 Planner 到执行器、模型路由和审计。 +3. [运行与验证说明](REPRODUCE.md):可直接运行的 CPU 检查,以及真实复现还需要的资产。 +4. [历史快照说明](docs/HISTORY.md):为什么旧 P14 不再作为第二套 non-training 主干。 -共 **422 个唯一配对、844 条正式轨迹**。失败与未终止均保留在每组 422 的分母内,双方无缺失。 - -| 指标 | ProgSkill:未微调 Planner | DCG-SFT:第一版 Planner SFT | 提升 | -| --- | ---: | ---: | ---: | -| 类别正确率 | 79/422,18.72% | **171/422,40.52%** | +21.80 个百分点 | -| 等级正确率 | 111/422,26.30% | **230/422,54.50%** | +28.20 个百分点 | -| 类别与等级联合正确率 | 79/422,18.72% | **171/422,40.52%** | +21.80 个百分点 | -| 合法终止率 | 191/422,45.26% | **420/422,99.53%** | +54.27 个百分点 | -| 首次 Top-5 命中率 | 177/422,41.94% | **251/422,59.48%** | +17.54 个百分点 | -| 最终 Top-5 命中率 | 177/422,41.94% | **251/422,59.48%** | +17.54 个百分点 | -| 任次 Top-5 命中率 | 177/422,41.94% | **251/422,59.48%** | +17.54 个百分点 | -| 类别 Macro-F1:8 个有支持类别 | 0.18845 | **0.32218** | +0.13373 | -| 类别 Macro-F1:固定 12 类 | 0.12563 | **0.21479** | +0.08916 | -| 未合法终止 | 231 | **2** | 减少 229 条 | -| 缺失轨迹 | 0 | 0 | 无缺失 | - -逐 ID 配对联合正确性:**99 条改善、7 条退步,净增加 92 条正确结果**。三种 Top-5 口径分别计算,本轮数值恰好相同。合法终止率不等于业务正确率。 - -| 调用与成本(422 条/组) | ProgSkill | DCG-SFT | 相对减少 | -| --- | ---: | ---: | ---: | -| 模型调用总数 | 2,897 | 1,695 | 41.49% | -| 平均模型调用数/来源 | 6.86 | 4.02 | 41.49% | -| 输入 token 总数 | 30,563,818 | 11,128,130 | 63.59% | -| 输出 token 总数 | 319,905 | 93,618 | 70.74% | -| 平均来源执行耗时 | 34.03 秒 | 11.03 秒 | 67.58% | - -耗时为各来源执行 receipt 的均值,包含失败来源,不是整轮墙钟或服务时延承诺。原已验证部分精确复用,其余来源唯一补充,完整集合无重叠遗漏;没有按结果重跑或筛除。原、新两个阶段墙钟分别保存于 JSON,不能当作同一次完整运行的墙钟测量。 - -## 代码与结果目录 - -| 目录 | 内容 | +| 目录 | 主干职责 | | --- | --- | -| `nontraining/` | 历史 non-training 执行及审计代码;历史接口不作为本表的严格配对对照 | -| `teacher/` | **百炼 `qwen3.8-2.4t-a95b`** 的教师轨迹采集代码,不是 9B 教师模型 | -| `sft/` | 第一版 Qwen3.5-9B Planner-only LoRA,200 个训练来源 | -| `evaluation/` | 原同接口评估、模型路由和控制器回放代码快照;示例数据为合成测试 fixture,不是完整真实验证数据 | -| `trajectories/` | 教师 200 条、完整验证 `base` 422 条与 `sft` 422 条,共 **1,044 条脱敏公开轨迹** | -| `tools/`、`publication_tests/` | 轨迹脱敏工具与隐私回归测试 | -| `results/` | [完整指标](results/evidence-summary.json)、[轨迹清单与 SHA](results/trajectory-export.json)、[模型角色](results/model-roles.json)、[验证说明](results/publication-verification.json) | - -## 验证与隐私边界 - -所有服务器阶段及完整回放成功退出;本机从各自解包目录再次完整回放,并逐 SHA 核验原始证据全部成员及 844 份正式轨迹。逐 ID 指标、配对统计和两种 Macro-F1 已独立重算。聚合 JSON 保留证据 SHA 依赖,但不发布私有目录和来源 ID。 - -公开轨迹只保留 Program、实际步骤状态、最终类别/等级与原 trace SHA;业务元数据、原始消息、推理文本和语义证据已脱敏。两组学生使用一致的顺序公开编号;无私有 ID 映射。它们**不是训练数据,也不是完整控制器回放输入**。教师轨迹保持不变。 - -这是开发验证集、单 seed,仅 8/12 类有支持,且来源可能共享表;不是独立 Test 或跨领域泛化结论。教育与钢铁数据集不在本轮结果内。该更新只替换结果展示和学生公开轨迹,不修改实验代码、权重或训练设置。 - -真实数据集、gold、权重、凭证和实验服务器地址均不上传。clone/import 不会启动任何训练、GPU 或 API 作业。复现说明见 [REPRODUCE.md](REPRODUCE.md)。 +| `teacher/` | 百炼 `qwen3.8-2.4t-a95b` 的采集、显式策略、传输重试和账本 | +| `sft/` | 真实 Planner Program JSON + EOS 的数据导出、分词和第一版 LoRA SFT | +| `evaluation/runtime/` | **唯一主干 runtime**:原版 F66 控制器、binder、Skill 与 terminal guard;两臂共享 | +| `evaluation/` | 仅 Planner 启用 adapter 的路由、执行、原调用回放、身份检查和指标 | +| `nontraining/README.md` | 未训练 Planner 条件的导航;直接指向同一 F66 runtime,没有第二套复制代码 | +| `results/`、`trajectories/` | 原聚合结果和1044条脱敏轨迹,字节不变 | +| `tools/`、`publication_tests/` | 脱敏与公开依赖验证;CPU 检查不运行真实模型 | -## 发布依赖修复(2026-10-19) +## 已发布的同协议 Val422 结果 -补回历史批次审计模块与源代码/官方模型哈希清单、教师录制调用回放助手,以及评估旧后端的SHA清单工具。未改变模型、实验协议、训练参数、结果数字或公开轨迹。 +每组固定422来源,合844条正式轨迹。`base` 是**未训练 Planner 调用 Skills**,不是直接回答的 Base-LLM;`sft` 只启用第一版 Planner adapter,模型型 Skill 两臂均用基座。 -`pool_metadata.py` 位于 `nontraining/vendor/` 和 `evaluation/runtime/vendor/`,不是仓库根目录模块。通过 `program_loop` 导入时会初始化对应的vendor路径;若只使用该工具,请按 [REPRODUCE.md](REPRODUCE.md) 设置明确的导入路径。新增隔离进程回归覆盖批次入口、完整合成回放和请求篡改拒绝。 +| 指标 | base / ProgSkill | sft / DCG-SFT | +| --- | ---: | ---: | +| 类别匹配 | 79/422(18.72%) | 171/422(40.52%) | +| 等级匹配 | 111/422(26.30%) | 230/422(54.50%) | +| 合法终止 | 191/422(45.26%) | 420/422(99.53%) | +| 实际模型调用 | 2897 | 1695 | -**代码依赖补齐不等于发布了私有数据/历史执行目录。** 历史 `teacher/collect.py`、`teacher/detached.py`、评估watcher/legacy环境身份仍要求经授权的原始配置、manifest、ledger或数据;不得直接运行它们来启动付费请求/GPU。公开CPU测试不需要这些私有资产。 +逐来源有99改善、7退化。完整分母、Top5、F1、成本与阶段墙钟保存在 [evidence-summary.json](results/evidence-summary.json)。本次未重新训练、生成或评分;旧结果不是本次排版后的新实验。 +Val422 是已观察开发集,只有8/12类有支持、来源可能共享业务上下文;它不提供专家 Gold 或独立业务族保证。合法终止不等于业务正确。公开轨迹脱敏有损,不能用于全量控制器回放或直接训练。M8/M9/M10、后续 Skill SFT 和其他 RL/领域实验不属于这份第一版 Planner 主干协议,不能与本表直接拼成统一对照。 diff --git a/research/finance_program_v1/REPRODUCE.md b/research/finance_program_v1/REPRODUCE.md index 22658ef..5e615c0 100644 --- a/research/finance_program_v1/REPRODUCE.md +++ b/research/finance_program_v1/REPRODUCE.md @@ -1,75 +1,38 @@ -# Reproduction and publication boundaries +# 金融主干运行与复现 -## CPU tests +先读 [实验协议](docs/EXPERIMENT_PROTOCOL.md)。在 `research/finance_program_v1` 工作;Python3.11+。原公开验证环境曾用Python3.13/Torch2.9 CPU。真实9B历史环境为Torch2.9、Transformers5.10.4、PEFT0.21、Accelerate1.15;这里只说明历史环境,不在import/test时安装或下载。 -Run stages in separate processes from their own directories; names such as `gate` and `io_utils` are intentionally local: +## 可直接运行:CPU测试 + +以下阶段使用合成/录制I/O,分别启动进程,避免同名 `gate`/`io_utils`/`program_loop` 混入另一个阶段: ```powershell -cd nontraining -python -B -m pytest tests -q -p no:cacheprovider -cd ../sft +Set-Location teacher +python -B -m pytest tests -q -p no:cacheprovider --basetemp .test-tmp +Set-Location ../sft python -B -m unittest discover -s tests -v -cd ../evaluation +Set-Location ../evaluation python -B -m unittest discover -s tests -v -cd .. +Set-Location runtime +python -B -m pytest tests -q -p no:cacheprovider --basetemp .test-tmp +Set-Location ../.. python -B -m unittest discover -s publication_tests -v ``` -Python 3.11+ is expected. The original publication checks used Python 3.13 with Torch 2.9 CPU operations. The actual 9B experiment used Torch 2.9 / Transformers 5.10.4 / PEFT 0.21 / Accelerate 1.15. These CPU tests do not download models or start GPU or teacher API work. The result update does not alter the original experiment code or its synthetic fixtures. - -`evaluation/data/study.json` is a fictional field/category fixture, **not the real Val422 dataset**. The private-data prompt integration test and private transport/deployment/download helpers are excluded. Adapter fixtures contain architecture/configuration only, with a placeholder base path. - -## Full financial Val422 results - -The current [aggregate result](results/evidence-summary.json) covers all 422 unique sources and 844 formal trajectories, comparing an untrained Planner and the accepted first SFT A under the same F66 Program/Skill interface. Both arms call Skills; `base` is not a direct-answer Base-LLM. Model Skills always use the original base without adapter; only the SFT Planner enables the accepted LoRA. - -The already verified subset was reused byte-for-byte and all remaining sources were run once under the same frozen protocol. Original smoke trajectories are excluded from formal metrics. The source union is exact and disjoint; failures and nontermination remain in each fixed 422 denominator. Labels were used only locally after generation and replay, never uploaded or inserted into model messages. Separate generation-stage walls are recorded, not represented as one full-run wall measurement. - -All remote stages, controller/tokenizer/routing replay and archive steps exited successfully. On Windows the original and supplementary archives were safely extracted and all listed member hashes rechecked; full controller replay ran from each extracted root. The local replay does not claim a local real tokenizer: it is bound to the same-SHA remote real-tokenizer proof. All 844 formal trace hashes, per-ID metrics, paired counts and Macro-F1 were independently rechecked before publication. - -Full numerical reproduction requires controlled input study/registry, exact source partition and order, local-only gold, full raw traces, original model revision and accepted first LoRA. These are not public. The `evaluation/` directory retains the original evaluation/replay code snapshot; it is not a self-contained launcher with private full-dataset orchestration or production data. The public JSON and trajectory views are a result release, not a replacement deployment bundle. - -For controlled real execution, create a new owned configuration/manifest with authorized assets and the prescribed resource/identity checks. Do not overwrite immutable runs, silently change budgets/labels or infer permission for GPU/API work from this publication. - -## Teacher and student trajectories - -The current release contains **1,044 lossy projections**: unchanged teacher 200, matched full-validation base 422 and SFT 422. The teacher is **Bailian `qwen3.8-2.4t-a95b`**, not a locally trained 9B teacher. The first student uses 200 teacher-selected sources for Planner-only Program+EOS SFT; Skill output text and evaluation labels are not supervision. - -Both student files align on public IDs `val-0001` through `val-0422`. No private source-ID mapping is published. The original trace SHA identifies controlled evidence; it is not the SHA of the redacted row. [trajectory-export.json](results/trajectory-export.json) records public-file sizes, row counts and SHA values, including the unchanged teacher file. - -Actual Program structure, attempts, execution statuses and final classification/grade are retained. Prompts, raw reasoning, source metadata and semantic observation values are omitted. Literal arguments are replaced by `[REDACTED]` and flagged; unparseable replies retain status/digest, not raw text. No failed row is removed. This format cannot independently establish semantic correctness and must not be used as training data or full replay input. +每次pytest使用独占临时目录或新路径;Windows上系统旧pytest临时符号链接可能产生清理权限错误,不能因此改业务代码。CPU通过只证明契约/路由/回放/监督边界,不是9B语义准确率或GPU显存证据。 -The prior partial-validation result tables and standalone partial trajectory files are no longer part of the current branch tree. Original raw evidence and its cryptographic provenance remain preserved privately; the first SFT weights, teacher trajectories and experiment source code are unchanged. +## 受控真实执行的顺序 -## Interpretation +1. 准备授权原始metadata、标准Registry、固定来源/分区/顺序、当前源码SHA、模型revision和逐文件身份;labels另存本地评估侧。公开 `study.json` 是合成fixture,不能替代这些资产。 +2. Teacher采集使用 `teacher/collect.py`/`detached.py` 和版本化policy,密钥仅内存由调用方供给。占位config不是历史账本,不能直接复用付费额度。 +3. 用 `sft/export_dataset.py`核200个来源与真实接受的Program;`token_audit.py --data ... --model ... --output ...`核无截断与响应+EOS监督。准备受控manifest、token审计和model identity后,才使用 `train_student.py --mode trial`,proof通过后fresh `--mode formal`。历史pipeline负责资源锁和实际退出;正式训练不会继承trial更新。 +4. 评估使用 `evaluation/evaluate.py --cohort smoke`,然后按新的受控队列执行评估。原公开runner只提供smoke/val80接口;完整历史Val422补充协调器及私有配置未发布,不能把这个命令声称为一键422复现。两个arm均显式F66与相同study预算;只有sft的Planner开adapter。 +5. 停写后运行 `evaluation/replay.py`、训练/路由身份gates,再本地评分、固定分母与独立复核。原run与manifest不可覆盖。 -Val422 is a development set with eight supported classes out of twelve, one seed and potentially correlated table sources. It is not held-out Test or independent generalization. Supported-class and fixed-twelve-class Macro-F1 are reported separately; legal termination is not business correctness. Historical non-training interfaces are not interchangeable with this matched F66 comparison. - -## Publication dependency repair (2026-10-19) - -The public nontraining audit now includes `reviews/independent_audit_01.py`, its exact historical source SHA inventory, the public official-model file-hash inventory, and the two omitted source files needed by that inventory. This preserves the historical 121-file/109-core-file signature; it does not fabricate a historical run or ship model weights. `batch_audit.py` imports and a real-controller recorded-I/O replay with synthetic source data are covered by fresh isolated-process tests, including tampered-request rejection. - -Additional restored code: `teacher/pilot_audit.py` contains only the recorded retry/I-O replay helpers used by `detached.py`, not the private-gold historical quality aggregator. The public teacher runtime resolves to the already included `evaluation/runtime` when no controlled local `teacher/runtime` is present. `evaluation/legacy/tools/freeze_revision.py` restores the original pure SHA inventory helper, not the private revision manifests or a new deployment authorization. Legacy environment-identity functions still require their controlled snapshot layout; this code snapshot is not a turnkey historical deployment. - -### Import paths and CPU checks - -From `research/finance_program_v1/nontraining`: - -```powershell -python -B -c "import batch_audit; import program_loop; import pool_metadata; print(pool_metadata.__file__)" -``` - -If using only the standalone metadata helper in your own Python program, add the explicit snapshot directory before importing it: - -```python -import sys -from pathlib import Path -snapshot = Path("research/finance_program_v1/nontraining").resolve() -sys.path.insert(0, str(snapshot / "vendor")) -from pool_metadata import PoolMetadata -``` +真实GPU/API命令需要资产和资源门全部满足;本次整理未执行这些步骤。各脚本的 `--help` 说明保留原参数。`pipeline.py`/`watch.py`是受控运行协作者,不能把缺失私有manifest当作公开CPU示例失败。 -Do not copy files between different historical snapshots or rely on another checkout's PYTHONPATH. Run the teacher synthetic suite from `teacher/` with `python -B -m pytest tests -q -p no:cacheprovider`. Run the publication checks from this directory with `python -B -m unittest discover -s publication_tests -v`; dependency checks use `-I` fresh processes so private/local import paths cannot mask missing modules. +## 结果与可复现程度 -`python -B -m reviews.independent_audit_01 --help` and `python -B batch_audit.py --help` are safe CPU-only entrypoint checks. Actual audit commands need complete, authorized, unredacted recorded runs and the matching study/model manifests; redacted public trajectories cannot substitute for them. Cloning/importing/testing does not authorize or start new model downloads, API calls, training, or GPU work. +`results/evidence-summary.json`是原422/844聚合;`results/model-roles.json`绑定teacher/第一版adapter和训练数据;`results/trajectory-export.json`记录1044条公开投影的大小/SHA。原结果文件和轨迹此次字节不变。`results/publication-verification.json`是原历史发布收据,不能当作本次新的测试结果;本次整理验证记录在 `docs/curation-verification.json`。 +公开轨迹隐藏了私有ID/metadata、实际prompt、语义文本及推理,保留状态、Program投影、最终类别/等级和原trace摘要。它们不是模型训练数据,也不足以全轨迹逐字回放。完整数值复现需私有输入与标签、完整原调用及权重,现有公开代码不能独立恢复这些信息。 diff --git a/research/finance_program_v1/docs/ARCHITECTURE.md b/research/finance_program_v1/docs/ARCHITECTURE.md new file mode 100644 index 0000000..62ebc39 --- /dev/null +++ b/research/finance_program_v1/docs/ARCHITECTURE.md @@ -0,0 +1,29 @@ +# 主干代码导读 + +```text +Teacher受控采集 -> 原始接受的Planner消息/Program -> export_dataset/token_audit + | + Planner-only SFT adapter + | +同一来源 + F66 runtime -> base Planner / SFT Planner -> Skill(base) -> trace/calls/route + | + exact replay / identity gates -> 本地metrics +``` + +## 外层规划与执行 + +`evaluation/evaluate.py` 负责固定来源、AB/BA和每臂输出目录;`backend.py`只负责实际模型与adapter路由。`io_utils.py`在一个明确边界初始化本阶段runtime/legacy导入。不同阶段的短模块名不要在同一Python进程混用。 + +`runtime/program_loop/controller.py`只协调 Planner→parse→执行Program→收集observation→终止/再次规划,并保存budget与trace。`planner.py`/`catalog_context.py`/`planning_contracts.py`生成公共契约及消息。`validation.py`检查Program结构、引用、依赖与长度;执行时 `execution.py`重新绑定实际state并交给底层guard。静态可能生产者不是已取得的事实。 + +`runtime/vendor/pool_runtime.py`、`pool_catalog.py`组合F66池与类型检查;底层 `vendor/runtime/code/agent/orchestration/model_skill_executor.py`组装Skill实际请求、读取模型输出并验证。`vendor/runtime/skills/full_pool/`是各Skill公共body;名称解释、描述、比较、分类与最终终止各有契约。名称/描述已使用grounded对象的路由不能称为独立名称推理。 + +## 训练与证据 + +`sft/export_dataset.py`保留来源与实际响应边界,`token_audit.py`做完整prompt前缀与Program+EOS监督,`completion_loss.py`核因果loss边界。`train_student.py`做最长样本trial与fresh formal;`pipeline.py`管资源锁、实际子进程退出与阶段门。 + +`evaluation/replay.py`消耗已记录模型回应,拒绝请求消息或调用顺序变化;`gate.py`核adapter/身份/真实退出;`runtime_identity.py`绑定运行源码;`metrics.py`保留固定分母。`evaluation/legacy/`仍是这些原版模块的必要模型/哈希依赖,不是第二个主干runtime,不能为目录看起来短而删除。 + +`teacher/teacher_api.py`处理SSE,`retry_backend.py`只重试授权范围内的传输问题,`campaign_budget.py`等记录安全账本;`policy.py`是显式版本化消息变体,`detached.py`是历史受控协调器。`pilot_audit.py`在采集回放中是必要依赖,虽然名字含pilot,也不应仅按名字删除。 + +源码排版展开了原单行多语句、条件和字典;注释集中解释来源隔离、预算、路由、监督和失败恢复。没有通过注释暗示原版不存在的修复。公共库仍支持部分旧接口,主干入口明确选F66。 diff --git a/research/finance_program_v1/docs/EXPERIMENT_PROTOCOL.md b/research/finance_program_v1/docs/EXPERIMENT_PROTOCOL.md new file mode 100644 index 0000000..e196bdd --- /dev/null +++ b/research/finance_program_v1/docs/EXPERIMENT_PROTOCOL.md @@ -0,0 +1,49 @@ +# 金融 Program 主干实验协议 + +## 1. 对照问题与版本 + +主对照为原版 F66 `base` 与 `sft`。两臂用同一基座、输入来源、完整66个 Skill、标准库、预算与生成参数;只切换第一版 Planner LoRA。所有 Skill 模型调用均关闭 adapter,包括 SEARCH 和分类。`evaluation/backend.py` 以可信 Planner system 消息识别路由并保存层状态,生成失败后也恢复关闭。 + +代码整理起点为 `b6fde9b80802593ad8ab30bdfae66fc28483a849`。历史结果对应受控执行的冻结身份;整理后源码SHA会因注释排版改变,不能把新源码冒充旧运行的逐字源码。运行语义由整理前后 AST 比较和CPU测试核对。新真实运行必须建立自己的 manifest,不能覆写历史 manifest。 + +## 2. 数据、输入与目标 + +- Teacher 为百炼 `qwen3.8-2.4t-a95b`;发布的200条轨迹对应806次已核实 HTTP 请求。当前 `config.example.json` 是占位示例,其单次请求预算不代表原806次完整采集总预算。 +- 学生使用固定200个训练来源,另14个 reserve 不参与训练。选择、实际原消息、接受的 Program 与来源覆盖由 `sft/export_dataset.py` 核对,不从公开脱敏轨迹反造训练数据。 +- 学生监督仅为真实 Planner Program JSON + tokenizer EOS;prompt、Skill回应、元数据与评估标签不计算训练 loss。分词边界逐项验证,超长直接拒绝,不截断。 +- 实际模型可见初始输入只有 domain/field_name;其他元数据由实际 Skill 取得。内部 source_id 是查找标识,不作为业务语义或答案。binder可为 `{}` 补齐已有 required输入,不能称模型独立生成了全部参数。 +- `evaluation/data/study.json` 只有合成字段/类别,`protocol.json` 是公开 Planner system;它们不是完整Val422输入、参考标签或分区清单。 + +## 3. 第一版 Planner SFT + +学生 `Qwen/Qwen3.5-9B`,revision `c202236235762e1c871ad0ccb60c8ee5ba337b9a`;接受的 adapter SHA `81b18e85c5ce9ceb9585cf069a87d389567a2be47198c35a0d79d73f850a2abc`。训练数据SHA见 `results/model-roles.json`。 + +`sft/train_student.py` 固定:1 epoch,200来源,microbatch=1,累积16,13次优化更新;AdamW,lr=1e-4、cosine、warmup3、weight_decay=.01、max_grad_norm=1。LoRA r8/alpha16/dropout.05,仅语言层40个实际目标模块(q_proj/v_proj/in_proj_qkv 后缀),base与vision冻结。BF16,三个精确身份GPU,27GiB/卡分片,梯度检查点;保留完整上下文,仅计算completion对应logits/loss,并将反向保存张量暂存CPU。不是全参数训练或Skill SFT。 + +先最长来源 trial,实际核有限 loss/gradient、LoRA更新、全部目标设备;formal必须重新加载新基座、核数据与试跑manifest,不能接着trial继续训练。正式期同时核200个来源各消费一次、13次有限梯度更新和只保存adapter。实际GPU身份/空闲证明属于受控manifest,不在占位示例中硬造。 + +## 4. F66 推理与预算 + +正式配置从受控study/config读取。公开合成study展示原实验预算:4 Planner尝试、3 Program、12 Skill步骤、单Program最多10步、相同调用限1。`ProgramConfig` 的通用构造默认值不同;主实验入口显式传study预算,不能用默认值替换并声称同协议。 + +评估seed在legacy中固定为20260928;SFT seed由受控manifest提供,不能仅凭评估seed补写未公开的训练配置。生成由 `evaluation/legacy/local_smoke.py` 与 `backend.py` 约束:greedy、max_new_tokens512、max_time90秒、上下文32768,超上下文拒绝且不截断。原模型EOS和监督tokenizer EOS取并集并核身份(248044/248046)。全模型和adapter FP16/cuda0冻结;正式训练资源与评估资源不同。 + +SEARCH由原版模型生成五个实际供给的短ID,再由执行器绑定标准;没有换成后续M9的三prefix概率排名。`evaluate.py` 每来源交替AB/BA,只有真实terminal guard通过才记合法终止。失败步骤的 `break` 结束当前Program,返回外层Planner;它不表示整个任务立刻成功或无限死循环。剩余预算为硬限。 + +## 5. 固定422分母、回放和评分 + +原正式结果固定422来源/臂、844轨迹。已核实阶段按原SHA复用,其余来源只补一次;smoke不进正式分母,未终止/错误不删。原阶段墙钟分别记录,平均来源耗时不是整轮墙钟。标签只在停写后本地评分,不能进入模型消息、候选选择或训练奖励。 + +合法类别/等级/联合、Top5首次/最后/任次、固定12类与实际8支持类Macro-F1、配对改善/退化及真实调用/token/时间分别报告。聚合见 `results/evidence-summary.json`;`evaluation/metrics.py` 是指标实现。所有公开结果/轨迹本次字节不改,不把一次整理包装成重跑。 + +完整复现需原授权study/registry、顺序/分区、真实完整调用/trace、model与adapter、source/config manifest及本地参考。原始控制器逐字回放和token/EOS/adapter路由证明保存在受控证据中。公开1044轨迹只保留脱敏投影,无法独立重建原始消息和语义事实。 + +## 6. 当前公开入口的能力边界 + +`evaluate.py --cohort` 保留历史 `smoke`/`val80` 队列接口;全Val422结果由历史受控补充分阶段执行完成。公开树没有私有补充协调器,不能把空smoke/val80合成fixture说成422复现。完整实验说明不等于仓库含有未公开资产。 + +Teacher当前policy源码有显式证据校准变体,主干保留原文件。重新采集必须核当前policy版本;历史Teacher200是否逐字等同某次新采集不能仅凭文件名推断,要核原消息/trace和训练数据SHA。 + +原版保留已知限制:通用feedback只保存最近一次Program observation;部分失败专用账本单独保留。Planner仍可能在缺输入、no_match或坏输出后重复规划;静态计划最大长度与实际剩余Skill额度并非完全同一检查。原公开base231/422未合法终止,不能把原版称为已修预算bug。本次没有合入隔离recovery补丁、重训或改prompt追分。 + +Val422是已观察开发集,239 original/183 synthesized不等于专家Gold/全错,多个字段可能共享上下文;source级结果不是422个独立业务族的证据。标准映射出的等级不等于独立模型分级推理,合法引文也不自动证明语义充分。 diff --git a/research/finance_program_v1/docs/HISTORY.md b/research/finance_program_v1/docs/HISTORY.md new file mode 100644 index 0000000..f3c7709 --- /dev/null +++ b/research/finance_program_v1/docs/HISTORY.md @@ -0,0 +1,11 @@ +# 原版与历史快照 + +本次只整理金融 Program,起点:[b6fde9b80802593ad8ab30bdfae66fc28483a849](https://github.com/DocAILab/DataClassifyGrading/tree/b6fde9b80802593ad8ab30bdfae66fc28483a849/research/finance_program_v1)。 + +当前树移除 `nontraining/` 下的独立P14实现、历史runner/下载器/旧源码审计及其测试,只保留指向正式F66的README。文件级原gitblob/SHA见 [removed-historical-files.json](removed-historical-files.json)。可从原提交完整取回,结果和失败不因目录整理而消失。原版公开树的P14依赖测试中3项已因旧source-manifest与当前download_model源码散列不符而失败;这次未改旧manifest伪造通过,而是移除不属F66主干的历史检查,新增实际F66依赖/回放检查。 + +`evaluation/runtime`、Teacher、第一版SFT、结果/轨迹保留;活动源码只做注释和格式整理,并核AST一致。所有 `results/`、`trajectories/`、Skill body、注册表/合成数据、公开协议字符串保持原字节。保留legacy模型/哈希工具和teacher录制重试助手,因为它们仍被主干实际导入。 + +本地2026-11-09 recovery01/02/03及其61CPU、smoke8/部分VAL58,M8/M9/M10与Skill SFT不是这份原版主干结果,不迁入、不改旧分母、不与79→171表混成同协议。其他金融RL、汽车、教育、仓库应用不在本次变更范围。 + +整理不修原版反馈覆盖或重复规划行为,也不声称新的GPU结果。若未来改这些行为,需另建协议版本和原版对照,保存新失败与成本。 diff --git a/research/finance_program_v1/docs/curation-verification.json b/research/finance_program_v1/docs/curation-verification.json new file mode 100644 index 0000000..5452e03 --- /dev/null +++ b/research/finance_program_v1/docs/curation-verification.json @@ -0,0 +1,55 @@ +{ + "scope": "Original financial Program mainline only", + "source_commit": "b6fde9b80802593ad8ab30bdfae66fc28483a849", + "CPU_suites": [ + { + "suite": "teacher", + "actual_exit": 0, + "tests": 29, + "seconds": 1.1086134910583496, + "stdout_sha256": "2eb00240e726ab0fc4fb05245bfd0d3fa197259774a167badd73489b48dcc10b", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "suite": "sft", + "actual_exit": 0, + "tests": 25, + "seconds": 2.5363693237304688, + "stdout_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "stderr_sha256": "bb8f22f8624e2727e60a6f66416aa10d38d1a6b2723c97b0fde3fe67ab99dba3" + }, + { + "suite": "evaluation", + "actual_exit": 0, + "tests": 25, + "seconds": 0.46035313606262207, + "stdout_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "stderr_sha256": "9325ed57f4b9f01d13aef1062df45a27d88b0563705de55ba646468662e01f62" + }, + { + "suite": "evaluation/runtime", + "actual_exit": 0, + "tests": 8, + "seconds": 1.1792833805084229, + "stdout_sha256": "5654d79099bea70a56f845c7bc9232db296bce68cb36e9ee03e910f71594b695", + "stderr_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + { + "suite": "publication", + "actual_exit": 0, + "tests": 8, + "seconds": 1.7081363201141357, + "stdout_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "stderr_sha256": "0fd774540567f54f10069288a5f1e1bb82bb4f8c994b0d6e227a68cd4075ee94" + } + ], + "CPU_test_total": 95, + "retained_original_python_AST_checked": 92, + "AST_changed": [], + "results_trajectories_contracts_and_JSON_changed": [], + "broken_document_links": [], + "new_model_calls": 0, + "new_training": 0, + "baseline_note": "Original source: main four suites passed 87 CPU tests. Three of twelve old publication tests failed in historical P14 source-manifest binding; 5 P14 dependency checks removed with that historical snapshot, 1 fresh F66 dependency/budget check added. This is not a repair of the original budgeting behavior.", + "passed": true +} diff --git a/research/finance_program_v1/docs/removed-historical-files.json b/research/finance_program_v1/docs/removed-historical-files.json new file mode 100644 index 0000000..1d45d7b --- /dev/null +++ b/research/finance_program_v1/docs/removed-historical-files.json @@ -0,0 +1,641 @@ +{ + "source_commit": "b6fde9b80802593ad8ab30bdfae66fc28483a849", + "reason": "P14 standalone history is outside the matched F66 financial mainline; preserved in Git history", + "files": [ + { + "path": "research/finance_program_v1/nontraining/batch_audit.py", + "git_blob": "36902ae83a1dae89e2bb3295d03b8e414a6c94ab", + "sha256": "a8440f1e3d723dfb7d69af7819e8b7398e441d2a0b86d37e30f543b4e7f89dbf" + }, + { + "path": "research/finance_program_v1/nontraining/batch_runner.py", + "git_blob": "56856b2ff3790a45c60586ec4e6ab498892931e5", + "sha256": "10ed285b65779ce24b2d66584b01f81c285fd7ca4c705857b076d2d0b1d950d4" + }, + { + "path": "research/finance_program_v1/nontraining/download_model.py", + "git_blob": "f1183720f230347f9ab7521bea3d321e7b8ec6cf", + "sha256": "8b0e3d2fad6b72737daa9f8c7d29f7d74660e7e9334e3ff170e646ad815c0f3e" + }, + { + "path": "research/finance_program_v1/nontraining/local_smoke.py", + "git_blob": "3285fb1f41a4664bf5471b9b8985d5723abe76e9", + "sha256": "5bef9eba9ad014681600586a59e42f6c0e912187aebfd6a26ff886300e103876" + }, + { + "path": "research/finance_program_v1/nontraining/prepare_batch.py", + "git_blob": "45812bf0070af4c255755820a4009f1764c4c13b", + "sha256": "c9e7f7cdf291589f9463222ee5f4fabd09e772c0a21645a57a6f2ebaa3b6e34c" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/__init__.py", + "git_blob": "44a7fe39d9048eee9e29fc7edca9f8a5cf06aa37", + "sha256": "8ebc1b9a3937a1848c199126edf97e5862741ede120a491e87a8473d6c0f7c46" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/__main__.py", + "git_blob": "eb53e2f31b2f703ad32ef64b8a41faa3e7d18e08", + "sha256": "935a1c1166b0c1ea35a82256345000bf2c73ded718d77773bc27a71ecce28f7d" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/_vendor.py", + "git_blob": "6222f14c990d6424ae2fc4f7b972cc9959d5b035", + "sha256": "cfb187e38a0b8acd86e83476ee24f3aa02928c86fd3deb532f752ae8784bbf80" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/catalog_context.py", + "git_blob": "9fe8b2855406e97bf9d54e5e7e3117b9d4f62a74", + "sha256": "d59a7d3636fa7cb92ba5fff2126a9aee2b6a2166970b20ec4a834abdd3235409" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/cli.py", + "git_blob": "bf13728d254b3f049f5daebd795458f7a2a694c9", + "sha256": "82d3841baa287c2d5e0cf519ae2532a4fd5a4d79e89d907e29ad029c17d59335" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/contracts.py", + "git_blob": "b7d715cd54a1863c5b29b6e50479929d6143c69a", + "sha256": "884a776db1a44475943a5b08370bad9d6107cfcbe7f40380622515e85713cb51" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/controller.py", + "git_blob": "e854784a88de8bebba7b80d1b4433ba04a605d03", + "sha256": "1cfc63e72086d382e476443a098389570605d58cfa4a2cb0de5efd8fd8c37dfd" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/execution.py", + "git_blob": "5e8630489b7c0dc5a4fd889393d26ed44da6612a", + "sha256": "f9f61e8a3e62d827ff0ceccc57f1d08c27b63c017ca3f1506c2955433d5b5bea" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/planner.py", + "git_blob": "41f4f905946b295242b68048cdbb524b36997c7c", + "sha256": "966e630a9f3a66ddfe725a61c35e004a39a255f6e9209535c2f1b2ef9e5200f2" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/planning_contracts.py", + "git_blob": "68fd55f4e9c49c86d9cca56a319681a724b70cf7", + "sha256": "90d671bb998814249379db93c887ece2df70476d12a4e8bbc15dd6ccd78f6845" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/recovery_context.py", + "git_blob": "bbb0aa2aabb9594a960a6cce98591031528ca1fa", + "sha256": "a6660c91d3e77804146b12ce1b77fb0974977bb75fd98cf81c6225f02ae48013" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/rejection_context.py", + "git_blob": "a75322b032e411c26b4692ed9cb89a669fd2021e", + "sha256": "fd71ad424ff4a201b01f4db7276f2d958fd94eba7aaf26deb16cc54dbcb9de1f" + }, + { + "path": "research/finance_program_v1/nontraining/program_loop/validation.py", + "git_blob": "6fc4e49d0ea91ca1c46b4151582d2adb7194b8e5", + "sha256": "8ac6c4bfa272c60fb0149eab43b73c9b9b5e210859940eef316dfa00e4723e23" + }, + { + "path": "research/finance_program_v1/nontraining/reviews/__init__.py", + "git_blob": "e45a911031dbb1284c8840a89fbde3e041b829b3", + "sha256": "ad269634e577d94a5c8ba5df37e88e8614e08a424c848e5d256d97ea16ccd04a" + }, + { + "path": "research/finance_program_v1/nontraining/reviews/independent_audit_01.py", + "git_blob": "9afdf2f2c1a7132b39eafa8ef4a854a1c6f3b186", + "sha256": "d88449c928b14e62477256ed1f62da10a75c715754a61ee6f24d2341ab9e64eb" + }, + { + "path": "research/finance_program_v1/nontraining/reviews/source-manifest-01.json", + "git_blob": "83fac3dc5596b6aeaec32b37f6da0e6b8e7f9ba4", + "sha256": "055e2e89dba5e43be29782dd597f5867b4914ff8d9bd3875e51380981fd06935" + }, + { + "path": "research/finance_program_v1/nontraining/reviews/trusted-model-manifest-01.json", + "git_blob": "fac39da79ac263168f340ddeea7887e3ec2c58f8", + "sha256": "5b0a6b5e607d5305b2d59dd3e04bbd0f8b04af4502c389be3a5d83d01eddc8c9" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_9b_identity.py", + "git_blob": "2cee3ef5a7e790ebc9862315911c3c050af3e200", + "sha256": "d350a177fc710dadf08121abe09bd0b89e2a14785e203535ea611a1bff102b5c" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_dynamic_references.py", + "git_blob": "e63bca651ac6199434685ac501b6c2f004c0d5af", + "sha256": "588688f185f721c742e78f336ab5b42b7f7a695c87a0b8640208412372edc30e" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_local_smoke.py", + "git_blob": "06f820e02fd4451932bcc2780a473f4cf8802878", + "sha256": "dfdc361c3a7243c5ee78645d1d2d7bb449927633d061bfd76986fb081e6be601" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_planning_contracts.py", + "git_blob": "747eb7c13f9e82b46862089ee71d451163750eae", + "sha256": "992da01d882c51a288b298db790705589e0cf16f92e9ecd4e611746c96504560" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_program_loop.py", + "git_blob": "0c66c3d3e22eba74154399c6f88fdafca045e4de", + "sha256": "18d251a2781b0bc89e9ff50fe53afe364a9e7a35fb48f19f610af987582a14fd" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_recovery_context.py", + "git_blob": "36365070bb9c6b1c0b770fd5cce953a31605575e", + "sha256": "ba4e725f74a216831466b56f3b93616ca82dd36d0d77d690185f2e13d14de08e" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_rejection_context.py", + "git_blob": "3bf7cca78ff453810cd5e70c74358558524f4ba8", + "sha256": "48024ea991eceb98c0eb2cc9d292f9092ded253d995cbc4398b3a1dfed9bdce3" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_source_integrity.py", + "git_blob": "faab8a2c43f00d4da348922e37d3b68639f311df", + "sha256": "8141193bf6771e3c0a2bedbf5bb7999ba32bbaa6f74adc77fa1a18d941ea37ea" + }, + { + "path": "research/finance_program_v1/nontraining/tests/test_task_level_prompt.py", + "git_blob": "52bf4e4b0cf4a5908b58c0950614a0add8ce3fc6", + "sha256": "165fe55de77344c81d97de30eb532b7aadd326ce3f91a502025d5ab571ac4fc5" + }, + { + "path": "research/finance_program_v1/nontraining/tools/check_local_gpu.py", + "git_blob": "ccbf06f9cc58a1d952427d9227537d47791357c3", + "sha256": "4b28ea500f7573dedc1801a8b73c8ddaa4b26d8f87e9a6624682a3aa2d8ac7f3" + }, + { + "path": "research/finance_program_v1/nontraining/tools/verify_source.py", + "git_blob": "b6d8016149e1ec9a1a26e6d5f74575262a138dbf", + "sha256": "c1d14bc3f5641a725d9c8d0be05391215bf696d850f3adf7e1239fbec5f02294" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/common.py", + "git_blob": "16542c7889e1651e490c5467e7721884f43d87f2", + "sha256": "c79a02e987a169436796f438a415d7c309c0e0cf50bb447e493cd68cb9301fa4" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/pool_availability.py", + "git_blob": "74c15b85d16bbd3c3d76d39979b6f35c122ff7e7", + "sha256": "c6fa8e23a678b4451ef78d301efb347507fb0513a9d18bfda76eeefc824d70aa" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/pool_bindings.py", + "git_blob": "18359c0e086bb9d567069495383817ac6cf4ffa6", + "sha256": "3c0c65e78f7bcdc5bb81003b455fd957dba5c4abdbfdaa20b8fddb3b155e07db" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/pool_catalog.py", + "git_blob": "4fd6b2d1f271bd600311528895daf777944ba247", + "sha256": "bd19db2c908d41120498eae4afc26e30726b60ddf7fbf834e77ca6251e8c8a82" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/pool_metadata.py", + "git_blob": "a7bc2d9aec53d8ad336754cfcc5a10bbd31c5f49", + "sha256": "0705318048785fd34edd970274145dec359269e5e30756a996eb156e168e3a8a" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/pool_runtime.py", + "git_blob": "edc95559eef22aa7f1ff1b7c489037413db4181d", + "sha256": "506f2b605a32b0a1cf1431cdd4b92f5ccf821909d20726f8aacdd672ab0a893d" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/reference_skills_63.json", + "git_blob": "211165d7e680f34637741f74f0ceb5aef9d91b3c", + "sha256": "a63b6ee85f983caf9f55d537fe85d24a283a860ccb0985c8a7fce8b1466e3caf" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/__init__.py", + "git_blob": "a06fbeb46d8c95cba0d302be72b06014512a17e7", + "sha256": "c2ee5b379bec6f6381e0651bee6078e38ad6ca294f497d40b6d27e583fd1492e" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/__init__.py", + "git_blob": "8157f3d3aa4944f07ff3f7ec8c07a5ca8d6ad925", + "sha256": "64f470fa2d85450ebbd8819a66c63064bcdbf993c829d248c64315285e7aca73" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/agent_loop.py", + "git_blob": "026352426fa7f0c339f63e621bddf475a3ad773f", + "sha256": "176bc72eebd17a7d2e45276654c49cbd5b1828306e11d2579faffe143eebcade" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/artifact_projection.py", + "git_blob": "e2b125051fec30049135ccbf3b22444df2f51555", + "sha256": "d71939b3e4b04b83d33f7aedbc3173cd44043b8a55d44c149c46f35d5aa3f7d8" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/catalog.py", + "git_blob": "da77ce43f98517efddab8706f88ba5f10fd61d09", + "sha256": "66ceb63dd02030cecb3965247a671da64c4d29724ece9a5eb52961a0647c8e6a" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/category_catalog.py", + "git_blob": "9696dd40655c0cebda965f2d03bf34063c48bb00", + "sha256": "baf7b0b234822060b48dded26f00d526654749f1384c3e23f9eb07ddc8fa0a58" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/contracts.py", + "git_blob": "d7634aeffd00bef814721b933034731ed9d1d1fd", + "sha256": "19ed69938bdc517be14625e0ef886945dc4483faeb6a8260fdfcacaffa83f233" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metadata_lookup.py", + "git_blob": "7de1ab437f4823a02bc815f313519b09c1cf60d2", + "sha256": "e338e0d804caa20218637074422b08f26b16fdbdd9faff39077a1cb73beb89fc" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metrics.py", + "git_blob": "d3ba05bbeb3b860864802754461c0f013ec6b960", + "sha256": "fffb69bd3e8efa149e46e3413b4056457840b9cd8f6798fd5e0871cdb7e3a0b3" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/model_skill_executor.py", + "git_blob": "8df1c1d3d65407a4650e091a7b4d7835f8377038", + "sha256": "03a90c6c58ffad2dddc9fa5c8982045eb2a73a804f521c2c679f61e14e17f3b0" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/planner.py", + "git_blob": "9987d1de6758d1ba7c430069310864b574a46f47", + "sha256": "5be67a873f8fa54c183c9fa381def425b73cc92181fab6079506eb2296fa53d8" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/retrieval.py", + "git_blob": "df3e67872c5215049647afc760a9d24b4c4e3419", + "sha256": "fbe140936695f38c6bc6838c5a9a0100ca9e6f98b6e77984e587fdbea28b6bf4" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/runtime.py", + "git_blob": "e90f1209dc15d92d9ac7bac0528afe9af626efdd", + "sha256": "887e82115154f043801719b5e292895e3eeef0d25e277748805a0c1dabc39acc" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/skill_loader.py", + "git_blob": "cb43a6a27dbbb0749b16ca4f6405e34eba624081", + "sha256": "7528bada337e98b69ef61ccf558574f5940d26fcfc2106530f8c9d0d765964f6" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/table_field_lookup.py", + "git_blob": "29350867ceba5f292855fc1f72d602a96da309ea", + "sha256": "93319c4ee044439f9e25449cec220dfaededa1c6b799816486d19402b569dc22" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/topk_selection.py", + "git_blob": "0a9891970019bab0f6b60aa10e1466eee7c1cb32", + "sha256": "a58411d1acb421bd5e5c134f4ceef7ccce76851f684a397446904b7a17b1eb4c" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/validator.py", + "git_blob": "8c30690e0560b008f53f4ba4cf5b1d208c6b663a", + "sha256": "15fd2b9faca5addf49f4fdf5d816eb2ecb3723c6b800da3fd591cda93b0bedcd" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/__init__.py", + "git_blob": "09f258a62a62517806bf9aed9f9573ee91a1e948", + "sha256": "7c61249a27a9c7ad011f983e9857e3889ae54837d00faf2660fe2f72350b30d6" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/run_agent_loop_batch.py", + "git_blob": "c8c6963e462345e0ff5e2449d54554df0354eed3", + "sha256": "6605815bf479e8fc50a3041af3c2430b3f121740bf38b8e6d497212d4425616d" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_ASSESS_CATEGORY_SUPPORT.md", + "git_blob": "06244148eb3509652f2a92f96abed60bed221056", + "sha256": "85ea64633013f69d582707acf4ab1b32201cf5ebbf7e0356041119d6c08c106a" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_CHECK_EVIDENCE_SUFFICIENCY.md", + "git_blob": "cb91800959e91ee85ff9b7aee1c3013435719e30", + "sha256": "f879c21470b9daeb773a80a256a07f7a6f43e38e8452347f128eca6391362f4a" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_COMPARE_CATEGORY_HYPOTHESES.md", + "git_blob": "b69eaafd74f2ae953ce7ae0e2c4b7a045f864a1f", + "sha256": "3fa31691df6bb353b4171a8c837da229549f8f4eff827bf502f81cb2318432a5" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_DECIDE_NEXT_EVIDENCE_SOURCE.md", + "git_blob": "92d385f0d33d95c3b4cd91242704ab0659cc6d65", + "sha256": "647a447ae584d92e67c17d2d7040ff48d14cb8d2b5039345d65eb072b5c14fd3" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FINALIZE_CLASSIFICATION.md", + "git_blob": "5e49b985869558b60b5a505a8332afe80cafa858", + "sha256": "cd66513c1ca4b6728bd217ae57a7ad7cd96257f61443a7af2ac1edd7e746f937" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_CONTEXT_EVIDENCE.md", + "git_blob": "bd49f0358db240c97dfd421fd85932a07deed9cb", + "sha256": "b0028a313fa3f81350f07093c5389c7ec0447539119e37930f1f05bceec539d1" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_DATABASE_EVIDENCE.md", + "git_blob": "9546a0b05c8259c96d3cb699b6996631ef36371a", + "sha256": "e27e9b2f57b5b1929d5286a10cc15233ab48ba40948fe520fde8853f66bc1e56" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_FIELD_EVIDENCE.md", + "git_blob": "97908d1aff91e162d2ab74a2147781d81bf4a043", + "sha256": "6dfef164297cb75a02f64ebbdafecb3f0519f1a5f1992c3bb9a98157b7a7ee54" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_METADATA_EVIDENCE.md", + "git_blob": "f17c5480f0ebb4d4a1c9c12b72c62137b2245abd", + "sha256": "e3a7e0de334bc39836c3a909edc79233075b0b73f7c30e879d4e087bc94aa6f2" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_STANDARD_EVIDENCE.md", + "git_blob": "4f74a10262fbb47497172b9e5fd6754b6a672ff6", + "sha256": "eddac25de1c3dda0baf876d29a7a32ae4fab980f2ae7ce892def82af3469087a" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_TABLE_EVIDENCE.md", + "git_blob": "9cb0a5f7e746fc3fa4b4d7ff1a5b8bc32426e0a0", + "sha256": "24c7eb0ea3381b640465e78e41eb2ff43495e7bb3eadcc652e5587c3bd167ab4" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_IDENTIFY_MISSING_EVIDENCE.md", + "git_blob": "b36a14cb2fb268b21ef1d860b4cc07f3b3db69ee", + "sha256": "237695b8b5d6f9a7105902dc32a120297c364ee5f8d1c27f4ead212df110668f" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY.md", + "git_blob": "265b235d02eb024a77d9333f30021d742f127c74", + "sha256": "032b758517d3a8535c29d20d8391bd8d27a2ad1d5c7e9f62246578076ddb5197" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY_FROM_TOPK.md", + "git_blob": "96a115599af1b29d410edd79241876854baa4e32", + "sha256": "7af18e11373d633fe4369338336c653b47238c214cb5f1937e0a5b30041f722f" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_GRADING_LEVEL.md", + "git_blob": "0f61b63032a95d5580f039aed198463963b00b87", + "sha256": "276b5e1a8b080d9aecec762762939372f40e56c8fb4b1eb92964c53073b6d603" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_FIELD_CONTEXT_CONFLICT.md", + "git_blob": "746a767b3f9961c0eb7087294ec2b3d123a7348c", + "sha256": "94e552edccadc03cb55a5ab8e54511a296971363bd4aafb30b3ab1385e5a18f3" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_METADATA_CONFLICT.md", + "git_blob": "3593ec1399de32df0fa1a23c8db0625ae93ec127", + "sha256": "643472dc5b7e7cdb38f3483857acc94d539884efede9b9ed0f4cccc79a037d0b" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_STANDARD_CONFLICT.md", + "git_blob": "54927962cee880dc386d0729c53ce43afac53e54", + "sha256": "be9b9c9c879b964acf4b5f7317dcf90c68833a1f98f6cb8ab9f8199460066b25" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CATEGORY_WITH_STANDARD.md", + "git_blob": "de3852fde506013f6e31dcd0de2bc6620f8ce12d", + "sha256": "deb07baab54b052a9323b475c912d7743115c96dd4b1dd0b7c4a80df3e3d0dfc" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CLASSIFICATION_GRADING_CONSISTENCY.md", + "git_blob": "482763bc68f1d201040481d6e4270ff5f5ff9a7f", + "sha256": "ff8ef17c1ce1408496c6634389ecba87f6d282d0264e4ac1ee9a8c2deb12bab1" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_WEIGH_EVIDENCE.md", + "git_blob": "c9649caa84f6b759f77b15395dfc54e3266cecdb", + "sha256": "c928a03a7a8f2d8b1a28ffb01c100543000a62e4a388a0e60051a4b6815dd43f" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_ACQUIRE_MISSING_METADATA.md", + "git_blob": "a8256f1ad77417528ddaa9ec4ca435e8e40ee008", + "sha256": "cc788f17f7c63e1f7974f220eca3becfb186d3df287a35d814a5387964d20ce3" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_CHECK_METADATA_AVAILABILITY.md", + "git_blob": "99385a6f4858b01ed4ea405c4906031d9c1aa50c", + "sha256": "fe27b6f518a98be4e88414d6180180954572f222fec37dfc4591e2b72a05ad5a" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_EXPAND_SELECTED_CONTEXT.md", + "git_blob": "d6d910518df6838d61cc8809e70a4e53e1d7b3ed", + "sha256": "323b136804a9db277d6642b71de277ae3fcd7021910645475872b1b018d79a79" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_DATABASE_CONTEXT.md", + "git_blob": "c1190482159fff30b6cdefb0eb44d1802e121b2b", + "sha256": "0008e4dc6b220757208cb656912ebb609c8230aaf62ce56a33f247dc5879f7cd" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_TABLE_CONTEXT.md", + "git_blob": "0838b6e0d6ae1e9c92a7f312364f239e197cbd2c", + "sha256": "09b1f136ca45244c603e98aba0bec6fad8997ca2e618eeaeaf7ac1c1de4fb711" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_DESCRIPTIONS.md", + "git_blob": "c6afadf5de6e5452909f7c1c999659a7644810ec", + "sha256": "0b5f7d9ced8902a3a7157d6781a3b3d6bc9fb9f2d2c55da99f31977ceb5609b8" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_TYPES.md", + "git_blob": "1515c037a70cc54dc39a3cbddcf1a5aaf2b25260", + "sha256": "61cfe7efeb0980d22e72c4069e70cb91d1a007c7352b528b600b7efbcfd313e5" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_VALUES.md", + "git_blob": "3566bb5236124e0b470a02ae9f02d6143fd73a43", + "sha256": "780305d46253a0ab132f35feee6ba420347f351326827c4be781bd4224349504" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_DATABASE_DESCRIPTION.md", + "git_blob": "a39482956299b781dde5d5c92356afe78930bd0f", + "sha256": "37b2146b9cd669e1dc0cb0a54c0f6ee36dc0157ce1e4e753d96be08a6fdada21" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_DESCRIPTION.md", + "git_blob": "2015e2c65512c00d12228828dcf30dbe985f2111", + "sha256": "d545962070cb10fa90ee1693261d48ee08df616cad4d098bfcd98643100fce7b" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_METADATA.md", + "git_blob": "f8504a3598191f48d7ff1809d20770d16031aa18", + "sha256": "372ce861fcca6138cda43b693a8fc32f85c0ec380b0c275c3cfe613dbe25f629" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_DESCRIPTION.md", + "git_blob": "2bf068980530891c4d235ca5b4885eb4cff1f6a5", + "sha256": "912334b76f95c6f468cf4bab840ae0ec3a262639c59e545db63bfce866710ea0" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_FIELDS.md", + "git_blob": "c1779ba7a91ca38938d97d851350079059a7553d", + "sha256": "99c01c5869b511754feccfd335017c7f4290683fbcc46ed6355b95f775d605b0" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_SELECT_CONTEXT_FIELDS.md", + "git_blob": "ca0decc7d3ccc4e766efde0f46806a3e35f2e870", + "sha256": "aacb11c41507d2c2743e56a7915c9dae9d6b4e2ff3ece6fec6b3d73babeb6683" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_DISAMBIGUATE_FIELD_SEMANTICS.md", + "git_blob": "1fc67c7ad68bd31d0cf66ba6800197b4927e9c9e", + "sha256": "e497bddaf99da95503677a969926921b507b92ad542055dafaa88ee724a235d0" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_DATABASE_ABBREVIATION.md", + "git_blob": "76258c8533023973cb0daa0f8e598cde4d022b41", + "sha256": "2338078f06cd5276b326747fa0b80790d3c638ba369f6579e4ddcff84882eb51" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_FIELD_ABBREVIATION.md", + "git_blob": "d6a7524483d0230171374c4f8ebc4da5f05a455b", + "sha256": "6b84b95768e4cc77d193b31871f3b75ab17ff86f526c4000bccd6f8c423cb2a7" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_TABLE_ABBREVIATION.md", + "git_blob": "1340fa2b42774fe6685fb158604592dd237073e9", + "sha256": "6ce033822d4d4f4ae7babba7bd0b44fa871476353b81fd86ac6742d266b3a426" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_CONTEXT_FIELDS.md", + "git_blob": "c5a536ab79bcacc615e0bb25f8b7f0033942f69f", + "sha256": "297bf09515bbbc0a4b9e6f80fb77c7135b7484c5c428da0868d7a0d0732717cb" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_DESCRIPTION.md", + "git_blob": "46c8b95b8ea8a34a3730b97d970f09fe2870f389", + "sha256": "acc57509cff6330476522f8fc5a7b286b0ede3e477c9806000b54542f89070dc" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_NAME.md", + "git_blob": "a1fdeb0a8e6b36256513e4cd50321ae6c4bb2a18", + "sha256": "e427e888ac10d742784d390ad2bdce40d0aec7c9a7abd52b5f5497fc83b866fc" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DOMAIN.md", + "git_blob": "23b3e93b15ec1ef985704a32d61e173f20c038dc", + "sha256": "6e1760ff387797cb4c171f404f744b6b6b87445969659bf8b37c8bca66de5375" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_DESCRIPTION.md", + "git_blob": "5809752abf2247fc86677d2b9d11037018407cb5", + "sha256": "a833b94c6c7afd5e740d67674662178e9b2f9cef6e0019dd9af8bbf62b324335" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_NAME.md", + "git_blob": "fd91c53ce05d5232ee57220c281e1ae5f641a605", + "sha256": "99934fabad8007d155624a475b1600b5b8139152efde2a9154cd7035e42ba56e" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_TYPE.md", + "git_blob": "f7faeb407d358407caee86ff5821445b9188ace4", + "sha256": "93500ee995113eed8ee9d6d8887d6f65f2d4aa6ac52b12697fb8e82982c1b49d" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_VALUE.md", + "git_blob": "8fd47479355c1f4b63aef8c8da099364c5be8bb9", + "sha256": "c0dad806fde006487b38b9d56fc0b5fde6cc2e367b8a46d13adb5c4171ed19ad" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_DESCRIPTION.md", + "git_blob": "31d9fd8f60f246e3f8b6b6beff2b313921a5cd0d", + "sha256": "901cef9276dd30ff1b2e35fb39bbe9138cf42bb4ded47b37fb3afe83c1945ac2" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_NAME.md", + "git_blob": "799e31b92c1c6516783210d5fe4accfbacb5cd50", + "sha256": "bfd2506982a98615fa40d2a2760893f7634a270a663f65a84547e4a2ec7a4186" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_SYNTHESIZE_METADATA_SEMANTICS.md", + "git_blob": "18c218cb9b4b4547d75a0e18446db496b8a8b327", + "sha256": "4d64debe0b8657d6c0960eb5e3eebad7aa5125e34e35f66deb38c050f665ec26" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_CONTEXT_TO_STANDARD.md", + "git_blob": "dc5dae5b7b31f7018bd2f169c25ea2034e36ec4e", + "sha256": "debf2fb145c10526e4952ba7cb322d8a88370ae136d1ae6f0b74b7b9d60734b0" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DATABASE_TO_STANDARD.md", + "git_blob": "c303142a4bad1eb113302694dcb6e0cf2e5da7af", + "sha256": "5bdb03e45720da5ff53297fae7ce476e6fd46f3af6277e8be147a87033917630" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DESCRIPTION_TO_STANDARD.md", + "git_blob": "cda05f1a7d916b347c1552eb1f5cd382ffa7bc58", + "sha256": "ec00677a4433b6110f529eafc28d5c0272746f186121ee563ab86eb8a3a9a6ec" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_FIELD_TO_STANDARD.md", + "git_blob": "0dde182941ec01971aa65a8b83564c4af02019ae", + "sha256": "19c1e2c28c4df124d9ef56501635c31443552cc3d103d727b927db78891eb53f" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_TABLE_TO_STANDARD.md", + "git_blob": "f20ed54d042a31fd0432e5ca5dd7654b7a4ac197", + "sha256": "7fa123b49aca5ec7f2525d3697e0108aaf3d85f61c966eb9492a19b657e2a300" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_VALUE_TO_STANDARD.md", + "git_blob": "43a354f874f735b9546fe1d55df67ba3952fa5b8", + "sha256": "d71db5f6adcf269897e8c9b662cc31edc18b7a7727db7a241624e319a390588e" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_COMPARE_STANDARD_CANDIDATES.md", + "git_blob": "1654fc55d693178807c4b7007db66aac56be0494", + "sha256": "d5e82a8d994155a010de18c15a1923a432e2e039a0aa3016bc1a7689cdfe9fdb" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_REFINE_STANDARD_QUERY.md", + "git_blob": "29433fb80a1f610c7b1ac371862aff51a541e11a", + "sha256": "51c1ead62e9d83c194ac1fc24c8f43b9879497477b79054e03384b6ded980420" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_RESEARCH_STANDARD.md", + "git_blob": "421cda4d2874720ff2345e0e7e44a3a9fbd57237", + "sha256": "05ccd5f271a060ed497242c494c34d8ce3cac22f03e6349d0d6edfe0a4b303ac" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD.md", + "git_blob": "79a5d12208a3e87ffa74bafba1f5e967720d14e9", + "sha256": "dcbd3841440dc7bf0ee22c02b9ba1014fff1fa6a68900f270bb8cbb40aa9074c" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_CONTEXT.md", + "git_blob": "20055dfd8e64b1e86a5ab2c28f456e7af929f7a5", + "sha256": "6c1c9ad8fd7036ddf2504e30bc4f920d9754c8c3de68f2ff5263f760630d839e" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_DATABASE.md", + "git_blob": "97b3bffcb5b776be28a24c8d32b8ea9678e35384", + "sha256": "fc38fe4bccc6637de6abe3b8434f7d069d42b6eabf1a8dc29b98cfcdd443a362" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_FIELD.md", + "git_blob": "5af62e3d0613278203710eef7c39cbdbc177ae26", + "sha256": "98862fb615e97f189420455219b484ef990e0f4768f7ba4e49983e237d3998f2" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_TABLE.md", + "git_blob": "2ffdd2492743f5f6a984a58007ccb430da942bc1", + "sha256": "ae067ae1570ad6e24e5c43a08aa4057223923b45e2593525255419144847ebd0" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SELECT_CATEGORY_TOPK.md", + "git_blob": "99684b013db233541e11ba1228c15a7eae919a6d", + "sha256": "c0dac66df87884c2ecd0e6dbfe2af1027b522a1653972ffa4d79e8a957a9bb74" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SUMMARIZE_STANDARD_EVIDENCE.md", + "git_blob": "331807563e54da13cb4ccda8b5dace9c99a20ab5", + "sha256": "ea3ee35fa9ddde244353f533a527bf25674ffb711218f74c8960862183bd664b" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/skill_reference.json", + "git_blob": "dac74e8222bc584be311b4b7029cc6958f147b62", + "sha256": "752ed72d4ed6e987542197dfff40786ebd4487bcf6b1042cbf769d1fed2392b8" + }, + { + "path": "research/finance_program_v1/nontraining/vendor/study.py", + "git_blob": "82d329c0c0e7fc20c99adf426f1e8e5f8691f520", + "sha256": "d8c78d387e00b13762fb509d23e147210b0016931879c4af7089c593d6eddbb3" + } + ] +} diff --git a/research/finance_program_v1/evaluation/README.md b/research/finance_program_v1/evaluation/README.md new file mode 100644 index 0000000..61c4bff --- /dev/null +++ b/research/finance_program_v1/evaluation/README.md @@ -0,0 +1,9 @@ +# F66同框架配对评估 + +`runtime/`是金融主干唯一Program/Skill实现。`evaluate.py`对同一来源交替AB/BA;`backend.py`保证base组所有请求关闭adapter,sft组只有可信Planner system请求开启adapter,结束/异常均恢复关闭。Skill两组都用原基座。`replay.py`拒绝实际请求和记录序列不一致;`gate.py`核模型、adapter和真实阶段退出;`metrics.py`保留固定分母。 + +原版预算与生成参数见 [完整协议](../docs/EXPERIMENT_PROTOCOL.md)。原先P14目录不再作为nontraining入口。不要直接用ProgramConfig通用默认值代替正式study预算,也不要省略 `skill_pool="F66"` 后声称相同实验。 + +当前runner保留原 `smoke` / `val80` 参数,公开study只是合成fixture;原完整422结果在 `../results`,私有的补充运行协调器未在此发布。真实运行需自己的受控manifest,源码整理后SHA变化必须重新绑定;不能重写旧审计身份。 + +CPU检查:在此目录 `python -B -m unittest discover -s tests -v`;另在 `runtime/` 运行 `python -B -m pytest tests -q -p no:cacheprovider`。这些检查没有模型下载、API、GPU或新成绩。 diff --git a/research/finance_program_v1/evaluation/archive.py b/research/finance_program_v1/evaluation/archive.py index c6c1ea6..33b74a1 100644 --- a/research/finance_program_v1/evaluation/archive.py +++ b/research/finance_program_v1/evaluation/archive.py @@ -1,22 +1,44 @@ """After writer exit, snapshot all frozen code, logs, inputs, calls, routes and traces.""" + # 运行结束后封存代码、输入、调用、路由与轨迹,成员清单用于核对档案内容及字节身份。 import tarfile -from io_utils import ROOT,verify,put,read,sha +from io_utils import ROOT, verify, put, read, sha def main(): - verify();read(ROOT/'runs/exit.json') - out=ROOT/'exports/final-01';out.mkdir(parents=True,exist_ok=False) - files=sorted(p for p in ROOT.rglob('*') if p.is_file() and '__pycache__' not in p.parts - and 'exports' not in p.relative_to(ROOT).parts and p.relative_to(ROOT).as_posix()!='runs/watch.log') - entries=[{'path':p.relative_to(ROOT).as_posix(),'sha256':sha(p),'bytes':p.stat().st_size} for p in files] - put(out/'members.json',entries) - archive=out/'student-val80-evidence.tar.gz' - with archive.open('xb') as stream,tarfile.open(fileobj=stream,mode='w:gz') as tar: - for p in files:tar.add(p,arcname=p.relative_to(ROOT).as_posix(),recursive=False) - tar.add(out/'members.json',arcname='archive-members.json',recursive=False) - put(out/'archive.json',{'archive_sha256':sha(archive),'bytes':archive.stat().st_size, - 'members':len(entries)+1,'members_sha256':sha(out/'members.json'),'exit':read(ROOT/'runs/exit.json')}) + verify() + read(ROOT / "runs/exit.json") + out = ROOT / "exports/final-01" + out.mkdir(parents=True, exist_ok=False) + files = sorted( + p + for p in ROOT.rglob("*") + if p.is_file() + and "__pycache__" not in p.parts + and "exports" not in p.relative_to(ROOT).parts + and p.relative_to(ROOT).as_posix() != "runs/watch.log" + ) + entries = [ + {"path": p.relative_to(ROOT).as_posix(), "sha256": sha(p), "bytes": p.stat().st_size} + for p in files + ] + put(out / "members.json", entries) + archive = out / "student-val80-evidence.tar.gz" + with archive.open("xb") as stream, tarfile.open(fileobj=stream, mode="w:gz") as tar: + for p in files: + tar.add(p, arcname=p.relative_to(ROOT).as_posix(), recursive=False) + tar.add(out / "members.json", arcname="archive-members.json", recursive=False) + put( + out / "archive.json", + { + "archive_sha256": sha(archive), + "bytes": archive.stat().st_size, + "members": len(entries) + 1, + "members_sha256": sha(out / "members.json"), + "exit": read(ROOT / "runs/exit.json"), + }, + ) -if __name__=='__main__':main() +if __name__ == "__main__": + main() diff --git a/research/finance_program_v1/evaluation/backend.py b/research/finance_program_v1/evaluation/backend.py index c7e1bd6..50d270b 100644 --- a/research/finance_program_v1/evaluation/backend.py +++ b/research/finance_program_v1/evaluation/backend.py @@ -1,81 +1,147 @@ +# 路由不依靠自由文本猜角色:用可信system精确识别Planner。 +# sft只开Planner LoRA;Skill/base始终关;finally恢复关闭并保存实际层状态。 """Full-context frozen local generation with measured Planner-only LoRA routing.""" # 两组条件复用相同基座和生成配置,只有 sft 的 Planner 请求启用 LoRA;实际层状态另存路由证据。 from copy import deepcopy from pathlib import Path import time from io_utils import ROOT, read, put, sha -from gate import enabled_for,eos_options,validate_adapter_files -from local_smoke import Backend,encode_messages,generation_metadata +from gate import enabled_for, eos_options, validate_adapter_files +from local_smoke import Backend, encode_messages, generation_metadata -def layer_state(model,disabled): - layers=[m for _,m in model.named_modules() if hasattr(m,'lora_A') and hasattr(m,'disable_adapters')] - if len(layers)!=40 or any(bool(m.disable_adapters)!=disabled or list(m.active_adapters)!=['default'] for m in layers): - raise RuntimeError('actual LoRA layer state differs from requested route') - return {'layer_count':len(layers),'disabled':disabled} +def layer_state(model, disabled): + layers = [ + m + for _, m in model.named_modules() + if hasattr(m, "lora_A") and hasattr(m, "disable_adapters") + ] + if len(layers) != 40 or any( + bool(m.disable_adapters) != disabled or list(m.active_adapters) != ["default"] + for m in layers + ): + raise RuntimeError("actual LoRA layer state differs from requested route") + return {"layer_count": len(layers), "disabled": disabled} class RoutedBackend(Backend): - def __init__(self,model,adapter,anchor,cohort): - if read(Path(model)/'model-manifest.json')!=read(ROOT/'model-identity.json'): - raise ValueError('base model manifest differs from frozen original identity') - validate_adapter_files(adapter,anchor) - super().__init__(model,ROOT/'runs'/(cohort+'-backend-init')) + def __init__(self, model, adapter, anchor, cohort): + if read(Path(model) / "model-manifest.json") != read(ROOT / "model-identity.json"): + raise ValueError("base model manifest differs from frozen original identity") + validate_adapter_files(adapter, anchor) + super().__init__(model, ROOT / "runs" / (cohort + "-backend-init")) from peft import PeftModel - validate_adapter_files(adapter,anchor) - self.model=PeftModel.from_pretrained(self.model,adapter,is_trainable=False,autocast_adapter_dtype=False) - validate_adapter_files(adapter,anchor) - self.model.to(dtype=self.torch.float16);self.model.requires_grad_(False);self.model.eval() - self.parameter_devices=sorted({str(p.device) for p in self.model.parameters()}) - self.parameter_dtypes=sorted({str(p.dtype) for p in self.model.parameters() if p.is_floating_point()}) - if self.parameter_devices!=['cuda:0'] or self.parameter_dtypes!=['torch.float16']: - raise RuntimeError('entire model and adapter must be FP16 cuda:0') - self.options['eos_token_id']=eos_options(self.model.generation_config.eos_token_id,self.tokenizer.eos_token_id) - if self.options['eos_token_id']!=[248044,248046]:raise ValueError('model/tokenizer EOS identity differs') - self.system=read(ROOT/'data/protocol.json')['planner_system'];self.anchor=anchor - self.model.base_model.disable_adapter_layers();layer_state(self.model,True) - put(ROOT/'runs'/(cohort+'-backend-loaded.json'),{'adapter':str(adapter),'adapter_sha256':anchor['adapter_sha256'], - 'base_revision':self.identity['revision'],'parameter_devices':self.parameter_devices, - 'parameter_dtypes':self.parameter_dtypes,'generation':self.options,'targets':40}) - def start_source(self,folder,arm): - self.arm=arm;self.call_dir=Path(folder)/'calls';self.call_dir.mkdir(parents=True,exist_ok=False) - self.calls=[];self.failures=[] + validate_adapter_files(adapter, anchor) + self.model = PeftModel.from_pretrained( + self.model, adapter, is_trainable=False, autocast_adapter_dtype=False + ) + validate_adapter_files(adapter, anchor) + self.model.to(dtype=self.torch.float16) + self.model.requires_grad_(False) + self.model.eval() + self.parameter_devices = sorted({str(p.device) for p in self.model.parameters()}) + self.parameter_dtypes = sorted( + {str(p.dtype) for p in self.model.parameters() if p.is_floating_point()} + ) + if self.parameter_devices != ["cuda:0"] or self.parameter_dtypes != ["torch.float16"]: + raise RuntimeError("entire model and adapter must be FP16 cuda:0") + self.options["eos_token_id"] = eos_options( + self.model.generation_config.eos_token_id, self.tokenizer.eos_token_id + ) + if self.options["eos_token_id"] != [248044, 248046]: + raise ValueError("model/tokenizer EOS identity differs") + self.system = read(ROOT / "data/protocol.json")["planner_system"] + self.anchor = anchor + self.model.base_model.disable_adapter_layers() + layer_state(self.model, True) + put( + ROOT / "runs" / (cohort + "-backend-loaded.json"), + { + "adapter": str(adapter), + "adapter_sha256": anchor["adapter_sha256"], + "base_revision": self.identity["revision"], + "parameter_devices": self.parameter_devices, + "parameter_dtypes": self.parameter_dtypes, + "generation": self.options, + "targets": 40, + }, + ) - def generate(self,messages): - enabled=enabled_for(self.arm,messages,self.system) - call=self.call_dir/('call-%04d'%(len(self.calls)+1));call.mkdir();self.calls.append(str(call)) - self.last_generation_metadata={};started=time.perf_counter() - q={'messages':deepcopy(messages),'generation':self.options};put(call/'request.json',q) - x={'messages':deepcopy(messages),'raw_text':None,'input_tokens':None,'output_tokens':None, - 'generated_ids':[],'input_devices':[],'parameter_devices':self.parameter_devices, - 'parameter_dtypes':self.parameter_dtypes,'generation':self.options,'truncation_at_budget':False,'error':None} - route={'arm':self.arm,'enabled':enabled,'layer_count':40,'entered_disabled':None,'restored_disabled':None, - 'adapter_sha256':self.anchor['adapter_sha256']} + def start_source(self, folder, arm): + self.arm = arm + self.call_dir = Path(folder) / "calls" + self.call_dir.mkdir(parents=True, exist_ok=False) + self.calls = [] + self.failures = [] + + def generate(self, messages): + enabled = enabled_for(self.arm, messages, self.system) + call = self.call_dir / ("call-%04d" % (len(self.calls) + 1)) + call.mkdir() + self.calls.append(str(call)) + self.last_generation_metadata = {} + started = time.perf_counter() + q = {"messages": deepcopy(messages), "generation": self.options} + put(call / "request.json", q) + x = { + "messages": deepcopy(messages), + "raw_text": None, + "input_tokens": None, + "output_tokens": None, + "generated_ids": [], + "input_devices": [], + "parameter_devices": self.parameter_devices, + "parameter_dtypes": self.parameter_dtypes, + "generation": self.options, + "truncation_at_budget": False, + "error": None, + } + route = { + "arm": self.arm, + "enabled": enabled, + "layer_count": 40, + "entered_disabled": None, + "restored_disabled": None, + "adapter_sha256": self.anchor["adapter_sha256"], + } try: - if enabled:self.model.base_model.enable_adapter_layers() - else:self.model.base_model.disable_adapter_layers() + if enabled: + self.model.base_model.enable_adapter_layers() + else: + self.model.base_model.disable_adapter_layers() try: - state=layer_state(self.model,not enabled);route['entered_disabled']=state['disabled'] - encoded=encode_messages(self.tokenizer,messages) - x['input_tokens']=encoded['input_ids'].shape[1] - encoded={k:v.to('cuda:0') for k,v in encoded.items()};x['input_devices']=['cuda:0'] + state = layer_state(self.model, not enabled) + route["entered_disabled"] = state["disabled"] + encoded = encode_messages(self.tokenizer, messages) + x["input_tokens"] = encoded["input_ids"].shape[1] + encoded = {k: v.to("cuda:0") for k, v in encoded.items()} + x["input_devices"] = ["cuda:0"] self.torch.cuda.synchronize(0) - with self.torch.inference_mode():output=self.model.generate(**encoded,**self.options) + with self.torch.inference_mode(): + output = self.model.generate(**encoded, **self.options) self.torch.cuda.synchronize(0) - ids=output[0,x['input_tokens']:].tolist();x['generated_ids']=ids;x['output_tokens']=len(ids) - x['truncation_at_budget']=len(ids)>=512 - x['raw_text']=self.tokenizer.decode(ids,skip_special_tokens=True,clean_up_tokenization_spaces=False) - return x['raw_text'] + ids = output[0, x["input_tokens"] :].tolist() + x["generated_ids"] = ids + x["output_tokens"] = len(ids) + x["truncation_at_budget"] = len(ids) >= 512 + x["raw_text"] = self.tokenizer.decode( + ids, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + return x["raw_text"] finally: self.model.base_model.disable_adapter_layers() except Exception as exc: - x['error']=type(exc).__name__+': '+str(exc);self.failures.append(x['error']);raise + x["error"] = type(exc).__name__ + ": " + str(exc) + self.failures.append(x["error"]) + raise finally: # 无论生成成功或抛错,都核验适配器已关闭,避免影响后续 Skill 或 base 调用。 - route['restored_disabled']=layer_state(self.model,True)['disabled'] - x['seconds']=time.perf_counter()-started - self.last_generation_metadata=generation_metadata(x) - put(call/'result.json',x) - route.update(request_sha256=sha(call/'request.json'),result_sha256=sha(call/'result.json')) - put(call/'route.json',route) + route["restored_disabled"] = layer_state(self.model, True)["disabled"] + x["seconds"] = time.perf_counter() - started + self.last_generation_metadata = generation_metadata(x) + put(call / "result.json", x) + route.update( + request_sha256=sha(call / "request.json"), result_sha256=sha(call / "result.json") + ) + put(call / "route.json", route) diff --git a/research/finance_program_v1/evaluation/evaluate.py b/research/finance_program_v1/evaluation/evaluate.py index 56ccc51..9921844 100644 --- a/research/finance_program_v1/evaluation/evaluate.py +++ b/research/finance_program_v1/evaluation/evaluate.py @@ -1,46 +1,86 @@ +# 主干协调层:固定来源及AB/BA;Skill和Planner的实际路由由backend负责。 +# 历史公开队列接口仅smoke/val80;完整422补充分阶段协调器未公开。 """One pair per source, real frozen F66 execution; no labels or scoring.""" # 同一来源分别执行 base 与 sft 条件,推理阶段只产出轨迹,标签评分由后续离线步骤完成。 import argparse import datetime from pathlib import Path import time -from io_utils import ROOT,read,put,verify +from io_utils import ROOT, read, put, verify def main(): - p=argparse.ArgumentParser();p.add_argument('--cohort',choices=('smoke','val80'),required=True);a=p.parse_args() - m=verify();c=m['config'];study=read(ROOT/'data/study.json') - anchor=read(ROOT/'runs/training-anchor.json') - if anchor['training_manifest_sha256']!=c['training_manifest_sha256']:raise ValueError('training anchor differs') - output=ROOT/'runs'/a.cohort;output.mkdir(parents=True,exist_ok=False) - ids=study['cohorts'][a.cohort];rows={r['id']:r for r in study['rows']};started=time.monotonic() - summary={'cohort':a.cohort,'expected_ids':ids,'samples':[{'id':i,'arms':{}} for i in ids], - 'paired_sources':0,'status':'running','started_at':datetime.datetime.now(datetime.timezone.utc).isoformat()} + p = argparse.ArgumentParser() + p.add_argument("--cohort", choices=("smoke", "val80"), required=True) + a = p.parse_args() + m = verify() + c = m["config"] + study = read(ROOT / "data/study.json") + anchor = read(ROOT / "runs/training-anchor.json") + if anchor["training_manifest_sha256"] != c["training_manifest_sha256"]: + raise ValueError("training anchor differs") + output = ROOT / "runs" / a.cohort + output.mkdir(parents=True, exist_ok=False) + ids = study["cohorts"][a.cohort] + rows = {r["id"]: r for r in study["rows"]} + started = time.monotonic() + summary = { + "cohort": a.cohort, + "expected_ids": ids, + "samples": [{"id": i, "arms": {}} for i in ids], + "paired_sources": 0, + "status": "running", + "started_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), + } from backend import RoutedBackend from program_loop import build_program_controller + # Separate processes per cohort, same frozen weights and routing; backend-init artifacts get cohort-specific path. try: - backend=RoutedBackend(c['model'],c['adapter'],anchor,a.cohort) - for n,entry in enumerate(summary['samples']): - ident=entry['id'];row=rows[ident] - for arm in (('base','sft') if n%2==0 else ('sft','base')): - folder=output/'sources'/ident/arm;folder.mkdir(parents=True,exist_ok=False) - backend.start_source(folder,arm);begin=time.monotonic() - controller=build_program_controller(backend,study['registry'],study['rows'],study['budget'],skill_pool='F66') - assert len(controller.library)==66 - trace=controller.run({'source_id':ident,'domain':row['domain'],'field_name':row['metadata']['field_name']}) - trace.write_json(folder/'trace.json') - receipt={'id':ident,'arm':arm,'terminated':trace.terminated,'stop_reason':trace.stop_reason, - 'calls':len(backend.calls),'backend_errors':len(backend.failures),'seconds':time.monotonic()-begin} - put(folder/'receipt.json',receipt);entry['arms'][arm]=receipt - print(a.cohort,ident,arm,trace.terminated,trace.stop_reason,flush=True) - if backend.failures:raise RuntimeError('backend engineering failure; preserve all remaining denominator IDs') - summary['paired_sources']+=1 - put(output/'progress'/('%04d.json'%(n+1)),summary) - summary['status']='completed' + backend = RoutedBackend(c["model"], c["adapter"], anchor, a.cohort) + for n, entry in enumerate(summary["samples"]): + ident = entry["id"] + row = rows[ident] + for arm in ("base", "sft") if n % 2 == 0 else ("sft", "base"): + folder = output / "sources" / ident / arm + folder.mkdir(parents=True, exist_ok=False) + backend.start_source(folder, arm) + begin = time.monotonic() + controller = build_program_controller( + backend, study["registry"], study["rows"], study["budget"], skill_pool="F66" + ) + assert len(controller.library) == 66 + trace = controller.run( + { + "source_id": ident, + "domain": row["domain"], + "field_name": row["metadata"]["field_name"], + } + ) + trace.write_json(folder / "trace.json") + receipt = { + "id": ident, + "arm": arm, + "terminated": trace.terminated, + "stop_reason": trace.stop_reason, + "calls": len(backend.calls), + "backend_errors": len(backend.failures), + "seconds": time.monotonic() - begin, + } + put(folder / "receipt.json", receipt) + entry["arms"][arm] = receipt + print(a.cohort, ident, arm, trace.terminated, trace.stop_reason, flush=True) + if backend.failures: + raise RuntimeError( + "backend engineering failure; preserve all remaining denominator IDs" + ) + summary["paired_sources"] += 1 + put(output / "progress" / ("%04d.json" % (n + 1)), summary) + summary["status"] = "completed" finally: - summary['seconds']=time.monotonic()-started - put(output/'summary.json',summary) + summary["seconds"] = time.monotonic() - started + put(output / "summary.json", summary) -if __name__=='__main__':main() +if __name__ == "__main__": + main() diff --git a/research/finance_program_v1/evaluation/gate.py b/research/finance_program_v1/evaluation/gate.py index 50ee8bd..532f25b 100644 --- a/research/finance_program_v1/evaluation/gate.py +++ b/research/finance_program_v1/evaluation/gate.py @@ -1,81 +1,139 @@ """Pure fail-closed evaluation authorization and routing gates.""" + + # 评估放行同时绑定训练完成状态、独立审计及适配器身份;路由依据可信 system 消息识别 Planner。 def training_ready(state, signature): - complete, proof = state.get('completion') or {}, state.get('cpu_proof') or {} - return bool(state.get('manifest_sha256') == signature and state.get('writer_live') is False - and all(state.get('exits', {}).get(k) == 0 for k in ('trial', 'formal', 'pipeline', 'archive')) - and complete.get('manifest_sha256') == proof.get('manifest_sha256') == signature - and complete.get('global_step') == 13 and complete.get('sources') == 200 and complete.get('epoch') == 1. - and proof.get('independent_cpu_audit_passed') is True and state.get('adapter_sha256') - and state['adapter_sha256'] == complete.get('adapter_sha256') == proof.get('adapter_sha256')) + complete, proof = state.get("completion") or {}, state.get("cpu_proof") or {} + return bool( + state.get("manifest_sha256") == signature + and state.get("writer_live") is False + and all( + state.get("exits", {}).get(k) == 0 for k in ("trial", "formal", "pipeline", "archive") + ) + and complete.get("manifest_sha256") == proof.get("manifest_sha256") == signature + and complete.get("global_step") == 13 + and complete.get("sources") == 200 + and complete.get("epoch") == 1.0 + and proof.get("independent_cpu_audit_passed") is True + and state.get("adapter_sha256") + and state["adapter_sha256"] == complete.get("adapter_sha256") == proof.get("adapter_sha256") + ) def enabled_for(arm, messages, planner_system): - if arm not in ('base', 'sft'): - raise ValueError('unknown paired condition') - return bool(arm == 'sft' and messages and messages[0].get('role') == 'system' - and messages[0].get('content') == planner_system) + if arm not in ("base", "sft"): + raise ValueError("unknown paired condition") + return bool( + arm == "sft" + and messages + and messages[0].get("role") == "system" + and messages[0].get("content") == planner_system + ) def validate_ids(ids, smoke, train): - if (len(ids) != 80 or len(set(ids)) != 80 or len(smoke) != 2 or len(set(smoke)) != 2 - or set(ids) & set(smoke) or (set(ids) | set(smoke)) & set(train)): - raise ValueError('fixed80 and smoke must be unique and disjoint from training') + if ( + len(ids) != 80 + or len(set(ids)) != 80 + or len(smoke) != 2 + or len(set(smoke)) != 2 + or set(ids) & set(smoke) + or (set(ids) | set(smoke)) & set(train) + ): + raise ValueError("fixed80 and smoke must be unique and disjoint from training") def eos_options(model_eos, tokenizer_eos): values = list(model_eos) if isinstance(model_eos, (list, tuple)) else [model_eos] values.append(tokenizer_eos) if any(type(x) is not int or x < 0 for x in values): - raise ValueError('actual model and tokenizer EOS required') + raise ValueError("actual model and tokenizer EOS required") return sorted(set(values)) def validate_adapter_files(folder, anchor): from pathlib import Path from io_utils import sha - folder=Path(folder) - if (sha(folder/'adapter_model.safetensors')!=anchor['adapter_sha256'] - or sha(folder/'adapter_config.json')!=anchor['adapter_config_sha256']): - raise ValueError('loaded adapter/config bytes differ from accepted training anchor') + + folder = Path(folder) + if ( + sha(folder / "adapter_model.safetensors") != anchor["adapter_sha256"] + or sha(folder / "adapter_config.json") != anchor["adapter_config_sha256"] + ): + raise ValueError("loaded adapter/config bytes differ from accepted training anchor") -def validate_lora_inventory(config,inventory,original_targets,linear_shapes): +def validate_lora_inventory(config, inventory, original_targets, linear_shapes): """Compare expanded module identity and both tensor shapes, not serialized suffix count.""" import re - if (config.get('r')!=8 or config.get('lora_alpha')!=16 or config.get('lora_dropout')!=.05 - or config.get('peft_type')!='LORA' or config.get('task_type')!='CAUSAL_LM' - or config.get('bias')!='none' or config.get('modules_to_save') - or config.get('use_dora') or config.get('use_rslora') or config.get('rank_pattern') - or config.get('alpha_pattern')): - raise ValueError('unexpected LoRA recipe') - suffixes=config.get('target_modules') - if not isinstance(suffixes,list) or not suffixes or any(not isinstance(s,str) or not s for s in suffixes): - raise ValueError('nonempty serialized target suffix list required') - wanted=set(original_targets) - if (len(wanted)!=len(original_targets) or len(wanted)!=40 - or any(not n.startswith('model.language_model.layers.') for n in wanted)): - raise ValueError('original forty language targets required') - expanded={n for n in linear_shapes if any(n==s or n.endswith('.'+s) for s in suffixes)} - if expanded!=wanted:raise ValueError('serialized targets expand beyond/differ from original forty layers') - found={};names=set() + + if ( + config.get("r") != 8 + or config.get("lora_alpha") != 16 + or config.get("lora_dropout") != 0.05 + or config.get("peft_type") != "LORA" + or config.get("task_type") != "CAUSAL_LM" + or config.get("bias") != "none" + or config.get("modules_to_save") + or config.get("use_dora") + or config.get("use_rslora") + or config.get("rank_pattern") + or config.get("alpha_pattern") + ): + raise ValueError("unexpected LoRA recipe") + suffixes = config.get("target_modules") + if ( + not isinstance(suffixes, list) + or not suffixes + or any(not isinstance(s, str) or not s for s in suffixes) + ): + raise ValueError("nonempty serialized target suffix list required") + wanted = set(original_targets) + if ( + len(wanted) != len(original_targets) + or len(wanted) != 40 + or any(not n.startswith("model.language_model.layers.") for n in wanted) + ): + raise ValueError("original forty language targets required") + expanded = {n for n in linear_shapes if any(n == s or n.endswith("." + s) for s in suffixes)} + if expanded != wanted: + raise ValueError("serialized targets expand beyond/differ from original forty layers") + found = {} + names = set() for item in inventory: - name=item['name'];match=re.fullmatch(r'base_model\.model\.(.+)\.lora_([AB])\.weight',name) - if name in names or not match:raise ValueError('unexpected or duplicate adapter tensor') - names.add(name);target,side=match.groups() - if target not in wanted:raise ValueError('adapter tensor outside original language targets') - out_features,in_features=linear_shapes[target] - shape=[8,in_features] if side=='A' else [out_features,8] - if item['shape']!=shape:raise ValueError('adapter tensor shape differs from original linear layer') - found.setdefault(target,set()).add(side) - if len(inventory)!=80 or set(found)!=wanted or any(sides!={'A','B'} for sides in found.values()): - raise ValueError('exactly forty complete A/B pairs required') - return {'serialized_target_suffixes':suffixes,'resolved_targets':40,'tensor_count':80, - 'original_targets_and_shapes_exact':True} - - -def cpu_proof_identity(proof,actual_config_sha,completion_config_sha,verifier_sha,validator_manifest_sha): - return bool(proof.get('cpu_validator_version')==2 - and proof.get('adapter_config_sha256')==actual_config_sha==completion_config_sha - and proof.get('verifier_sha256')==verifier_sha - and proof.get('validator_manifest_sha256')==validator_manifest_sha) + name = item["name"] + match = re.fullmatch(r"base_model\.model\.(.+)\.lora_([AB])\.weight", name) + if name in names or not match: + raise ValueError("unexpected or duplicate adapter tensor") + names.add(name) + target, side = match.groups() + if target not in wanted: + raise ValueError("adapter tensor outside original language targets") + out_features, in_features = linear_shapes[target] + shape = [8, in_features] if side == "A" else [out_features, 8] + if item["shape"] != shape: + raise ValueError("adapter tensor shape differs from original linear layer") + found.setdefault(target, set()).add(side) + if ( + len(inventory) != 80 + or set(found) != wanted + or any(sides != {"A", "B"} for sides in found.values()) + ): + raise ValueError("exactly forty complete A/B pairs required") + return { + "serialized_target_suffixes": suffixes, + "resolved_targets": 40, + "tensor_count": 80, + "original_targets_and_shapes_exact": True, + } + + +def cpu_proof_identity( + proof, actual_config_sha, completion_config_sha, verifier_sha, validator_manifest_sha +): + return bool( + proof.get("cpu_validator_version") == 2 + and proof.get("adapter_config_sha256") == actual_config_sha == completion_config_sha + and proof.get("verifier_sha256") == verifier_sha + and proof.get("validator_manifest_sha256") == validator_manifest_sha + ) diff --git a/research/finance_program_v1/evaluation/io_utils.py b/research/finance_program_v1/evaluation/io_utils.py index 74fcbbf..30178f8 100644 --- a/research/finance_program_v1/evaluation/io_utils.py +++ b/research/finance_program_v1/evaluation/io_utils.py @@ -1,34 +1,39 @@ """Exclusive artifact writes; byte identity and runtime import bootstrap.""" + import hashlib import json from pathlib import Path import sys ROOT = Path(__file__).resolve().parent -sys.path[:0] = [str(ROOT / 'runtime'), str(ROOT / 'legacy')] +sys.path[:0] = [str(ROOT / "runtime"), str(ROOT / "legacy")] def sha(path): h = hashlib.sha256() - with Path(path).open('rb') as f: - for b in iter(lambda: f.read(1048576), b''):h.update(b) + with Path(path).open("rb") as f: + for b in iter(lambda: f.read(1048576), b""): + h.update(b) return h.hexdigest() -def read(path):return json.loads(Path(path).read_text(encoding='utf-8')) +def read(path): + return json.loads(Path(path).read_text(encoding="utf-8")) def put(path, value): - path = Path(path);path.parent.mkdir(parents=True, exist_ok=True) - with path.open('x', encoding='utf-8', newline='\n') as f: - json.dump(value, f, ensure_ascii=False, indent=2, allow_nan=False);f.write('\n') + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", encoding="utf-8", newline="\n") as f: + json.dump(value, f, ensure_ascii=False, indent=2, allow_nan=False) + f.write("\n") def verify(root=ROOT): root = Path(root) - m = read(root / 'manifest.json') - for item in m['files']: - p = root / item['path'] - if not p.resolve().is_relative_to(root.resolve()) or sha(p) != item['sha256']: - raise ValueError('evaluation frozen file SHA differs: ' + item['path']) + m = read(root / "manifest.json") + for item in m["files"]: + p = root / item["path"] + if not p.resolve().is_relative_to(root.resolve()) or sha(p) != item["sha256"]: + raise ValueError("evaluation frozen file SHA differs: " + item["path"]) return m diff --git a/research/finance_program_v1/evaluation/metrics.py b/research/finance_program_v1/evaluation/metrics.py index 06f6eeb..9d0e031 100644 --- a/research/finance_program_v1/evaluation/metrics.py +++ b/research/finance_program_v1/evaluation/metrics.py @@ -1,54 +1,91 @@ """Post-run local-only labels; all failures retain the fixed denominator.""" + # 评分始终遍历固定评估 ID,缺失或未合法终止的轨迹也计入分母;配对比较要求两组来源完全一致。 from collections import Counter -def macro(golds,preds,labels): - values=[] +def macro(golds, preds, labels): + values = [] for label in labels: - tp=sum(g==label and p==label for g,p in zip(golds,preds)) - fp=sum(g!=label and p==label for g,p in zip(golds,preds)) - fn=sum(g==label and p!=label for g,p in zip(golds,preds)) - values.append(2*tp/(2*tp+fp+fn) if 2*tp+fp+fn else 0.) - return sum(values)/len(values) if values else 0. + tp = sum(g == label and p == label for g, p in zip(golds, preds)) + fp = sum(g != label and p == label for g, p in zip(golds, preds)) + fn = sum(g == label and p != label for g, p in zip(golds, preds)) + values.append(2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0) + return sum(values) / len(values) if values else 0.0 -def score(ids,traces,gold,registry): - if len(ids)!=len(set(ids)) or not set(traces)<=set(ids) or not set(ids)<=set(gold):raise ValueError('score ID mismatch') - counts=Counter();details={};golds=[];preds=[] +def score(ids, traces, gold, registry): + if len(ids) != len(set(ids)) or not set(traces) <= set(ids) or not set(ids) <= set(gold): + raise ValueError("score ID mismatch") + counts = Counter() + details = {} + golds = [] + preds = [] # 遍历固定名单而非现存轨迹,缺失样本不会被静默排除并抬高准确率。 for i in ids: - t=traces.get(i) or {};final=t.get('final_result') or {};legal=t.get('terminated') is True - prediction=final.get('category') if legal else None;grade=final.get('grading_level') if legal else None - cat=bool(legal and prediction==gold[i]['category']);level=bool(legal and grade==gold[i]['grading_level']) - history=[] - for program in t.get('programs',[]): - for step in program.get('steps',[]): - data=step.get('data') or {} - candidates=data.get('standard_candidates') - if (step.get('call',{}).get('tool') in ('SELECT_CATEGORY_TOPK','SEARCH_STANDARD','SEARCH_STANDARD_BY_FIELD', - 'SEARCH_STANDARD_BY_CONTEXT','SEARCH_STANDARD_BY_TABLE','SEARCH_STANDARD_BY_DATABASE','RESEARCH_STANDARD') - and step.get('status')=='success' and isinstance(candidates,list) and len(candidates)==5): - value=[v.get('category') or v.get('category_id') for v in candidates] - if len(set(value))==5:history.append(value) - row={'terminated':legal,'category_correct':cat,'grading_correct':level,'joint_correct':cat and level, - 'top5_first_hit':bool(history and gold[i]['category'] in history[0]), - 'top5_final_hit':bool(history and gold[i]['category'] in history[-1]), - 'top5_any_hit':any(gold[i]['category'] in h for h in history)} - details[i]=row;counts.update({k:int(v) for k,v in row.items()});golds.append(gold[i]['category']);preds.append(prediction) - return {'denominator':len(ids),'missing':len(ids)-len(traces),**counts, - 'category_accuracy':counts['category_correct']/len(ids), - 'grading_accuracy':counts['grading_correct']/len(ids),'joint_accuracy':counts['joint_correct']/len(ids), - 'termination_rate':counts['terminated']/len(ids), - 'macro_f1_supported':macro(golds,preds,sorted(set(golds))), - 'macro_f1_fixed12':macro(golds,preds,sorted(registry)),'per_id':details} + t = traces.get(i) or {} + final = t.get("final_result") or {} + legal = t.get("terminated") is True + prediction = final.get("category") if legal else None + grade = final.get("grading_level") if legal else None + cat = bool(legal and prediction == gold[i]["category"]) + level = bool(legal and grade == gold[i]["grading_level"]) + history = [] + for program in t.get("programs", []): + for step in program.get("steps", []): + data = step.get("data") or {} + candidates = data.get("standard_candidates") + if ( + step.get("call", {}).get("tool") + in ( + "SELECT_CATEGORY_TOPK", + "SEARCH_STANDARD", + "SEARCH_STANDARD_BY_FIELD", + "SEARCH_STANDARD_BY_CONTEXT", + "SEARCH_STANDARD_BY_TABLE", + "SEARCH_STANDARD_BY_DATABASE", + "RESEARCH_STANDARD", + ) + and step.get("status") == "success" + and isinstance(candidates, list) + and len(candidates) == 5 + ): + value = [v.get("category") or v.get("category_id") for v in candidates] + if len(set(value)) == 5: + history.append(value) + row = { + "terminated": legal, + "category_correct": cat, + "grading_correct": level, + "joint_correct": cat and level, + "top5_first_hit": bool(history and gold[i]["category"] in history[0]), + "top5_final_hit": bool(history and gold[i]["category"] in history[-1]), + "top5_any_hit": any(gold[i]["category"] in h for h in history), + } + details[i] = row + counts.update({k: int(v) for k, v in row.items()}) + golds.append(gold[i]["category"]) + preds.append(prediction) + return { + "denominator": len(ids), + "missing": len(ids) - len(traces), + **counts, + "category_accuracy": counts["category_correct"] / len(ids), + "grading_accuracy": counts["grading_correct"] / len(ids), + "joint_accuracy": counts["joint_correct"] / len(ids), + "termination_rate": counts["terminated"] / len(ids), + "macro_f1_supported": macro(golds, preds, sorted(set(golds))), + "macro_f1_fixed12": macro(golds, preds, sorted(registry)), + "per_id": details, + } -def paired(ids,sft,base): - if set(sft)!=set(base) or set(sft)!=set(ids):raise ValueError('paired IDs differ') - result={} +def paired(ids, sft, base): + if set(sft) != set(base) or set(sft) != set(ids): + raise ValueError("paired IDs differ") + result = {} for key in next(iter(sft.values())): - new=[i for i in ids if sft[i][key] and not base[i][key]] - old=[i for i in ids if base[i][key] and not sft[i][key]] - result[key]={'sft_only':new,'base_only':old,'delta':len(new)-len(old)} + new = [i for i in ids if sft[i][key] and not base[i][key]] + old = [i for i in ids if base[i][key] and not sft[i][key]] + result[key] = {"sft_only": new, "base_only": old, "delta": len(new) - len(old)} return result diff --git a/research/finance_program_v1/evaluation/replay.py b/research/finance_program_v1/evaluation/replay.py index e929e35..0567e95 100644 --- a/research/finance_program_v1/evaluation/replay.py +++ b/research/finance_program_v1/evaluation/replay.py @@ -1,3 +1,4 @@ +# Recorded消耗原始响应,逐次核原请求;不生成新答案,也不把脱敏投影当完整回放。 """Independent recorded-I/O replay; never loads a GPU or a model.""" # 使用记录中的响应重跑冻结控制器,同时核对请求、生成参数与 LoRA 路由,回放无需模型或 GPU。 import argparse @@ -8,92 +9,159 @@ def validate_record(q, x, route, arm, system, tokenizer, anchor=None): - assert q['messages'] == x['messages'] - assert q['generation'] == x['generation'] - g=q['generation'] - assert g == {'do_sample':False,'max_new_tokens':512,'max_time':90.,'eos_token_id':[248044,248046],'pad_token_id':248044} - enabled=enabled_for(arm,q['messages'],system) - assert route['arm']==arm and route['enabled'] is enabled and route['layer_count']==40 - assert route['entered_disabled'] is (not enabled) and route['restored_disabled'] is True - if anchor is not None:assert route['adapter_sha256']==anchor['adapter_sha256'] - assert x['parameter_devices']==['cuda:0'] and x['parameter_dtypes']==['torch.float16'] - if not x.get('error'): - assert x['input_devices']==['cuda:0'] and 0=512) + assert q["messages"] == x["messages"] + assert q["generation"] == x["generation"] + g = q["generation"] + assert g == { + "do_sample": False, + "max_new_tokens": 512, + "max_time": 90.0, + "eos_token_id": [248044, 248046], + "pad_token_id": 248044, + } + enabled = enabled_for(arm, q["messages"], system) + assert route["arm"] == arm and route["enabled"] is enabled and route["layer_count"] == 40 + assert route["entered_disabled"] is (not enabled) and route["restored_disabled"] is True + if anchor is not None: + assert route["adapter_sha256"] == anchor["adapter_sha256"] + assert x["parameter_devices"] == ["cuda:0"] and x["parameter_dtypes"] == ["torch.float16"] + if not x.get("error"): + assert x["input_devices"] == ["cuda:0"] and 0 < x["input_tokens"] <= 32768 - 512 + assert x["output_tokens"] == len(x["generated_ids"]) <= 512 + assert x["truncation_at_budget"] is (x["output_tokens"] >= 512) if tokenizer is not None: - prompt=tokenizer.apply_chat_template(q['messages'],tokenize=False,add_generation_prompt=True,enable_thinking=False) - ids=tokenizer(prompt,add_special_tokens=False)['input_ids'] - assert len(ids)==x['input_tokens'] - assert tokenizer.decode(x['generated_ids'],skip_special_tokens=True,clean_up_tokenization_spaces=False)==x['raw_text'] + prompt = tokenizer.apply_chat_template( + q["messages"], tokenize=False, add_generation_prompt=True, enable_thinking=False + ) + ids = tokenizer(prompt, add_special_tokens=False)["input_ids"] + assert len(ids) == x["input_tokens"] + assert ( + tokenizer.decode( + x["generated_ids"], skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + == x["raw_text"] + ) class Recorded: def __init__(self, records): - self.records=records;self.position=0;self.faults=[];self.last_generation_metadata={} - def __call__(self,messages): - self.last_generation_metadata={} + self.records = records + self.position = 0 + self.faults = [] + self.last_generation_metadata = {} + + def __call__(self, messages): + self.last_generation_metadata = {} try: - assert self.position= self.max_identical_calls: raise ValueError("identical successful call blocked for current evidence lineage") correction_context = None @@ -60,46 +94,78 @@ def step(self, call, record, state, counts, lineage, comparison_failures=None): comparison_fingerprint, correction_context = comparison_failures.before_call(inputs) result["status"] = "error" if call.tool == COMPARISON: - observation = self.executor.execute(canonical, record, state, self.loader.load(call.tool), - correction_context=correction_context) + observation = self.executor.execute( + canonical, + record, + state, + self.loader.load(call.tool), + correction_context=correction_context, + ) else: - observation = self.executor.execute(canonical, record, state, self.loader.load(call.tool)) + observation = self.executor.execute( + canonical, record, state, self.loader.load(call.tool) + ) # Normalize/availability update is transactional with publication. updated = deepcopy(state) observation = self.guard._normalize_observation(canonical, observation, updated) self.executor._validate_deterministic(observation, spec) result.update(asdict(observation)) if observation.status == "success": - changed = {key for key, value in observation.data.items() if state.get(key) != value} - evidence = changed & (set(SEMANTIC_KEYS) | set(ALIGNMENT_KEYS) | set(FIELDS) - | {"field_metadata", "acquired_metadata", "table_fields", "selected_context_fields", - "context_fields", "context_field_descriptions", "context_field_types", - "context_field_values", "table_context", "database_context"}) + changed = { + key for key, value in observation.data.items() if state.get(key) != value + } + evidence = changed & ( + set(SEMANTIC_KEYS) + | set(ALIGNMENT_KEYS) + | set(FIELDS) + | { + "field_metadata", + "acquired_metadata", + "table_fields", + "selected_context_fields", + "context_fields", + "context_field_descriptions", + "context_field_types", + "context_field_values", + "table_context", + "database_context", + } + ) invalidated = [] if evidence or "standard_candidates" in changed: invalidated.extend(self._drop(updated, SELECTION)) elif "category" in changed or "aligned_standard_entry" in changed: invalidated.extend(self._drop(updated, GRADE)) - if spec.terminal and not self.guard._valid_terminal(observation.data.get("final_result"), updated): + if spec.terminal and not self.guard._valid_terminal( + observation.data.get("final_result"), updated + ): raise ValueError("invalid terminal result rejected by real PoolController") publish_state(record, updated, observation.data, call.tool) - state.clear(); state.update(updated) + state.clear() + state.update(updated) # Global success dedup consumes the input lineage, before incrementing it. counts[identity] += 1 - if evidence: lineage["evidence"] += 1 - if "standard_candidates" in changed: lineage["candidates"] += 1 - if "category" in changed or "aligned_standard_entry" in changed: lineage["selection"] += 1 + if evidence: + lineage["evidence"] += 1 + if "standard_candidates" in changed: + lineage["candidates"] += 1 + if "category" in changed or "aligned_standard_entry" in changed: + lineage["selection"] += 1 result["invalidations"] = invalidated else: - state.clear(); state.update(updated) + state.clear() + state.update(updated) except Exception as exc: - if result["status"] == "success": result["status"] = "error" + if result["status"] == "success": + result["status"] = "error" metadata = {**result.get("metadata", {}), **deepcopy(getattr(exc, "metadata", {}))} result.update(summary=str(exc), data={}, metadata=metadata) if comparison_fingerprint is not None and result["status"] == "error": comparison_failures.record_failure(comparison_fingerprint, exc, metadata) state["comparison_failure_ledger"] = comparison_failures.snapshot() if canonical is not None and result["status"] == "error": - self.availability.observe(canonical, Observation(call.tool, "error", str(exc), {}), state) + self.availability.observe( + canonical, Observation(call.tool, "error", str(exc), {}), state + ) result["lineage"] = dict(lineage) return json_snapshot(result) diff --git a/research/finance_program_v1/evaluation/runtime/program_loop/failure_policy.py b/research/finance_program_v1/evaluation/runtime/program_loop/failure_policy.py index 574e8a0..b2f06f6 100644 --- a/research/finance_program_v1/evaluation/runtime/program_loop/failure_policy.py +++ b/research/finance_program_v1/evaluation/runtime/program_loop/failure_policy.py @@ -1,4 +1,5 @@ """Run-local comparison failure facts and limits; never execute a retry.""" + from copy import deepcopy import hashlib import json @@ -12,8 +13,13 @@ def content_sha256(value): - serialized = json.dumps(json_snapshot(value), sort_keys=True, ensure_ascii=False, - separators=(",", ":"), allow_nan=False) + serialized = json.dumps( + json_snapshot(value), + sort_keys=True, + ensure_ascii=False, + separators=(",", ":"), + allow_nan=False, + ) return hashlib.sha256(serialized.encode("utf-8")).hexdigest() @@ -40,21 +46,39 @@ def before_call(self, inputs): raise ValueError("comparison blocked: observed no_match for identical effective inputs") correctable = [failure for failure in failures if failure["failure_kind"] in CORRECTABLE] if len(correctable) >= 2: - raise ValueError("comparison blocked: explicit correction already failed for identical effective inputs") + raise ValueError( + "comparison blocked: explicit correction already failed for identical effective inputs" + ) return fingerprint, deepcopy(correctable[-1]) if correctable else None def record_failure(self, fingerprint, error, metadata): kind = metadata.get("failure_kind", "unknown_error") if kind not in FAILURE_KINDS: kind = "unknown_error" - entry = self.entries.setdefault(fingerprint, {"tool": COMPARISON, - "input_fingerprint": fingerprint, "failure_count": 0, "failures": []}) + entry = self.entries.setdefault( + fingerprint, + { + "tool": COMPARISON, + "input_fingerprint": fingerprint, + "failure_count": 0, + "failures": [], + }, + ) entry["failure_count"] += 1 raw = metadata.get("raw_response") - entry["failures"].append({"failure_kind": kind, "attempt": entry["failure_count"], - "request_sha256": content_sha256(metadata["messages"]) if "messages" in metadata else None, - "raw_sha256": raw_sha256(raw), "raw_response": json_snapshot(raw), - "validation_error": str(error), "generation": json_snapshot(metadata.get("generation", {}))}) + entry["failures"].append( + { + "failure_kind": kind, + "attempt": entry["failure_count"], + "request_sha256": ( + content_sha256(metadata["messages"]) if "messages" in metadata else None + ), + "raw_sha256": raw_sha256(raw), + "raw_response": json_snapshot(raw), + "validation_error": str(error), + "generation": json_snapshot(metadata.get("generation", {})), + } + ) def snapshot(self): return deepcopy(list(self.entries.values())) diff --git a/research/finance_program_v1/evaluation/runtime/program_loop/planner.py b/research/finance_program_v1/evaluation/runtime/program_loop/planner.py index 9c986d3..8831c8b 100644 --- a/research/finance_program_v1/evaluation/runtime/program_loop/planner.py +++ b/research/finance_program_v1/evaluation/runtime/program_loop/planner.py @@ -1,4 +1,5 @@ """Generate one whole Program per outer attempt.""" + import json from .catalog_context import public_state, pack_library from .prompt_encoding import pack_prompt @@ -42,16 +43,21 @@ def planner_messages(record, state, library, budget, feedback, *, skill_pool="P14"): compact_library, input_rules = pack_library(library) - payload = {"task": "Plan the complete remaining classification task using verified evidence and frozen Registry grading, through legal terminal execution.", - "current": public_state(record, state), "skill_library": compact_library, - "shared_input_rules": input_rules, - "remaining_budget": budget, "feedback": feedback, - "recovery_context": recovery_context(state, budget, feedback), - "availability_rule": "unknown permits acquisition; canonical source observations establish obtained/unavailable; errors remain retryable; omitted batch attributes remain unknown"} + payload = { + "task": "Plan the complete remaining classification task using verified evidence and frozen Registry grading, through legal terminal execution.", + "current": public_state(record, state), + "skill_library": compact_library, + "shared_input_rules": input_rules, + "remaining_budget": budget, + "feedback": feedback, + "recovery_context": recovery_context(state, budget, feedback), + "availability_rule": "unknown permits acquisition; canonical source observations establish obtained/unavailable; errors remain retryable; omitted batch attributes remain unknown", + } if skill_pool == "F66" and any( - failure.get("failure_kind") == "no_match" - for entry in state.get("comparison_failure_ledger", []) - for failure in entry.get("failures", [])): + failure.get("failure_kind") == "no_match" + for entry in state.get("comparison_failure_ledger", []) + for failure in entry.get("failures", []) + ): payload["recovery_context"]["comparison_recovery_rule"] = ( "An observed no_match blocks another comparison with identical effective inputs. " "Repeating the same failed comparison cannot advance the task and still consumes the remaining budget. " @@ -61,28 +67,51 @@ def planner_messages(record, state, library, budget, feedback, *, skill_pool="P1 "and current verified state. Plan the complete remaining task autonomously within the existing budget, " "using genuinely new evidence or changed candidates where available, or another contract-valid path " "supported by current observations. Do not reuse a blocked comparison, fabricate alignment, or assume " - "that an unexecuted tail must be followed. Only a verified terminal completes classification.") - system = SYSTEM if skill_pool == "P14" else SYSTEM.replace("complete P14 library", "complete F66 library") + "that an unexecuted tail must be followed. Only a verified terminal completes classification." + ) + system = ( + SYSTEM + if skill_pool == "P14" + else SYSTEM.replace("complete P14 library", "complete F66 library") + ) if skill_pool == "F66": payload["contract_dependency_facts"] = { "category_and_alignment_producers": [ - {"name": s["name"], "required_inputs": s["required_inputs"], "produces": s["produces"]} - for s in library if {"category", "aligned_standard_entry"} <= set(s["produces"])], + { + "name": s["name"], + "required_inputs": s["required_inputs"], + "produces": s["produces"], + } + for s in library + if {"category", "aligned_standard_entry"} <= set(s["produces"]) + ], "comparison_dependency_rule": ( "Comparison is optional for a Skill whose required inputs do not require a comparison output. " "The listed category producers themselves publish the selected category and its frozen aligned entry " "after a validated choice from actual retrieved candidates. This is a literal contract subset, " - "not a selected Program or permission to skip any required input.")} + "not a selected Program or permission to skip any required input." + ), + } current_facts = [] for spec in payload["contract_dependency_facts"]["category_and_alignment_producers"]: observed = [] for key in spec["required_inputs"]: reference = canonical_reference(key, state) - if (reference and reference.startswith("$state.") and - present(state.get(reference.removeprefix("$state.")))): + if ( + reference + and reference.startswith("$state.") + and present(state.get(reference.removeprefix("$state."))) + ): observed.append(key) - current_facts.append({"name": spec["name"], "observed_required_inputs": observed, - "unobserved_required_inputs": [key for key in spec["required_inputs"] if key not in observed]}) + current_facts.append( + { + "name": spec["name"], + "observed_required_inputs": observed, + "unobserved_required_inputs": [ + key for key in spec["required_inputs"] if key not in observed + ], + } + ) payload["contract_dependency_facts"]["current_category_input_facts"] = current_facts system += ( "\nF66 dependency reminder: consult contract_dependency_facts and the full contracts. " @@ -90,13 +119,15 @@ def planner_messages(record, state, library, budget, feedback, *, skill_pool="P1 "Choose the dependency path yourself. For runtime state inputs prefer arguments:{}; " "the binder supplies actually available required inputs. Never paste observed metadata or semantic " "text into dynamic arguments. A missing semantic dependency needs its actual producer before use; " - "a raw table description is not already table_semantics. Observe all original budgets and terminal guards.") + "a raw table description is not already table_semantics. Observe all original budgets and terminal guards." + ) system += ( "\nF66 completion objective: prioritize a complete contract-valid classification path whose required " "inputs are already observed. Input presence is factual context, not a guarantee of semantic validity; " "execution still verifies all contracts. Optional diagnostics must not become undocumented gating " "steps. A no_match observation does not require repeatedly searching until an optional comparison " - "agrees. Choose the remaining whole Program yourself from actual evidence and dependencies.") + "agrees. Choose the remaining whole Program yourself from actual evidence and dependencies." + ) if feedback and feedback.get("status") == "planner_rejected": payload["request_mode"] = "revise_rejected_program" payload["revision_request"] = { @@ -106,16 +137,29 @@ def planner_messages(record, state, library, budget, feedback, *, skill_pool="P1 "argument_rule": ( "Prefer arguments:{} for required runtime-bound inputs. For explicit state inputs copy the " "exact shared_input_rules canonical_reference; do not substitute a different alias or observed " - "text. Native observed_missing_metadata_type choices remain subject to their actual contract.")} + "text. Native observed_missing_metadata_type choices remain subject to their actual contract." + ), + } payload["task"] = ( "Revise the previous unexecuted Program to correct the actual validation error in feedback. " "Return one complete remaining Program, using only exact allowed Skill names and canonical " "arguments from the contracts. The rejected Program produced no observations. Use current " "verified state and the unchanged remaining budget; do not repeat the rejected error or invent " - "a new Skill or dependency. Choose the sequence yourself and finish through the validated terminal.") + "a new Skill or dependency. Choose the sequence yourself and finish through the validated terminal." + ) encoded = pack_prompt(payload) if skill_pool == "F66": tail = ("current", "feedback", "recovery_context", "remaining_budget", "task") - encoded = {**{key: value for key, value in encoded.items() if key not in tail}, - **{key: encoded[key] for key in tail}} - return [{"role": "system", "content": system}, {"role": "user", "content": json.dumps(encoded, ensure_ascii=False, allow_nan=False, separators=(",", ":"))}] + encoded = { + **{key: value for key, value in encoded.items() if key not in tail}, + **{key: encoded[key] for key in tail}, + } + return [ + {"role": "system", "content": system}, + { + "role": "user", + "content": json.dumps( + encoded, ensure_ascii=False, allow_nan=False, separators=(",", ":") + ), + }, + ] diff --git a/research/finance_program_v1/evaluation/runtime/program_loop/planning_contracts.py b/research/finance_program_v1/evaluation/runtime/program_loop/planning_contracts.py index 67c396a..5cb880c 100644 --- a/research/finance_program_v1/evaluation/runtime/program_loop/planning_contracts.py +++ b/research/finance_program_v1/evaluation/runtime/program_loop/planning_contracts.py @@ -3,11 +3,21 @@ Possible producers and outputs are conditional, never proof of execution success. Actual-state binding and the executor still validate every supplied input/output. """ -from .validation import canonical_reference, explicit_value_policy, possible_outputs, FINAL_EVIDENCE_REQUIREMENTS + +from .validation import ( + canonical_reference, + explicit_value_policy, + possible_outputs, + FINAL_EVIDENCE_REQUIREMENTS, +) def planning_contract(spec, catalog): - known = {key for entry in catalog.values() for key in (*entry.required_inputs, *entry.optional_inputs)} + known = { + key + for entry in catalog.values() + for key in (*entry.required_inputs, *entry.optional_inputs) + } known.update(key for entry in catalog.values() for key in possible_outputs(entry)) known.add("final_evidence_state") inputs = {} @@ -17,14 +27,30 @@ def planning_contract(spec, catalog): inputs[key] = { "required": key in spec.required_inputs, "canonical_reference": ref, - "explicit_value_policy": "observed_missing_metadata_type" if spec.name == "ACQUIRE_MISSING_METADATA" and key == "missing_metadata_type" else explicit_value_policy(ref), + "explicit_value_policy": ( + "observed_missing_metadata_type" + if spec.name == "ACQUIRE_MISSING_METADATA" and key == "missing_metadata_type" + else explicit_value_policy(ref) + ), "source": "state" if target else "initial_binding", - "possible_producers": [other.name for other in catalog.values() if target in possible_outputs(other)] if target and key != "final_evidence_state" else [], - "requires_all": sorted(FINAL_EVIDENCE_REQUIREMENTS) if key == "final_evidence_state" else [], + "possible_producers": ( + [other.name for other in catalog.values() if target in possible_outputs(other)] + if target and key != "final_evidence_state" + else [] + ), + "requires_all": ( + sorted(FINAL_EVIDENCE_REQUIREMENTS) if key == "final_evidence_state" else [] + ), } if spec.name == "ACQUIRE_MISSING_METADATA" and key == "missing_metadata_type": - inputs[key]["choice_rule"] = ("Choose an explicit native type from actual missing_metadata_types, " - "or a type conditionally reported missing by a preceding metadata check/acquisition " - "in this Program. The runtime binder checks actual missing_metadata_types; " - "a future retrieval is not guaranteed to succeed.") - return {"argument_template": {}, "inputs": inputs, "conditional_outputs": sorted(possible_outputs(spec))} + inputs[key]["choice_rule"] = ( + "Choose an explicit native type from actual missing_metadata_types, " + "or a type conditionally reported missing by a preceding metadata check/acquisition " + "in this Program. The runtime binder checks actual missing_metadata_types; " + "a future retrieval is not guaranteed to succeed." + ) + return { + "argument_template": {}, + "inputs": inputs, + "conditional_outputs": sorted(possible_outputs(spec)), + } diff --git a/research/finance_program_v1/evaluation/runtime/program_loop/prompt_encoding.py b/research/finance_program_v1/evaluation/runtime/program_loop/prompt_encoding.py index 4ab1d3f..ea18038 100644 --- a/research/finance_program_v1/evaluation/runtime/program_loop/prompt_encoding.py +++ b/research/finance_program_v1/evaluation/runtime/program_loop/prompt_encoding.py @@ -1,33 +1,40 @@ """Lossless repeated-observation references, not execution/state references.""" + from collections import Counter from copy import deepcopy import json -SCOPE = ('current', 'feedback', 'recovery_context') -TAG = 'prompt_ref' -TABLE = 'shared_values' -SCHEMA = 'prompt_encoding_schema' +SCOPE = ("current", "feedback", "recovery_context") +TAG = "prompt_ref" +TABLE = "shared_values" +SCHEMA = "prompt_encoding_schema" def _canonical(value): - return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False) + return json.dumps( + value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False + ) def pack_prompt(payload): if not isinstance(payload, dict) or TABLE in payload or SCHEMA in payload: - raise ValueError('reserved prompt encoding fields already present') + raise ValueError("reserved prompt encoding fields already present") counts = Counter() originals = {} def count(value): if isinstance(value, dict) and set(value) == {TAG}: - raise ValueError('reserved prompt reference collision') + raise ValueError("reserved prompt reference collision") if isinstance(value, (dict, list, str)): key = _canonical(value) if len(key) >= 256: counts[key] += 1 originals[key] = value - children = value.values() if isinstance(value, dict) else value if isinstance(value, list) else () + children = ( + value.values() + if isinstance(value, dict) + else value if isinstance(value, list) else () + ) for child in children: count(child) @@ -38,10 +45,10 @@ def count(value): values = {} def walk(value, excluded=None): - key = _canonical(value) if isinstance(value, (dict, list, str)) else '' + key = _canonical(value) if isinstance(value, (dict, list, str)) else "" if counts[key] > 1 and key != excluded: if key not in refs: - name = 'v' + str(len(refs) + 1) + name = "v" + str(len(refs) + 1) refs[key] = name values[name] = walk(originals[key], key) return {TAG: refs[key]} @@ -58,13 +65,17 @@ def walk(value, excluded=None): encoded[SCHEMA] = 1 encoded[TABLE] = values if _canonical(unpack_prompt(encoded)) != _canonical(payload): - raise ValueError('lossless prompt roundtrip failed') + raise ValueError("lossless prompt roundtrip failed") return encoded def unpack_prompt(encoded): - if not isinstance(encoded, dict) or encoded.get(SCHEMA) != 1 or not isinstance(encoded.get(TABLE), dict): - raise ValueError('invalid prompt encoding schema') + if ( + not isinstance(encoded, dict) + or encoded.get(SCHEMA) != 1 + or not isinstance(encoded.get(TABLE), dict) + ): + raise ValueError("invalid prompt encoding schema") values = encoded[TABLE] used = set() active = set() @@ -74,7 +85,7 @@ def expand(value): if isinstance(value, dict) and set(value) == {TAG}: name = value[TAG] if not isinstance(name, str) or name not in values or name in active: - raise ValueError('dangling or cyclic prompt reference') + raise ValueError("dangling or cyclic prompt reference") used.add(name) if name not in cache: active.add(name) @@ -87,10 +98,12 @@ def expand(value): return [expand(child) for child in value] return value - result = {name: deepcopy(value) for name, value in encoded.items() if name not in (TABLE, SCHEMA)} + result = { + name: deepcopy(value) for name, value in encoded.items() if name not in (TABLE, SCHEMA) + } for name in SCOPE: if name in result: result[name] = expand(result[name]) if used != set(values): - raise ValueError('unused shared value could conceal unobserved evidence') + raise ValueError("unused shared value could conceal unobserved evidence") return result diff --git a/research/finance_program_v1/evaluation/runtime/program_loop/recovery_context.py b/research/finance_program_v1/evaluation/runtime/program_loop/recovery_context.py index 6f75a96..eb1fee6 100644 --- a/research/finance_program_v1/evaluation/runtime/program_loop/recovery_context.py +++ b/research/finance_program_v1/evaluation/runtime/program_loop/recovery_context.py @@ -1,4 +1,5 @@ """Summarize actual outer-loop observations without proposing or executing steps.""" + from .contracts import json_snapshot @@ -9,33 +10,53 @@ def recovery_context(state, budget, feedback): Keep raw feedback at its existing boundary; this summary omits values and arguments. """ previous = None - if feedback and feedback.get('status') in ('completed', 'failed', 'budget_exhausted', 'terminated') and 'plan' in feedback: - steps = feedback.get('steps', []) - executed = {step['step_index'] for step in steps} + if ( + feedback + and feedback.get("status") in ("completed", "failed", "budget_exhausted", "terminated") + and "plan" in feedback + ): + steps = feedback.get("steps", []) + executed = {step["step_index"] for step in steps} previous = { - 'status': feedback['status'], - 'failure_index': feedback.get('failure_index'), - 'successful_steps': [{'step_index': s['step_index'], 'tool': s['call']['tool']} - for s in steps if s['status'] == 'success'], - 'failed_steps': [{'step_index': s['step_index'], 'tool': s['call']['tool'], 'status': s['status']} - for s in steps if s['status'] != 'success'], - 'unexecuted_tail': [{'step_index': i, 'tool': call['tool']} - for i, call in enumerate(feedback['plan']['program']) if i not in executed], + "status": feedback["status"], + "failure_index": feedback.get("failure_index"), + "successful_steps": [ + {"step_index": s["step_index"], "tool": s["call"]["tool"]} + for s in steps + if s["status"] == "success" + ], + "failed_steps": [ + {"step_index": s["step_index"], "tool": s["call"]["tool"], "status": s["status"]} + for s in steps + if s["status"] != "success" + ], + "unexecuted_tail": [ + {"step_index": i, "tool": call["tool"]} + for i, call in enumerate(feedback["plan"]["program"]) + if i not in executed + ], + } + return json_snapshot( + { + "previous_program": previous, + "classification_completed": bool( + previous + and previous["status"] == "terminated" + and feedback.get("terminated") is True + and feedback.get("steps") + and feedback["steps"][-1]["status"] == "success" + ), + "remaining_budget": budget, + "comparison_failures": state.get("comparison_failure_ledger", []), + "invalidations": feedback.get("invalidations", []) if previous else [], + "observed_state_keys": sorted(state), + "state_rule": "Observed keys indicate presence only; neither presence nor historical success verifies readiness. Removed invalidated outputs are not available in current state.", + "availability_observations": [ + {k: entry[k] for k in ("scope", "type", "status", "skill") if k in entry} + for entry in state.get("availability_ledger", []) + ], + "availability_rule": "These are recorded observations, not new checks. Missing observations remain unknown/unqueried; omitted batch attributes remain unknown. Obtained and canonical unavailable are distinct; error is retryable and does not establish absence. Target details remain in actual public state.", + "tail_rule": "Unexecuted tail is historical intent only, without arguments; choose a new whole Program autonomously using current state and contracts.", + "task_reminder": "Consider the remaining complete classification task within the actual global budget. Only a validated successful terminal completes classification. A successful recovery step alone may leave the task unfinished, especially on the last available Program. Partial legal Programs remain allowed; no steps or extra budget are supplied.", } - return json_snapshot({ - 'previous_program': previous, - 'classification_completed': bool(previous and previous['status'] == 'terminated' - and feedback.get('terminated') is True - and feedback.get('steps') - and feedback['steps'][-1]['status'] == 'success'), - 'remaining_budget': budget, - 'comparison_failures': state.get('comparison_failure_ledger', []), - 'invalidations': feedback.get('invalidations', []) if previous else [], - 'observed_state_keys': sorted(state), - 'state_rule': 'Observed keys indicate presence only; neither presence nor historical success verifies readiness. Removed invalidated outputs are not available in current state.', - 'availability_observations': [{k: entry[k] for k in ('scope', 'type', 'status', 'skill') if k in entry} - for entry in state.get('availability_ledger', [])], - 'availability_rule': 'These are recorded observations, not new checks. Missing observations remain unknown/unqueried; omitted batch attributes remain unknown. Obtained and canonical unavailable are distinct; error is retryable and does not establish absence. Target details remain in actual public state.', - 'tail_rule': 'Unexecuted tail is historical intent only, without arguments; choose a new whole Program autonomously using current state and contracts.', - 'task_reminder': 'Consider the remaining complete classification task within the actual global budget. Only a validated successful terminal completes classification. A successful recovery step alone may leave the task unfinished, especially on the last available Program. Partial legal Programs remain allowed; no steps or extra budget are supplied.', - }) + ) diff --git a/research/finance_program_v1/evaluation/runtime/program_loop/rejection_context.py b/research/finance_program_v1/evaluation/runtime/program_loop/rejection_context.py index a75322b..c0f1dbc 100644 --- a/research/finance_program_v1/evaluation/runtime/program_loop/rejection_context.py +++ b/research/finance_program_v1/evaluation/runtime/program_loop/rejection_context.py @@ -1,36 +1,54 @@ """Read-only summary of unexecuted model intent; never execution evidence.""" + import json import math from .validation import _unique_object + def _reject_constant(value): - raise ValueError(f'nonfinite JSON {value}') + raise ValueError(f"nonfinite JSON {value}") + def _finite_float(value): number = float(value) if not math.isfinite(number): - raise ValueError('nonfinite JSON number') + raise ValueError("nonfinite JSON number") return number + def rejected_program_summary(raw, catalog, max_steps): if not isinstance(raw, str): return None try: - value = json.loads(raw, object_pairs_hook=_unique_object, parse_constant=_reject_constant, parse_float=_finite_float) + value = json.loads( + raw, + object_pairs_hook=_unique_object, + parse_constant=_reject_constant, + parse_float=_finite_float, + ) except (ValueError, TypeError, RecursionError): return None - if not isinstance(value, dict) or set(value) != {'program'}: + if not isinstance(value, dict) or set(value) != {"program"}: return None - steps = value['program'] + steps = value["program"] if not isinstance(steps, list) or not steps: return None tools = [] for item in steps: - if not isinstance(item, dict) or set(item) != {'tool','arguments'}: + if not isinstance(item, dict) or set(item) != {"tool", "arguments"}: return None - name = item['tool'] - if not isinstance(name, str) or name not in catalog or not isinstance(item['arguments'], dict): + name = item["tool"] + if ( + not isinstance(name, str) + or name not in catalog + or not isinstance(item["arguments"], dict) + ): return None tools.append(name) - return {'executed':False,'trusted':False,'step_count':len(steps), - 'max_program_steps':max_steps,'tool_sequence':tools} + return { + "executed": False, + "trusted": False, + "step_count": len(steps), + "max_program_steps": max_steps, + "tool_sequence": tools, + } diff --git a/research/finance_program_v1/evaluation/runtime/program_loop/validation.py b/research/finance_program_v1/evaluation/runtime/program_loop/validation.py index eec0160..1020ae1 100644 --- a/research/finance_program_v1/evaluation/runtime/program_loop/validation.py +++ b/research/finance_program_v1/evaluation/runtime/program_loop/validation.py @@ -1,31 +1,67 @@ +# 静态验Program形状、规范引用与依赖可能性;真实数据/guard另在执行时验证。 """Validate possible dependencies, never pretend a future retrieval succeeded.""" import json from .contracts import Program, ToolCall from pool_metadata import FIELDS from pool_runtime import SEMANTIC_KEYS, ALIGNMENT_KEYS -SELECTION = {"category", "aligned_category", "candidate_category", "category_candidate", "aligned_standard_entry", "grading_level", "grading_level_candidate", "final_evidence_state", "final_result"} +SELECTION = { + "category", + "aligned_category", + "candidate_category", + "category_candidate", + "aligned_standard_entry", + "grading_level", + "grading_level_candidate", + "final_evidence_state", + "final_result", +} GRADE = {"grading_level", "grading_level_candidate", "final_evidence_state", "final_result"} -EVIDENCE_BUNDLES = {"semantic_query", "semantic_evidence", "current_semantic_state", "current_evidence", "current_evidence_state", "all_available_evidence", "available_evidence", "evidence", "evidence_set"} -FINAL_EVIDENCE_REQUIREMENTS = frozenset({"grading_level", "category", "aligned_standard_entry", "standard_candidates"}) -RAW_CONTEXT = set(FIELDS) | {"table_fields", "selected_context_fields", "context_fields", "context_field_descriptions", - "context_field_types", "context_field_values", "table_context", "database_context", - "acquired_metadata"} +EVIDENCE_BUNDLES = { + "semantic_query", + "semantic_evidence", + "current_semantic_state", + "current_evidence", + "current_evidence_state", + "all_available_evidence", + "available_evidence", + "evidence", + "evidence_set", +} +FINAL_EVIDENCE_REQUIREMENTS = frozenset( + {"grading_level", "category", "aligned_standard_entry", "standard_candidates"} +) +RAW_CONTEXT = set(FIELDS) | { + "table_fields", + "selected_context_fields", + "context_fields", + "context_field_descriptions", + "context_field_types", + "context_field_values", + "table_context", + "database_context", + "acquired_metadata", +} def _unique_object(pairs): result = {} for key, value in pairs: - if key in result: raise ValueError(f"duplicate JSON key {key}") + if key in result: + raise ValueError(f"duplicate JSON key {key}") result[key] = value return result def canonical_reference(key, available): - if key == "current_record": return "$record" - if key == "domain": return "$domain" - if key in ("field_name", "target_field"): return "$metadata.field_name" - if key == "candidate_standard_categories" and "standard_candidates" in available: return "$state.standard_candidates" + if key == "current_record": + return "$record" + if key == "domain": + return "$domain" + if key in ("field_name", "target_field"): + return "$metadata.field_name" + if key == "candidate_standard_categories" and "standard_candidates" in available: + return "$state.standard_candidates" return "$state." + key if key in available else None @@ -33,7 +69,11 @@ def canonical_reference(key, available): def explicit_value_policy(reference): - return "canonical_reference_only" if reference and reference.startswith("$state.") else "initial_binding_contract" + return ( + "canonical_reference_only" + if reference and reference.startswith("$state.") + else "initial_binding_contract" + ) def possible_outputs(spec): @@ -45,33 +85,71 @@ def possible_outputs(spec): outputs.update(EVIDENCE_BUNDLES | {"available_metadata_evidence"}) if any(key.startswith(("field_", "disambiguated_", "value_")) for key in semantic): outputs.add("available_field_evidence") - if any(key.startswith("context_") for key in semantic): outputs.add("context_field_evidence") - if any(key.startswith("table_") for key in semantic): outputs.add("available_table_evidence") - if any(key.startswith("database_") for key in semantic): outputs.add("available_database_evidence") + if any(key.startswith("context_") for key in semantic): + outputs.add("context_field_evidence") + if any(key.startswith("table_") for key in semantic): + outputs.add("available_table_evidence") + if any(key.startswith("database_") for key in semantic): + outputs.add("available_database_evidence") if alignment: - outputs.update(("standard_alignment_evidence", "aligned_standard_candidates", "conflicting_standard_alignments")) - if "context_field_semantics" in produced: outputs.add("context_semantics") - if "field_semantics" in produced: outputs.add("candidate_field_semantics") + outputs.update( + ( + "standard_alignment_evidence", + "aligned_standard_candidates", + "conflicting_standard_alignments", + ) + ) + if "context_field_semantics" in produced: + outputs.add("context_semantics") + if "field_semantics" in produced: + outputs.add("candidate_field_semantics") if "field_metadata" in produced: - outputs.update((*FIELDS, "current_metadata", "available_metadata", "semantic_query", "available_evidence", "all_available_evidence")) + outputs.update( + ( + *FIELDS, + "current_metadata", + "available_metadata", + "semantic_query", + "available_evidence", + "all_available_evidence", + ) + ) if "acquired_metadata" in produced: outputs.update(FIELDS) - if "metadata_availability" in produced or produced & (set(FIELDS) | {"field_metadata", "acquired_metadata"}): - outputs.update(("current_metadata", "available_metadata", "missing_metadata_types", "missing_metadata_type")) - if "category" in produced: outputs.update(("aligned_category", "candidate_category", "category_candidate")) - if "standard_candidates" in produced: outputs.update(("candidate_standard_categories", "candidate_categories", "previous_standard_results")) - if "grading_level" in produced: outputs.add("grading_level_candidate") + if "metadata_availability" in produced or produced & ( + set(FIELDS) | {"field_metadata", "acquired_metadata"} + ): + outputs.update( + ( + "current_metadata", + "available_metadata", + "missing_metadata_types", + "missing_metadata_type", + ) + ) + if "category" in produced: + outputs.update(("aligned_category", "candidate_category", "category_candidate")) + if "standard_candidates" in produced: + outputs.update( + ("candidate_standard_categories", "candidate_categories", "previous_standard_results") + ) + if "grading_level" in produced: + outputs.add("grading_level_candidate") return outputs def advance_available(spec, available): available = set(available) produced = set(spec.produces) - if produced & (set(SEMANTIC_KEYS) | set(ALIGNMENT_KEYS) | RAW_CONTEXT | {"field_metadata"}): available -= SELECTION - if "standard_candidates" in produced: available -= SELECTION - if "category" in produced: available -= GRADE + if produced & (set(SEMANTIC_KEYS) | set(ALIGNMENT_KEYS) | RAW_CONTEXT | {"field_metadata"}): + available -= SELECTION + if "standard_candidates" in produced: + available -= SELECTION + if "category" in produced: + available -= GRADE available.update(possible_outputs(spec)) - if FINAL_EVIDENCE_REQUIREMENTS <= available: available.add("final_evidence_state") + if FINAL_EVIDENCE_REQUIREMENTS <= available: + available.add("final_evidence_state") return available @@ -79,33 +157,68 @@ def parse_program(raw, catalog, state, max_steps): """ Parse a program from raw JSON text. """ - if not isinstance(raw, str): raise ValueError("Planner must return JSON text") - value = json.loads(raw, object_pairs_hook=_unique_object, parse_constant=lambda v: (_ for _ in ()).throw(ValueError(f"nonfinite JSON {v}"))) - if not isinstance(value, dict) or set(value) != {"program"}: raise ValueError("Expected exactly one JSON Program object") + if not isinstance(raw, str): + raise ValueError("Planner must return JSON text") + value = json.loads( + raw, + object_pairs_hook=_unique_object, + parse_constant=lambda v: (_ for _ in ()).throw(ValueError(f"nonfinite JSON {v}")), + ) + if not isinstance(value, dict) or set(value) != {"program"}: + raise ValueError("Expected exactly one JSON Program object") steps = value["program"] - if not isinstance(steps, list) or not steps: raise ValueError("Program must be nonempty") - if len(steps) > max_steps: raise ValueError("Program length exceeds max_program_steps") + if not isinstance(steps, list) or not steps: + raise ValueError("Program must be nonempty") + if len(steps) > max_steps: + raise ValueError("Program length exceeds max_program_steps") available = set(state) - calls:list[ToolCall] = [] + calls: list[ToolCall] = [] for index, item in enumerate(steps): - if not isinstance(item, dict) or set(item) != {"tool", "arguments"}: raise ValueError(f"step {index}: expected only tool and arguments") + if not isinstance(item, dict) or set(item) != {"tool", "arguments"}: + raise ValueError(f"step {index}: expected only tool and arguments") name, args = item["tool"], item["arguments"] - if not isinstance(name, str) or name not in catalog: raise ValueError(f"step {index}: unknown Skill") + if not isinstance(name, str) or name not in catalog: + raise ValueError(f"step {index}: unknown Skill") spec = catalog[name] - if not isinstance(args, dict) or set(args) - set((*spec.required_inputs, *spec.optional_inputs)): raise ValueError(f"step {index}: unknown arguments") + if not isinstance(args, dict) or set(args) - set( + (*spec.required_inputs, *spec.optional_inputs) + ): + raise ValueError(f"step {index}: unknown arguments") for key in sorted(set(spec.required_inputs) | set(args)): reference = canonical_reference(key, available) - if reference is None: raise ValueError(f"step {index}: missing dependency {key}") + if reference is None: + raise ValueError(f"step {index}: missing dependency {key}") supplied = args.get(key) if name == "ACQUIRE_MISSING_METADATA" and key == "missing_metadata_type": - choices = state.get("missing_metadata_types") if "missing_metadata_types" in state else None - if not isinstance(supplied, str) or supplied not in FIELDS or supplied == "field_name" or (choices is not None and supplied not in choices): - raise ValueError(f"step {index}: missing_metadata_type must be an observed or conditionally missing metadata type") + choices = ( + state.get("missing_metadata_types") + if "missing_metadata_types" in state + else None + ) + if ( + not isinstance(supplied, str) + or supplied not in FIELDS + or supplied == "field_name" + or (choices is not None and supplied not in choices) + ): + raise ValueError( + f"step {index}: missing_metadata_type must be an observed or conditionally missing metadata type" + ) continue - if key in args and ((explicit_value_policy(reference) == "canonical_reference_only" and supplied != reference) - or (isinstance(supplied, str) and supplied.startswith("$") and supplied != reference)): - raise ValueError(f"step {index}: incorrect canonical reference for {key}; expected {reference}") - if spec.terminal and index != len(steps) - 1: raise ValueError(f"step {index}: terminal Skill must be last") + if key in args and ( + ( + explicit_value_policy(reference) == "canonical_reference_only" + and supplied != reference + ) + or ( + isinstance(supplied, str) and supplied.startswith("$") and supplied != reference + ) + ): + raise ValueError( + f"step {index}: incorrect canonical reference for {key}; expected {reference}" + ) + if spec.terminal and index != len(steps) - 1: + raise ValueError(f"step {index}: terminal Skill must be last") available = advance_available(spec, available) calls.append(ToolCall(name, args)) return Program(tuple(calls)) diff --git a/research/finance_program_v1/evaluation/runtime/vendor/pool_catalog.py b/research/finance_program_v1/evaluation/runtime/vendor/pool_catalog.py index 4fd6b2d..e106952 100644 --- a/research/finance_program_v1/evaluation/runtime/vendor/pool_catalog.py +++ b/research/finance_program_v1/evaluation/runtime/vendor/pool_catalog.py @@ -1,111 +1,159 @@ """Frozen P14/F66 interfaces and one-time separate contract installation.""" + from pathlib import Path from dataclasses import replace import json from agent.orchestration.catalog import SkillSpec, default_catalog, dynamic_loop_catalog ROOT = Path(__file__).resolve().parent -REFERENCE = json.loads((ROOT/'skill_reference.json').read_text(encoding='utf-8')) -NAMES = json.loads((ROOT/'reference_skills_63.json').read_text(encoding='utf-8')) -SHARED = dynamic_loop_catalog(include_field_metadata=True, include_description_skills=True, two_stage=True) -SEARCH_NAMES = ('SEARCH_STANDARD','SEARCH_STANDARD_BY_FIELD','SEARCH_STANDARD_BY_CONTEXT','SEARCH_STANDARD_BY_TABLE','SEARCH_STANDARD_BY_DATABASE','RESEARCH_STANDARD') +REFERENCE = json.loads((ROOT / "skill_reference.json").read_text(encoding="utf-8")) +NAMES = json.loads((ROOT / "reference_skills_63.json").read_text(encoding="utf-8")) +SHARED = dynamic_loop_catalog( + include_field_metadata=True, include_description_skills=True, two_stage=True +) +SEARCH_NAMES = ( + "SEARCH_STANDARD", + "SEARCH_STANDARD_BY_FIELD", + "SEARCH_STANDARD_BY_CONTEXT", + "SEARCH_STANDARD_BY_TABLE", + "SEARCH_STANDARD_BY_DATABASE", + "RESEARCH_STANDARD", +) OUTPUTS = { - 'GET_FIELD_DESCRIPTION':'field_description','GET_TABLE_DESCRIPTION':'table_description', - 'GET_DATABASE_DESCRIPTION':'database_description','GET_TABLE_FIELDS':'table_fields', - 'GET_CONTEXT_FIELD_DESCRIPTIONS':'context_field_descriptions','GET_CONTEXT_FIELD_TYPES':'context_field_types', - 'GET_CONTEXT_FIELD_VALUES':'context_field_values','SELECT_CONTEXT_FIELDS':'selected_context_fields', - 'EXPAND_SELECTED_CONTEXT':'context_fields','GET_COMPLETE_TABLE_CONTEXT':'table_context', - 'GET_COMPLETE_DATABASE_CONTEXT':'database_context','ACQUIRE_MISSING_METADATA':'acquired_metadata', - 'INTERPRET_FIELD_TYPE':'field_type_semantics','INTERPRET_FIELD_VALUE':'value_semantics', - 'EXPAND_TABLE_ABBREVIATION':'table_abbreviation_semantics','EXPAND_DATABASE_ABBREVIATION':'database_abbreviation_semantics', - 'INTERPRET_DATABASE_NAME':'database_semantics','INTERPRET_DATABASE_DESCRIPTION':'database_description_semantics', - 'REFINE_STANDARD_QUERY':'refined_semantic_query','SUMMARIZE_STANDARD_EVIDENCE':'standard_evidence_summary', - 'FUSE_FIELD_EVIDENCE':'field_evidence','FUSE_CONTEXT_EVIDENCE':'context_evidence', - 'FUSE_TABLE_EVIDENCE':'table_evidence','FUSE_DATABASE_EVIDENCE':'database_evidence', - 'FUSE_METADATA_EVIDENCE':'metadata_evidence','FUSE_STANDARD_EVIDENCE':'standard_evidence', - 'WEIGH_EVIDENCE':'evidence_weights','RESOLVE_FIELD_CONTEXT_CONFLICT':'field_context_resolution', - 'RESOLVE_METADATA_CONFLICT':'metadata_conflict_resolution','RESOLVE_STANDARD_CONFLICT':'standard_conflict_resolution', - 'ASSESS_CATEGORY_SUPPORT':'category_support','COMPARE_CATEGORY_HYPOTHESES':'category_comparison', - 'IDENTIFY_MISSING_EVIDENCE':'missing_evidence','DECIDE_NEXT_EVIDENCE_SOURCE':'next_evidence_source', - 'VERIFY_CATEGORY_WITH_STANDARD':'category_verification', - 'VERIFY_CLASSIFICATION_GRADING_CONSISTENCY':'grading_consistency', + "GET_FIELD_DESCRIPTION": "field_description", + "GET_TABLE_DESCRIPTION": "table_description", + "GET_DATABASE_DESCRIPTION": "database_description", + "GET_TABLE_FIELDS": "table_fields", + "GET_CONTEXT_FIELD_DESCRIPTIONS": "context_field_descriptions", + "GET_CONTEXT_FIELD_TYPES": "context_field_types", + "GET_CONTEXT_FIELD_VALUES": "context_field_values", + "SELECT_CONTEXT_FIELDS": "selected_context_fields", + "EXPAND_SELECTED_CONTEXT": "context_fields", + "GET_COMPLETE_TABLE_CONTEXT": "table_context", + "GET_COMPLETE_DATABASE_CONTEXT": "database_context", + "ACQUIRE_MISSING_METADATA": "acquired_metadata", + "INTERPRET_FIELD_TYPE": "field_type_semantics", + "INTERPRET_FIELD_VALUE": "value_semantics", + "EXPAND_TABLE_ABBREVIATION": "table_abbreviation_semantics", + "EXPAND_DATABASE_ABBREVIATION": "database_abbreviation_semantics", + "INTERPRET_DATABASE_NAME": "database_semantics", + "INTERPRET_DATABASE_DESCRIPTION": "database_description_semantics", + "REFINE_STANDARD_QUERY": "refined_semantic_query", + "SUMMARIZE_STANDARD_EVIDENCE": "standard_evidence_summary", + "FUSE_FIELD_EVIDENCE": "field_evidence", + "FUSE_CONTEXT_EVIDENCE": "context_evidence", + "FUSE_TABLE_EVIDENCE": "table_evidence", + "FUSE_DATABASE_EVIDENCE": "database_evidence", + "FUSE_METADATA_EVIDENCE": "metadata_evidence", + "FUSE_STANDARD_EVIDENCE": "standard_evidence", + "WEIGH_EVIDENCE": "evidence_weights", + "RESOLVE_FIELD_CONTEXT_CONFLICT": "field_context_resolution", + "RESOLVE_METADATA_CONFLICT": "metadata_conflict_resolution", + "RESOLVE_STANDARD_CONFLICT": "standard_conflict_resolution", + "ASSESS_CATEGORY_SUPPORT": "category_support", + "COMPARE_CATEGORY_HYPOTHESES": "category_comparison", + "IDENTIFY_MISSING_EVIDENCE": "missing_evidence", + "DECIDE_NEXT_EVIDENCE_SOURCE": "next_evidence_source", + "VERIFY_CATEGORY_WITH_STANDARD": "category_verification", + "VERIFY_CLASSIFICATION_GRADING_CONSISTENCY": "grading_consistency", } def _inputs(text): - return () if text in ('','无') else tuple(v.strip() for v in text.split(',')) + return () if text in ("", "无") else tuple(v.strip() for v in text.split(",")) def pool_catalog(pool: str): - if pool not in ('P14','F66'): - raise ValueError('pool must be P14 or F66') - if pool=='P14': + if pool not in ("P14", "F66"): + raise ValueError("pool must be P14 or F66") + if pool == "P14": return dict(SHARED) - legacy=default_catalog() - result={} - for role,names in NAMES.items(): - if not isinstance(names,list): + legacy = default_catalog() + result = {} + for role, names in NAMES.items(): + if not isinstance(names, list): continue for name in names: if name in SHARED: - result[name]=SHARED[name] + result[name] = SHARED[name] elif name in legacy: - result[name]=legacy[name] - if name=='SYNTHESIZE_METADATA_SEMANTICS': - result[name]=replace(result[name],optional_inputs=_inputs(REFERENCE[name]['optional'])) + result[name] = legacy[name] + if name == "SYNTHESIZE_METADATA_SEMANTICS": + result[name] = replace( + result[name], optional_inputs=_inputs(REFERENCE[name]["optional"]) + ) else: - ref=REFERENCE[name] - produced='standard_candidates' if name in SEARCH_NAMES else OUTPUTS.get(name,name.lower()) - result[name]=SkillSpec(name,role,_inputs(ref['required']),_inputs(ref['optional']),(produced,)) + ref = REFERENCE[name] + produced = ( + "standard_candidates" + if name in SEARCH_NAMES + else OUTPUTS.get(name, name.lower()) + ) + result[name] = SkillSpec( + name, role, _inputs(ref["required"]), _inputs(ref["optional"]), (produced,) + ) result.update(SHARED) return result def purpose(name): if name in REFERENCE: - return REFERENCE[name]['purpose'] + return REFERENCE[name]["purpose"] return { - 'GET_FIELD_METADATA':'Retrieve actual allowlisted metadata for the privately identified target record.', - 'SELECT_CATEGORY_TOPK':'Rank exactly five actual frozen Registry options by supplied evidence.', - 'INFER_CATEGORY_FROM_TOPK':'Select one actual prior Top-5 option and bind its frozen standard entry.' + "GET_FIELD_METADATA": "Retrieve actual allowlisted metadata for the privately identified target record.", + "SELECT_CATEGORY_TOPK": "Rank exactly five actual frozen Registry options by supplied evidence.", + "INFER_CATEGORY_FROM_TOPK": "Select one actual prior Top-5 option and bind its frozen standard entry.", }[name] def install_contracts(skill_root): """Explicit pre-freeze action; creates missing contracts, never edits existing files.""" - destination=Path(skill_root)/'full_pool' - existing=[p for p in (ROOT/'runtime/skills').rglob('*.md') if 'full_pool' not in p.parts] - patches=[] - for name,spec in pool_catalog('F66').items(): - target=destination/f'{spec.role}_{name}.md' + destination = Path(skill_root) / "full_pool" + existing = [p for p in (ROOT / "runtime/skills").rglob("*.md") if "full_pool" not in p.parts] + patches = [] + for name, spec in pool_catalog("F66").items(): + target = destination / f"{spec.role}_{name}.md" if target.exists(): continue - source=next((p for p in existing if p.name==target.name and ('neighbor_extra' not in p.parts)),None) - if source is not None and name!='SYNTHESIZE_METADATA_SEMANTICS': - content=source.read_bytes().decode('utf-8') + source = next( + (p for p in existing if p.name == target.name and ("neighbor_extra" not in p.parts)), + None, + ) + if source is not None and name != "SYNTHESIZE_METADATA_SEMANTICS": + content = source.read_bytes().decode("utf-8") else: - header='\n'.join([ - '---',f'name: {name}',f'dsl: {spec.role}', - f'required_inputs: [{", ".join(spec.required_inputs)}]', - f'optional_inputs: [{", ".join(spec.optional_inputs)}]', - f'produces: [{", ".join(spec.produces)}]',f'terminal: {str(spec.terminal).lower()}','---','', - ]) - ref=REFERENCE[name] - body=f'# {name}\n\nPurpose: {purpose(name)}\n\nObservation: {ref["output"]}\n\n' - boundaries={ - 'metadata_acquisition':'Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage.', - 'semantic_interpretation':'Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata.', - 'standard_alignment':'Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state.', - 'evidence_reasoning':'Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state.' + header = "\n".join( + [ + "---", + f"name: {name}", + f"dsl: {spec.role}", + f'required_inputs: [{", ".join(spec.required_inputs)}]', + f'optional_inputs: [{", ".join(spec.optional_inputs)}]', + f'produces: [{", ".join(spec.produces)}]', + f"terminal: {str(spec.terminal).lower()}", + "---", + "", + ] + ) + ref = REFERENCE[name] + body = f'# {name}\n\nPurpose: {purpose(name)}\n\nObservation: {ref["output"]}\n\n' + boundaries = { + "metadata_acquisition": "Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage.", + "semantic_interpretation": "Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata.", + "standard_alignment": "Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state.", + "evidence_reasoning": "Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state.", } - body+=boundaries[spec.role]+'\n\nReturn exactly {"summary": "nonempty natural-language observation", "data": {...}}. ' - body+=f'Data keys must be exactly {json.dumps(spec.produces)}. ' - body+='Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys.\n' - content=header+body - patches.append((target,content)) + body += ( + boundaries[spec.role] + + '\n\nReturn exactly {"summary": "nonempty natural-language observation", "data": {...}}. ' + ) + body += f"Data keys must be exactly {json.dumps(spec.produces)}. " + body += "Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys.\n" + content = header + body + patches.append((target, content)) # Runtime contract installation is an explicit artifact generation operation. - destination.mkdir(parents=True,exist_ok=True) - for target,content in patches: - with target.open('xb') as stream: - stream.write(content.encode('utf-8')) + destination.mkdir(parents=True, exist_ok=True) + for target, content in patches: + with target.open("xb") as stream: + stream.write(content.encode("utf-8")) return destination diff --git a/research/finance_program_v1/evaluation/runtime/vendor/pool_runtime.py b/research/finance_program_v1/evaluation/runtime/vendor/pool_runtime.py index 2fdeb0b..ee74b5b 100644 --- a/research/finance_program_v1/evaluation/runtime/vendor/pool_runtime.py +++ b/research/finance_program_v1/evaluation/runtime/vendor/pool_runtime.py @@ -1,15 +1,27 @@ """Common dynamic controller, scoped metadata paths and native semantic execution.""" + import json from collections.abc import Mapping from dataclasses import replace from pathlib import Path -from agent.orchestration.agent_loop import (AgentLoopController, LoopConfig, LoopState, PolicyDecision, - ActionError, parse_policy_action, build_final_evidence_state) +from agent.orchestration.agent_loop import ( + AgentLoopController, + LoopConfig, + LoopState, + PolicyDecision, + ActionError, + parse_policy_action, + build_final_evidence_state, +) from agent.orchestration.category_catalog import CategoryCatalog from agent.orchestration.contracts import ToolCall -from agent.orchestration.model_skill_executor import (ModelSkillExecutor, SkillExecutionError, - parse_skill_observation, _generation_metadata) +from agent.orchestration.model_skill_executor import ( + ModelSkillExecutor, + SkillExecutionError, + parse_skill_observation, + _generation_metadata, +) from agent.orchestration.runtime import Observation from agent.orchestration.skill_loader import SkillLoader from pool_catalog import ROOT, pool_catalog, purpose, SEARCH_NAMES @@ -17,548 +29,1026 @@ from pool_bindings import bind_call, BINDING_RULE_VERSION from comparison_output import parse_comparison_output, ComparisonOutputError, MAX_REASON_LENGTH from evidence_roles import acquired_source, evidence_roles -from grounded_semantics import TARGETS as GROUNDED_TARGETS, valid_shape as grounded_shape, make_messages as grounded_messages, validate_observation as validate_grounded +from grounded_semantics import ( + TARGETS as GROUNDED_TARGETS, + valid_shape as grounded_shape, + make_messages as grounded_messages, + validate_observation as validate_grounded, +) -POLICY_SYSTEM = '''You are a database-field classification orchestration policy. +POLICY_SYSTEM = """You are a database-field classification orchestration policy. Choose exactly one currently callable Skill, using the global capability index to plan a minimum sufficient evidence program. Only domain and field_name are visible initially. Other raw metadata requires explicit acquisition; pending metadata is not evidence. Choose the Skill; the controller binds required state arguments. Omit controller-bound arguments, or supply their exact advertised references or strictly identical values. Explicit values are checked before normalization. ACQUIRE_MISSING_METADATA requires an explicit missing_metadata_type chosen from actual missing_metadata_types. Optional arguments may be supplied only when actually bound. Never use provenance source names as argument data. Never invent raw metadata, standard entries, labels or grading levels. Intermediate semantic strings are evidence, not acquired raw values. Stop acquiring when evidence is sufficient, select a supported category, confirm its frozen grade and finalize within the remaining budget. -Return exactly one JSON object: {"tool":"SKILL_NAME","arguments":{}}. No Program, Markdown, plain stop, or extra JSON.''' +Return exactly one JSON object: {"tool":"SKILL_NAME","arguments":{}}. No Program, Markdown, plain stop, or extra JSON.""" SEMANTIC_KEYS = ( - 'domain_semantics','field_abbreviation_semantics','field_semantics','disambiguated_field_semantics', - 'field_description_semantics','field_type_semantics','value_semantics','table_abbreviation_semantics', - 'table_semantics','table_description_semantics','database_abbreviation_semantics','database_semantics', - 'database_description_semantics','context_field_semantics','metadata_semantics', - 'field_evidence','context_evidence','table_evidence','database_evidence','metadata_evidence', + "domain_semantics", + "field_abbreviation_semantics", + "field_semantics", + "disambiguated_field_semantics", + "field_description_semantics", + "field_type_semantics", + "value_semantics", + "table_abbreviation_semantics", + "table_semantics", + "table_description_semantics", + "database_abbreviation_semantics", + "database_semantics", + "database_description_semantics", + "context_field_semantics", + "metadata_semantics", + "field_evidence", + "context_evidence", + "table_evidence", + "database_evidence", + "metadata_evidence", +) +ALIGNMENT_KEYS = ( + "field_standard_alignment", + "context_standard_alignment", + "table_standard_alignment", + "database_standard_alignment", + "value_standard_alignment", + "description_standard_alignment", + "standard_comparison", ) -ALIGNMENT_KEYS=('field_standard_alignment','context_standard_alignment','table_standard_alignment', - 'database_standard_alignment','value_standard_alignment','description_standard_alignment','standard_comparison') # Every validated, declared-type native output participates in the evidence # boundary, including refinement, conflict resolution and support assessments. -SEMANTIC_KEYS=tuple(dict.fromkeys((*SEMANTIC_KEYS,*(key for spec in pool_catalog('F66').values() - if spec.role in ('semantic_interpretation','evidence_reasoning') for key in spec.produces - if key not in ('category','grading_level','aligned_standard_entry','final_result'))))) -ALIGNMENT_KEYS=tuple(dict.fromkeys((*ALIGNMENT_KEYS,*(key for spec in pool_catalog('F66').values() - if spec.role=='standard_alignment' for key in spec.produces - if key not in ('standard_candidates','aligned_standard_entry'))))) +SEMANTIC_KEYS = tuple( + dict.fromkeys( + ( + *SEMANTIC_KEYS, + *( + key + for spec in pool_catalog("F66").values() + if spec.role in ("semantic_interpretation", "evidence_reasoning") + for key in spec.produces + if key + not in ("category", "grading_level", "aligned_standard_entry", "final_result") + ), + ) + ) +) +ALIGNMENT_KEYS = tuple( + dict.fromkeys( + ( + *ALIGNMENT_KEYS, + *( + key + for spec in pool_catalog("F66").values() + if spec.role == "standard_alignment" + for key in spec.produces + if key not in ("standard_candidates", "aligned_standard_entry") + ), + ) + ) +) -def valid_evidence_value(key,value): +def valid_evidence_value(key, value): if key in GROUNDED_TARGETS.values(): return grounded_shape(value) - if key=='evidence_sufficiency': - return (isinstance(value,Mapping) and set(value)=={'sufficient','rationale'} - and type(value['sufficient']) is bool - and isinstance(value['rationale'],str) and bool(value['rationale'].strip())) - return isinstance(value,str) and bool(value.strip()) + if key == "evidence_sufficiency": + return ( + isinstance(value, Mapping) + and set(value) == {"sufficient", "rationale"} + and type(value["sufficient"]) is bool + and isinstance(value["rationale"], str) + and bool(value["rationale"].strip()) + ) + return isinstance(value, str) and bool(value.strip()) -def validated_evidence_values(state,keys): - catalog=pool_catalog('F66');provenance=state.get('_provenance',{}) - return {key:state[key] for key in keys - if key in state and provenance.get(key) in catalog +def validated_evidence_values(state, keys): + catalog = pool_catalog("F66") + provenance = state.get("_provenance", {}) + return { + key: state[key] + for key in keys + if key in state + and provenance.get(key) in catalog and key in catalog[provenance[key]].produces - and valid_evidence_value(key,state[key])} + and valid_evidence_value(key, state[key]) + } -def acquired_raw(record,state): - provenance=state.get('_provenance',{}) - return {'field_name':record.field_name,**{k:state[k] for k in FIELDS - if k!='field_name' and acquired_source(k,provenance.get(k)) and present(state.get(k))}} +def acquired_raw(record, state): + provenance = state.get("_provenance", {}) + return { + "field_name": record.field_name, + **{ + k: state[k] + for k in FIELDS + if k != "field_name" and acquired_source(k, provenance.get(k)) and present(state.get(k)) + }, + } -def assemble_pool_evidence(record,state): +def assemble_pool_evidence(record, state): """Single allowlisted boundary for publication, model search and finalization.""" - provenance=state.get('_provenance',{}) - semantics=validated_evidence_values(state,SEMANTIC_KEYS) - alignments=validated_evidence_values(state,ALIGNMENT_KEYS) - observations={k:state[k] for k in ('table_fields','selected_context_fields','context_fields', - 'context_field_descriptions','context_field_types','context_field_values','table_context','database_context') - if acquired_source(k,provenance.get(k)) and present(state.get(k))} - metadata=acquired_raw(record,state) if record is not None else dict(state.get('current_metadata',{})) - names=set(metadata)|set(semantics)|set(alignments)|set(observations) - prior=state.get('available_evidence',{}) - return {'domain':record.domain if record is not None else prior.get('domain'), - 'field_name':record.field_name if record is not None else metadata.get('field_name'), - 'metadata':metadata,'semantics':semantics,'alignments':alignments,'observations':observations, - 'provenance':{k:provenance[k] for k in sorted(names) if k in provenance}, - 'roles':evidence_roles(metadata,semantics,alignments,observations,provenance)} - - -def pool_final_evidence(record,state): - final=build_final_evidence_state(state) + provenance = state.get("_provenance", {}) + semantics = validated_evidence_values(state, SEMANTIC_KEYS) + alignments = validated_evidence_values(state, ALIGNMENT_KEYS) + observations = { + k: state[k] + for k in ( + "table_fields", + "selected_context_fields", + "context_fields", + "context_field_descriptions", + "context_field_types", + "context_field_values", + "table_context", + "database_context", + ) + if acquired_source(k, provenance.get(k)) and present(state.get(k)) + } + metadata = ( + acquired_raw(record, state) + if record is not None + else dict(state.get("current_metadata", {})) + ) + names = set(metadata) | set(semantics) | set(alignments) | set(observations) + prior = state.get("available_evidence", {}) + return { + "domain": record.domain if record is not None else prior.get("domain"), + "field_name": record.field_name if record is not None else metadata.get("field_name"), + "metadata": metadata, + "semantics": semantics, + "alignments": alignments, + "observations": observations, + "provenance": {k: provenance[k] for k in sorted(names) if k in provenance}, + "roles": evidence_roles(metadata, semantics, alignments, observations, provenance), + } + + +def pool_final_evidence(record, state): + final = build_final_evidence_state(state) if final is not None: - evidence=assemble_pool_evidence(record,state) - final['semantic_evidence']={**evidence['semantics'],**evidence['alignments']} - final['available_evidence']=evidence + evidence = assemble_pool_evidence(record, state) + final["semantic_evidence"] = {**evidence["semantics"], **evidence["alignments"]} + final["available_evidence"] = evidence return final -def publish_state(record,state,data,skill): +def publish_state(record, state, data, skill): """Publish only typed observed data and explicit evidence bundles, with provenance.""" - spec=pool_catalog('F66').get(skill) - if spec is None or not set(data)<=set(spec.produces): - raise SkillExecutionError('publication contains undeclared outputs or unknown Skill') - for key,value in data.items(): - if key in (*SEMANTIC_KEYS,*ALIGNMENT_KEYS) and not valid_evidence_value(key,value): - raise SkillExecutionError(f'{key} violates its declared evidence type') + spec = pool_catalog("F66").get(skill) + if spec is None or not set(data) <= set(spec.produces): + raise SkillExecutionError("publication contains undeclared outputs or unknown Skill") + for key, value in data.items(): + if key in (*SEMANTIC_KEYS, *ALIGNMENT_KEYS) and not valid_evidence_value(key, value): + raise SkillExecutionError(f"{key} violates its declared evidence type") state.update(data) - provenance=state.setdefault('_provenance',{}) - provenance.update({k:skill for k in data}) - if isinstance(data.get('metadata_availability'),Mapping): - state['current_metadata']=acquired_raw(record,state) - state['available_metadata']={'domain':record.domain,**state['current_metadata']} - missing=data['metadata_availability'].get('missing',[]) - state['missing_metadata_types']=[k for k in missing if k in FIELDS] - if state['missing_metadata_types']: - state['missing_metadata_type']=state['missing_metadata_types'][0] - provenance['missing_metadata_type']=skill + provenance = state.setdefault("_provenance", {}) + provenance.update({k: skill for k in data}) + if isinstance(data.get("metadata_availability"), Mapping): + state["current_metadata"] = acquired_raw(record, state) + state["available_metadata"] = {"domain": record.domain, **state["current_metadata"]} + missing = data["metadata_availability"].get("missing", []) + state["missing_metadata_types"] = [k for k in missing if k in FIELDS] + if state["missing_metadata_types"]: + state["missing_metadata_type"] = state["missing_metadata_types"][0] + provenance["missing_metadata_type"] = skill else: - state.pop('missing_metadata_type',None) - provenance.pop('missing_metadata_type',None) - raw={} - for key in ('field_metadata','acquired_metadata'): - value=data.get(key) - if isinstance(value,Mapping): - raw.update({k:v for k,v in value.items() if k in FIELDS and present(v)}) - if skill.startswith('GET_'): - raw.update({k:v for k,v in data.items() if k in FIELDS and present(v)}) - for key,value in raw.items(): - state[key]=value; provenance[key]=skill + state.pop("missing_metadata_type", None) + provenance.pop("missing_metadata_type", None) + raw = {} + for key in ("field_metadata", "acquired_metadata"): + value = data.get(key) + if isinstance(value, Mapping): + raw.update({k: v for k, v in value.items() if k in FIELDS and present(v)}) + if skill.startswith("GET_"): + raw.update({k: v for k, v in data.items() if k in FIELDS and present(v)}) + for key, value in raw.items(): + state[key] = value + provenance[key] = skill if raw: # Initial field_name belongs to the record, not necessarily to state. # Publish the same acquired-only boundary consumed by the executor. - state['current_metadata']=acquired_raw(record,state) - state['available_metadata']={'domain':record.domain,**state['current_metadata']} - state['missing_metadata_types']=[k for k in FIELDS if k not in state['current_metadata']] - if state['missing_metadata_types']: - state['missing_metadata_type']=state['missing_metadata_types'][0] - provenance['missing_metadata_type']=skill + state["current_metadata"] = acquired_raw(record, state) + state["available_metadata"] = {"domain": record.domain, **state["current_metadata"]} + state["missing_metadata_types"] = [k for k in FIELDS if k not in state["current_metadata"]] + if state["missing_metadata_types"]: + state["missing_metadata_type"] = state["missing_metadata_types"][0] + provenance["missing_metadata_type"] = skill else: - state.pop('missing_metadata_type',None) - provenance.pop('missing_metadata_type',None) - aliases={'context_field_semantics':'context_semantics','field_semantics':'candidate_field_semantics', - 'category':'aligned_category','grading_level':'grading_level_candidate'} - for original,alias in aliases.items(): + state.pop("missing_metadata_type", None) + provenance.pop("missing_metadata_type", None) + aliases = { + "context_field_semantics": "context_semantics", + "field_semantics": "candidate_field_semantics", + "category": "aligned_category", + "grading_level": "grading_level_candidate", + } + for original, alias in aliases.items(): if original in state and present(state[original]): - state[alias]=state[original]; provenance[alias]=provenance.get(original,skill) - if 'category' in state: - for alias in ('candidate_category','category_candidate'): - state[alias]=state['category']; provenance[alias]=provenance.get('category',skill) - if isinstance(state.get('standard_candidates'),list) and state['standard_candidates']: - for alias in ('candidate_standard_categories','candidate_categories','previous_standard_results'): - state[alias]=state['standard_candidates']; provenance[alias]=provenance.get('standard_candidates',skill) - semantics=validated_evidence_values(state,SEMANTIC_KEYS) - alignments=validated_evidence_values(state,ALIGNMENT_KEYS) - groups={ - 'available_field_evidence':{k:v for k,v in semantics.items() if k.startswith(('field_','disambiguated_','value_'))}, - 'context_field_evidence':{k:v for k,v in semantics.items() if k.startswith('context_')}, - 'available_table_evidence':{k:v for k,v in semantics.items() if k.startswith('table_')}, - 'available_database_evidence':{k:v for k,v in semantics.items() if k.startswith('database_')}, - 'available_metadata_evidence':semantics,'standard_alignment_evidence':alignments, - 'aligned_standard_candidates':alignments,'available_semantic_context':{k:v for k,v in semantics.items() if k not in ('field_semantics','field_abbreviation_semantics')}, + state[alias] = state[original] + provenance[alias] = provenance.get(original, skill) + if "category" in state: + for alias in ("candidate_category", "category_candidate"): + state[alias] = state["category"] + provenance[alias] = provenance.get("category", skill) + if isinstance(state.get("standard_candidates"), list) and state["standard_candidates"]: + for alias in ( + "candidate_standard_categories", + "candidate_categories", + "previous_standard_results", + ): + state[alias] = state["standard_candidates"] + provenance[alias] = provenance.get("standard_candidates", skill) + semantics = validated_evidence_values(state, SEMANTIC_KEYS) + alignments = validated_evidence_values(state, ALIGNMENT_KEYS) + groups = { + "available_field_evidence": { + k: v + for k, v in semantics.items() + if k.startswith(("field_", "disambiguated_", "value_")) + }, + "context_field_evidence": {k: v for k, v in semantics.items() if k.startswith("context_")}, + "available_table_evidence": {k: v for k, v in semantics.items() if k.startswith("table_")}, + "available_database_evidence": { + k: v for k, v in semantics.items() if k.startswith("database_") + }, + "available_metadata_evidence": semantics, + "standard_alignment_evidence": alignments, + "aligned_standard_candidates": alignments, + "available_semantic_context": { + k: v + for k, v in semantics.items() + if k not in ("field_semantics", "field_abbreviation_semantics") + }, } if semantics: - for name in ('semantic_evidence','current_semantic_state','semantic_query','current_evidence', - 'current_evidence_state','all_available_evidence','evidence','evidence_set'): - groups[name]=semantics + for name in ( + "semantic_evidence", + "current_semantic_state", + "semantic_query", + "current_evidence", + "current_evidence_state", + "all_available_evidence", + "evidence", + "evidence_set", + ): + groups[name] = semantics # Multiple model interpretations do not establish a business-data conflict. - if len(alignments)>=2: - groups['conflicting_standard_alignments']=alignments - for name,value in groups.items(): + if len(alignments) >= 2: + groups["conflicting_standard_alignments"] = alignments + for name, value in groups.items(): if value: - state[name]=value; provenance[name]='validated-evidence-bundle' + state[name] = value + provenance[name] = "validated-evidence-bundle" # Raw retrieved metadata is also usable search evidence, without pretending it is semantics. - if isinstance(state.get('field_metadata'),Mapping) or semantics: - state['available_evidence']=assemble_pool_evidence(record,state) - provenance['available_evidence']='validated-evidence-bundle' - state['all_available_evidence']=state['available_evidence'] - provenance['all_available_evidence']='validated-evidence-bundle' - if 'semantic_query' not in state: - state['semantic_query']=state['available_evidence'] - evidence=pool_final_evidence(record,state) + if isinstance(state.get("field_metadata"), Mapping) or semantics: + state["available_evidence"] = assemble_pool_evidence(record, state) + provenance["available_evidence"] = "validated-evidence-bundle" + state["all_available_evidence"] = state["available_evidence"] + provenance["all_available_evidence"] = "validated-evidence-bundle" + if "semantic_query" not in state: + state["semantic_query"] = state["available_evidence"] + evidence = pool_final_evidence(record, state) if evidence is not None: - state['final_evidence_state']=evidence - provenance['final_evidence_state']='frozen-classification-bundle' + state["final_evidence_state"] = evidence + provenance["final_evidence_state"] = "frozen-classification-bundle" -def _binding(name,record,state): - if name=='current_record': return '$record' - if name=='domain': return '$domain' - if name in ('field_name','target_field'): return '$metadata.field_name' - if name=='table_fields': - value=state.get(name) - if not isinstance(value,Mapping) or value.get('coverage')!='canonical-val-same-table-only' or value.get('missing_locators')!=[]: +def _binding(name, record, state): + if name == "current_record": + return "$record" + if name == "domain": + return "$domain" + if name in ("field_name", "target_field"): + return "$metadata.field_name" + if name == "table_fields": + value = state.get(name) + if ( + not isinstance(value, Mapping) + or value.get("coverage") != "canonical-val-same-table-only" + or value.get("missing_locators") != [] + ): return None - fields=value.get('fields') - if (not isinstance(fields,list) or not fields or len(fields)>30 - or type(value.get('returned_count')) is not int or value['returned_count']!=len(fields) - or type(value.get('available_count')) is not int or value['available_count'] 30 + or type(value.get("returned_count")) is not int + or value["returned_count"] != len(fields) + or type(value.get("available_count")) is not int + or value["available_count"] < len(fields) + or not all(present(value.get(k)) for k in ("database_name", "table_name")) + or not all( + isinstance(f, Mapping) + and isinstance(f.get("field_name"), str) + and present(f["field_name"]) + for f in fields + ) + ): return None - if name=='selected_context_fields': - value=state.get(name) - if not isinstance(value,list) or not value or not all(isinstance(v,str) and present(v) for v in value) or len(set(value))!=len(value): + if name == "selected_context_fields": + value = state.get(name) + if ( + not isinstance(value, list) + or not value + or not all(isinstance(v, str) and present(v) for v in value) + or len(set(value)) != len(value) + ): return None - if name=='context_fields' and (not isinstance(state.get(name),list) or not state[name] or not all(isinstance(f,Mapping) and present(f.get('field_name')) for f in state[name])): + if name == "context_fields" and ( + not isinstance(state.get(name), list) + or not state[name] + or not all(isinstance(f, Mapping) and present(f.get("field_name")) for f in state[name]) + ): return None - if name=='candidate_standard_categories' and present(state.get('standard_candidates')): - return '$state.standard_candidates' - if name in state and present(state[name]): return '$state.'+name - if name=='all_available_evidence' and present(state.get('available_evidence')): return '$state.available_evidence' + if name == "candidate_standard_categories" and present(state.get("standard_candidates")): + return "$state.standard_candidates" + if name in state and present(state[name]): + return "$state." + name + if name == "all_available_evidence" and present(state.get("available_evidence")): + return "$state.available_evidence" return None -def derive_pool_callable(record,state,catalog): - named=state.named_state if isinstance(state,LoopState) else state - result={} - for name,spec in catalog.items(): - if all(_binding(k,record,named) is not None for k in spec.required_inputs): +def derive_pool_callable(record, state, catalog): + named = state.named_state if isinstance(state, LoopState) else state + result = {} + for name, spec in catalog.items(): + if all(_binding(k, record, named) is not None for k in spec.required_inputs): # Placeholders, empty structures and unprovenanced raw state cannot enable raw Skills. - raw_inputs=set(spec.required_inputs)&(set(FIELDS)-{'field_name'}) - raw_inputs|=set(spec.required_inputs)&{'table_fields','context_fields','selected_context_fields'} - if any(k not in named.get('_provenance',{}) for k in raw_inputs): + raw_inputs = set(spec.required_inputs) & (set(FIELDS) - {"field_name"}) + raw_inputs |= set(spec.required_inputs) & { + "table_fields", + "context_fields", + "selected_context_fields", + } + if any(k not in named.get("_provenance", {}) for k in raw_inputs): continue - result[name]=spec + result[name] = spec return result class PoolPolicy: - def __init__(self,generate,catalog,*,missing_awareness=False,metadata_prefetch=False): - self.generate=generate; self.catalog=catalog - self.missing_awareness=missing_awareness - self.metadata_prefetch=metadata_prefetch - - def select_action(self,record,state,callable_skills,*,feedback=None,forced_finalize=False): - if (self.metadata_prefetch and not forced_finalize and state.turns==0 - and not any(c.get('tool')=='GET_FIELD_METADATA' for c in state.call_history) - and 'GET_FIELD_METADATA' in callable_skills): - call=ToolCall('GET_FIELD_METADATA',{'current_record':'$record'}) - return PolicyDecision(call,json.dumps(call.to_dict(),ensure_ascii=False), - metadata={'fixed_metadata_prefetch':True}) - index=[{'name':s.name,'purpose':purpose(s.name),'required_inputs':list(s.required_inputs), - 'optional_inputs':list(s.optional_inputs),'produces':list(s.produces),'terminal':s.terminal} for s in self.catalog.values()] - payload={'task':'Predict the target leaf category and its frozen standard grading level.', - 'current':state.to_model_dict(),'capability_index':index,'callable_skills':list(callable_skills), - 'argument_bindings':{name:{k:_binding(k,record,state.named_state) for k in (*spec.required_inputs,*spec.optional_inputs) - if k!='missing_metadata_type' and _binding(k,record,state.named_state) is not None} for name,spec in callable_skills.items()}, - 'pending_metadata_retrieval':'Optional metadata is unavailable until explicitly retrieved from canonical Val. Missing types/values/descriptions remain unavailable.', - 'forced_finalize':forced_finalize,'output_schema':{'tool':'SKILL_NAME','arguments':{}}} - if feedback: payload['validation_feedback']=feedback + def __init__(self, generate, catalog, *, missing_awareness=False, metadata_prefetch=False): + self.generate = generate + self.catalog = catalog + self.missing_awareness = missing_awareness + self.metadata_prefetch = metadata_prefetch + + def select_action( + self, record, state, callable_skills, *, feedback=None, forced_finalize=False + ): + if ( + self.metadata_prefetch + and not forced_finalize + and state.turns == 0 + and not any(c.get("tool") == "GET_FIELD_METADATA" for c in state.call_history) + and "GET_FIELD_METADATA" in callable_skills + ): + call = ToolCall("GET_FIELD_METADATA", {"current_record": "$record"}) + return PolicyDecision( + call, + json.dumps(call.to_dict(), ensure_ascii=False), + metadata={"fixed_metadata_prefetch": True}, + ) + index = [ + { + "name": s.name, + "purpose": purpose(s.name), + "required_inputs": list(s.required_inputs), + "optional_inputs": list(s.optional_inputs), + "produces": list(s.produces), + "terminal": s.terminal, + } + for s in self.catalog.values() + ] + payload = { + "task": "Predict the target leaf category and its frozen standard grading level.", + "current": state.to_model_dict(), + "capability_index": index, + "callable_skills": list(callable_skills), + "argument_bindings": { + name: { + k: _binding(k, record, state.named_state) + for k in (*spec.required_inputs, *spec.optional_inputs) + if k != "missing_metadata_type" + and _binding(k, record, state.named_state) is not None + } + for name, spec in callable_skills.items() + }, + "pending_metadata_retrieval": "Optional metadata is unavailable until explicitly retrieved from canonical Val. Missing types/values/descriptions remain unavailable.", + "forced_finalize": forced_finalize, + "output_schema": {"tool": "SKILL_NAME", "arguments": {}}, + } + if feedback: + payload["validation_feedback"] = feedback if self.missing_awareness: from pool_availability import RULE - payload['availability_rule']=RULE - messages=[{'role':'system','content':POLICY_SYSTEM},{'role':'user','content':json.dumps(payload,ensure_ascii=False,indent=2)}] + + payload["availability_rule"] = RULE + messages = [ + {"role": "system", "content": POLICY_SYSTEM}, + {"role": "user", "content": json.dumps(payload, ensure_ascii=False, indent=2)}, + ] try: - raw=self.generate(messages) - call=parse_policy_action(raw) + raw = self.generate(messages) + call = parse_policy_action(raw) except Exception as exc: - if isinstance(exc,ActionError): - exc.metadata={'messages':messages,'raw_response':locals().get('raw'),'generation':_generation_metadata(self.generate)} + if isinstance(exc, ActionError): + exc.metadata = { + "messages": messages, + "raw_response": locals().get("raw"), + "generation": _generation_metadata(self.generate), + } raise - error=ActionError(f'policy generator failed: {exc}') - error.metadata={'messages':messages,'raw_response':None,'generation':_generation_metadata(self.generate)} + error = ActionError(f"policy generator failed: {exc}") + error.metadata = { + "messages": messages, + "raw_response": None, + "generation": _generation_metadata(self.generate), + } raise error from exc - return PolicyDecision(call,raw,tuple(messages),_generation_metadata(self.generate)) + return PolicyDecision(call, raw, tuple(messages), _generation_metadata(self.generate)) class PoolExecutor(ModelSkillExecutor): - def __init__(self,generate,loader,metadata_lookup,category_catalog,*,top1_selection_mode='model',include_comparison_explanation=True): - super().__init__(generate,loader,category_catalog=category_catalog,top_k=5,guard_two_stage_evidence=True, - evidence_assembly=assemble_pool_evidence,top1_selection_mode=top1_selection_mode, - include_comparison_explanation=include_comparison_explanation) - self.metadata_lookup=metadata_lookup + def __init__( + self, + generate, + loader, + metadata_lookup, + category_catalog, + *, + top1_selection_mode="model", + include_comparison_explanation=True, + ): + super().__init__( + generate, + loader, + category_catalog=category_catalog, + top_k=5, + guard_two_stage_evidence=True, + evidence_assembly=assemble_pool_evidence, + top1_selection_mode=top1_selection_mode, + include_comparison_explanation=include_comparison_explanation, + ) + self.metadata_lookup = metadata_lookup - def comparison_inputs(self,record,state,resolved): + def comparison_inputs(self, record, state, resolved): """The actual comparison model input, shared with recovery fingerprinting.""" - if resolved['standard_candidates']!=state.get('standard_candidates'): - raise SkillExecutionError('alignment must consume actual prior candidates') - ids=[item['category'] for item in resolved['standard_candidates']] + if resolved["standard_candidates"] != state.get("standard_candidates"): + raise SkillExecutionError("alignment must consume actual prior candidates") + ids = [item["category"] for item in resolved["standard_candidates"]] # The model chooses a short ID; only the executor binds the frozen object. - return {**resolved,'standard_candidate_details':self.category_catalog.option_details(ids), - 'available_evidence':assemble_pool_evidence(record,state)} - - def _execute_comparison(self,record,state,resolved,contract,*,correction_context=None): - inputs=self.comparison_inputs(record,state,resolved) - system=(f'Execute only the selected Skill {contract.name}.\n' - f'DSL: {contract.dsl}\nContract:\n{contract.body}\n' - 'Use only the resolved inputs. Return exactly one compact JSON decision with ' - 'decision, option_id, reason; no Markdown or extra fields.') - payload={'skill':contract.name,'resolved_inputs':inputs,'output_schema':{ - 'decision':'match or no_match', - 'option_id':'one exact short option_id from standard_candidate_details for match; null for no_match', - 'reason':f'non-empty brief string, at most {MAX_REASON_LENGTH} characters'}} + return { + **resolved, + "standard_candidate_details": self.category_catalog.option_details(ids), + "available_evidence": assemble_pool_evidence(record, state), + } + + def _execute_comparison(self, record, state, resolved, contract, *, correction_context=None): + inputs = self.comparison_inputs(record, state, resolved) + system = ( + f"Execute only the selected Skill {contract.name}.\n" + f"DSL: {contract.dsl}\nContract:\n{contract.body}\n" + "Use only the resolved inputs. Return exactly one compact JSON decision with " + "decision, option_id, reason; no Markdown or extra fields." + ) + payload = { + "skill": contract.name, + "resolved_inputs": inputs, + "output_schema": { + "decision": "match or no_match", + "option_id": "one exact short option_id from standard_candidate_details for match; null for no_match", + "reason": f"non-empty brief string, at most {MAX_REASON_LENGTH} characters", + }, + } if correction_context is not None: - payload['correction_context']=correction_context - messages=[{'role':'system','content':system}, - {'role':'user','content':json.dumps(payload,ensure_ascii=False,indent=2)}] - raw=None + payload["correction_context"] = correction_context + messages = [ + {"role": "system", "content": system}, + {"role": "user", "content": json.dumps(payload, ensure_ascii=False, indent=2)}, + ] + raw = None try: - raw=self.generate(messages) + raw = self.generate(messages) except Exception as exc: - generation=_generation_metadata(self.generate) - raise SkillExecutionError(str(exc),metadata={**getattr(exc,'metadata',{}), - **generation,'messages':messages,'raw_response':None,'generation':generation, - 'failure_kind':'backend_error'}) from exc - generation=_generation_metadata(self.generate) - metadata={**generation,'messages':messages,'raw_response':raw,'generation':generation} - if generation.get('truncation_at_budget') is True: - raise SkillExecutionError('comparison generation reported truncation at output budget', - metadata={**metadata,'failure_kind':'output_truncated'}) + generation = _generation_metadata(self.generate) + raise SkillExecutionError( + str(exc), + metadata={ + **getattr(exc, "metadata", {}), + **generation, + "messages": messages, + "raw_response": None, + "generation": generation, + "failure_kind": "backend_error", + }, + ) from exc + generation = _generation_metadata(self.generate) + metadata = { + **generation, + "messages": messages, + "raw_response": raw, + "generation": generation, + } + if generation.get("truncation_at_budget") is True: + raise SkillExecutionError( + "comparison generation reported truncation at output budget", + metadata={**metadata, "failure_kind": "output_truncated"}, + ) try: - decision=parse_comparison_output(raw,[item['option_id'] for item in inputs['standard_candidate_details']]) - if decision['decision']=='no_match': - raise SkillExecutionError(decision['reason'],metadata={'failure_kind':'no_match'}) - category=self.category_catalog.resolve_option_ids([decision['option_id']],1)[0] - observation=Observation(contract.name,'success',decision['reason'],{ - 'standard_comparison':decision['reason'], - 'aligned_standard_entry':self.category_catalog.frozen_entry(category)}) - observation=self._validate_semantic(observation,self.loader.catalog[contract.name],state) - except (ComparisonOutputError,SkillExecutionError,ValueError) as exc: - failure_kind=getattr(exc,'metadata',{}).get('failure_kind','invalid_output') - raise SkillExecutionError(str(exc),metadata={**getattr(exc,'metadata',{}),**metadata, - 'failure_kind':failure_kind}) from exc + decision = parse_comparison_output( + raw, [item["option_id"] for item in inputs["standard_candidate_details"]] + ) + if decision["decision"] == "no_match": + raise SkillExecutionError(decision["reason"], metadata={"failure_kind": "no_match"}) + category = self.category_catalog.resolve_option_ids([decision["option_id"]], 1)[0] + observation = Observation( + contract.name, + "success", + decision["reason"], + { + "standard_comparison": decision["reason"], + "aligned_standard_entry": self.category_catalog.frozen_entry(category), + }, + ) + observation = self._validate_semantic( + observation, self.loader.catalog[contract.name], state + ) + except (ComparisonOutputError, SkillExecutionError, ValueError) as exc: + failure_kind = getattr(exc, "metadata", {}).get("failure_kind", "invalid_output") + raise SkillExecutionError( + str(exc), + metadata={**getattr(exc, "metadata", {}), **metadata, "failure_kind": failure_kind}, + ) from exc except Exception as exc: - raise SkillExecutionError(str(exc),metadata={**metadata,'failure_kind':'unknown_error'}) from exc - return replace(observation,metadata=metadata) - - def _scoped_inputs(self,record,resolved): - for key in ('table_name','database_name','field_name','target_field'): - if key not in resolved: continue - actual=record.field_name if key=='target_field' else self.metadata_lookup.get(record).get(key) - if resolved[key]!=actual: - raise SkillExecutionError(f'{key} differs from actual privately scoped record') - - def _metadata(self,call,record,resolved,state): - lookup=self.metadata_lookup; own=lookup.get(record); name=call.tool - self._scoped_inputs(record,resolved) - if name=='CHECK_METADATA_AVAILABILITY': + raise SkillExecutionError( + str(exc), metadata={**metadata, "failure_kind": "unknown_error"} + ) from exc + return replace(observation, metadata=metadata) + + def _scoped_inputs(self, record, resolved): + for key in ("table_name", "database_name", "field_name", "target_field"): + if key not in resolved: + continue + actual = ( + record.field_name + if key == "target_field" + else self.metadata_lookup.get(record).get(key) + ) + if resolved[key] != actual: + raise SkillExecutionError(f"{key} differs from actual privately scoped record") + + def _metadata(self, call, record, resolved, state): + lookup = self.metadata_lookup + own = lookup.get(record) + name = call.tool + self._scoped_inputs(record, resolved) + if name == "CHECK_METADATA_AVAILABILITY": # Report currently visible raw inputs, not secretly loaded source data. - visible={'domain':record.domain,**acquired_raw(record,state)} - data={'metadata_availability':{'available':list(visible),'missing':[k for k in FIELDS if k not in visible]}} - elif name=='GET_FIELD_METADATA': data={'field_metadata':own} - elif name in ('GET_FIELD_DESCRIPTION','GET_TABLE_DESCRIPTION','GET_DATABASE_DESCRIPTION'): - key=self.loader.catalog[name].produces[0] - if key not in own: return Observation(name,'unavailable',f'Actual canonical metadata has no {key}',{},metadata={'missing':[key],'source':'canonical-val'}) - data={key:own[key]} - elif name=='GET_TABLE_FIELDS': data={'table_fields':lookup.table_fields(record)} - elif name=='GET_COMPLETE_TABLE_CONTEXT': data={'table_context':lookup.table_context(record)} - elif name=='GET_COMPLETE_DATABASE_CONTEXT': data={'database_context':lookup.database_context(record)} - elif name=='EXPAND_SELECTED_CONTEXT': data={'context_fields':lookup.expand(record,resolved['selected_context_fields'])} - elif name in ('GET_CONTEXT_FIELD_DESCRIPTIONS','GET_CONTEXT_FIELD_TYPES','GET_CONTEXT_FIELD_VALUES'): - fields=resolved['context_fields'] - names=[f['field_name'] if isinstance(f,Mapping) else f for f in fields] if isinstance(fields,list) else fields - expanded=lookup.expand(record,names) - rawkey={'GET_CONTEXT_FIELD_DESCRIPTIONS':'field_description','GET_CONTEXT_FIELD_TYPES':'field_type','GET_CONTEXT_FIELD_VALUES':'value'}[name] - missing=[f['field_name'] for f in expanded if rawkey not in f] - available=[{'field_name':f['field_name'],rawkey:f[rawkey]} for f in expanded if rawkey in f] - if not available: return Observation(name,'unavailable',f'No actual context {rawkey} is available',{},metadata={'missing_fields':missing,'source':'canonical-val'}) - data={self.loader.catalog[name].produces[0]:{'fields':available,'missing_fields':missing}} - elif name=='ACQUIRE_MISSING_METADATA': - key=resolved['missing_metadata_type'] - if not isinstance(key,str) or key not in FIELDS: raise SkillExecutionError('requested metadata type is outside allowlist') - if key not in own: return Observation(name,'unavailable',f'Canonical source has no requested {key}',{},metadata={'missing':[key],'source':'canonical-val'}) - data={'acquired_metadata':{key:own[key]}} - else: raise SkillExecutionError(f'unsupported metadata acquisition {name}') - return Observation(name,'success',f'{purpose(name)} Actual source data loaded with bounded coverage.',data,metadata={'source':'canonical-val'}) - - def _validate_semantic(self,observation,spec,state): - data=dict(observation.data) - for key,value in observation.data.items(): - if key=='aligned_standard_entry': - if not isinstance(value,Mapping): raise SkillExecutionError('aligned entry must be an actual frozen object') - category=value.get('category') - prior=state.get('standard_candidates',[]) - if not isinstance(category,str) or not any(isinstance(c,Mapping) and c.get('category')==category for c in prior): - raise SkillExecutionError('aligned entry must belong to actual retrieved candidates') - frozen=self.category_catalog.frozen_entry(category) - if spec.name=='COMPARE_STANDARD_CANDIDATES': - visible=self.category_catalog.details([category])[0] - if not ((set(value)==set(visible) and value==visible) or - (set(value)==set(frozen) and value==frozen)): - raise SkillExecutionError('aligned entry differs from authoritative candidate views') - data[key]=frozen - elif value!=frozen: raise SkillExecutionError('aligned entry differs from frozen Registry') - if state.get('category') and state['category']!=category: raise SkillExecutionError('comparison cannot overwrite selected category alignment') - elif not valid_evidence_value(key,value): - raise SkillExecutionError(f'{key} violates its declared evidence type') - return replace(observation,data=data) - - def _validate_consumed_raw(self,record,resolved,state): + visible = {"domain": record.domain, **acquired_raw(record, state)} + data = { + "metadata_availability": { + "available": list(visible), + "missing": [k for k in FIELDS if k not in visible], + } + } + elif name == "GET_FIELD_METADATA": + data = {"field_metadata": own} + elif name in ("GET_FIELD_DESCRIPTION", "GET_TABLE_DESCRIPTION", "GET_DATABASE_DESCRIPTION"): + key = self.loader.catalog[name].produces[0] + if key not in own: + return Observation( + name, + "unavailable", + f"Actual canonical metadata has no {key}", + {}, + metadata={"missing": [key], "source": "canonical-val"}, + ) + data = {key: own[key]} + elif name == "GET_TABLE_FIELDS": + data = {"table_fields": lookup.table_fields(record)} + elif name == "GET_COMPLETE_TABLE_CONTEXT": + data = {"table_context": lookup.table_context(record)} + elif name == "GET_COMPLETE_DATABASE_CONTEXT": + data = {"database_context": lookup.database_context(record)} + elif name == "EXPAND_SELECTED_CONTEXT": + data = {"context_fields": lookup.expand(record, resolved["selected_context_fields"])} + elif name in ( + "GET_CONTEXT_FIELD_DESCRIPTIONS", + "GET_CONTEXT_FIELD_TYPES", + "GET_CONTEXT_FIELD_VALUES", + ): + fields = resolved["context_fields"] + names = ( + [f["field_name"] if isinstance(f, Mapping) else f for f in fields] + if isinstance(fields, list) + else fields + ) + expanded = lookup.expand(record, names) + rawkey = { + "GET_CONTEXT_FIELD_DESCRIPTIONS": "field_description", + "GET_CONTEXT_FIELD_TYPES": "field_type", + "GET_CONTEXT_FIELD_VALUES": "value", + }[name] + missing = [f["field_name"] for f in expanded if rawkey not in f] + available = [ + {"field_name": f["field_name"], rawkey: f[rawkey]} for f in expanded if rawkey in f + ] + if not available: + return Observation( + name, + "unavailable", + f"No actual context {rawkey} is available", + {}, + metadata={"missing_fields": missing, "source": "canonical-val"}, + ) + data = { + self.loader.catalog[name].produces[0]: { + "fields": available, + "missing_fields": missing, + } + } + elif name == "ACQUIRE_MISSING_METADATA": + key = resolved["missing_metadata_type"] + if not isinstance(key, str) or key not in FIELDS: + raise SkillExecutionError("requested metadata type is outside allowlist") + if key not in own: + return Observation( + name, + "unavailable", + f"Canonical source has no requested {key}", + {}, + metadata={"missing": [key], "source": "canonical-val"}, + ) + data = {"acquired_metadata": {key: own[key]}} + else: + raise SkillExecutionError(f"unsupported metadata acquisition {name}") + return Observation( + name, + "success", + f"{purpose(name)} Actual source data loaded with bounded coverage.", + data, + metadata={"source": "canonical-val"}, + ) + + def _validate_semantic(self, observation, spec, state): + data = dict(observation.data) + for key, value in observation.data.items(): + if key == "aligned_standard_entry": + if not isinstance(value, Mapping): + raise SkillExecutionError("aligned entry must be an actual frozen object") + category = value.get("category") + prior = state.get("standard_candidates", []) + if not isinstance(category, str) or not any( + isinstance(c, Mapping) and c.get("category") == category for c in prior + ): + raise SkillExecutionError( + "aligned entry must belong to actual retrieved candidates" + ) + frozen = self.category_catalog.frozen_entry(category) + if spec.name == "COMPARE_STANDARD_CANDIDATES": + visible = self.category_catalog.details([category])[0] + if not ( + (set(value) == set(visible) and value == visible) + or (set(value) == set(frozen) and value == frozen) + ): + raise SkillExecutionError( + "aligned entry differs from authoritative candidate views" + ) + data[key] = frozen + elif value != frozen: + raise SkillExecutionError("aligned entry differs from frozen Registry") + if state.get("category") and state["category"] != category: + raise SkillExecutionError( + "comparison cannot overwrite selected category alignment" + ) + elif not valid_evidence_value(key, value): + raise SkillExecutionError(f"{key} violates its declared evidence type") + return replace(observation, data=data) + + def _validate_consumed_raw(self, record, resolved, state): """Bind every supplied raw argument to acquired canonical values before generation.""" - own=self.metadata_lookup.get(record) - provenance=state.get('_provenance',{}) - for key,value in resolved.items(): - if key=='current_record': - if value!={'domain':record.domain,'metadata':dict(record.metadata)}: - raise SkillExecutionError('current_record differs from actual initial record') - elif key in ('domain','field_name','target_field'): - actual=record.domain if key=='domain' else record.field_name - if value!=actual: raise SkillExecutionError(f'{key} differs from actual initial record') + own = self.metadata_lookup.get(record) + provenance = state.get("_provenance", {}) + for key, value in resolved.items(): + if key == "current_record": + if value != {"domain": record.domain, "metadata": dict(record.metadata)}: + raise SkillExecutionError("current_record differs from actual initial record") + elif key in ("domain", "field_name", "target_field"): + actual = record.domain if key == "domain" else record.field_name + if value != actual: + raise SkillExecutionError(f"{key} differs from actual initial record") elif key in FIELDS: - if key not in provenance or key not in state or value!=state[key] or value!=own.get(key): - raise SkillExecutionError(f'{key} must equal actually acquired canonical raw metadata') - elif key=='current_metadata': - if value!=state.get(key) or value!=acquired_raw(record,state): - raise SkillExecutionError('current_metadata must equal actually acquired raw state') - elif key=='available_metadata': - actual={'domain':record.domain,**acquired_raw(record,state)} - if not isinstance(value,Mapping) or value!=state.get(key) or value!=actual: - raise SkillExecutionError('available_metadata must equal actually acquired public raw metadata') - elif key=='table_fields': - if key not in provenance or value!=state.get(key) or value!=self.metadata_lookup.table_fields(record) or _binding(key,record,state) is None: - raise SkillExecutionError('table_fields must equal acquired nonempty same-table candidates') - elif key=='context_fields': - if key not in provenance or value!=state.get(key) or _binding(key,record,state) is None: - raise SkillExecutionError('context_fields must equal acquired expanded context objects') - actual=self.metadata_lookup.expand(record,[f['field_name'] for f in value]) - if value!=actual: raise SkillExecutionError('context_fields differ from actual bounded neighbors') - elif key=='selected_context_fields': - if key not in provenance or value!=state.get(key) or _binding(key,record,state) is None: - raise SkillExecutionError('selected_context_fields must equal actual acquired selection') - self.metadata_lookup.expand(record,value) - - def execute(self,call,record,state,contract,*,correction_context=None): - if self.loader.load(call.tool)!=contract: raise SkillExecutionError('contract mismatch') - spec=self.loader.catalog[call.tool] - allowed=set(spec.required_inputs)|set(spec.optional_inputs) - if set(call.arguments)-allowed or any(k not in call.arguments for k in spec.required_inputs): - raise SkillExecutionError('arguments must satisfy the selected native contract') - resolved=self._resolved_arguments(call,record,state) - if any(not present(resolved[k]) for k in spec.required_inputs): raise SkillExecutionError('required inputs must be nonempty actual values') - self._validate_consumed_raw(record,resolved,state) - if spec.role=='metadata_acquisition' and call.tool!='SELECT_CONTEXT_FIELDS': - return self._validate_deterministic(self._metadata(call,record,resolved,state),spec) + if ( + key not in provenance + or key not in state + or value != state[key] + or value != own.get(key) + ): + raise SkillExecutionError( + f"{key} must equal actually acquired canonical raw metadata" + ) + elif key == "current_metadata": + if value != state.get(key) or value != acquired_raw(record, state): + raise SkillExecutionError( + "current_metadata must equal actually acquired raw state" + ) + elif key == "available_metadata": + actual = {"domain": record.domain, **acquired_raw(record, state)} + if not isinstance(value, Mapping) or value != state.get(key) or value != actual: + raise SkillExecutionError( + "available_metadata must equal actually acquired public raw metadata" + ) + elif key == "table_fields": + if ( + key not in provenance + or value != state.get(key) + or value != self.metadata_lookup.table_fields(record) + or _binding(key, record, state) is None + ): + raise SkillExecutionError( + "table_fields must equal acquired nonempty same-table candidates" + ) + elif key == "context_fields": + if ( + key not in provenance + or value != state.get(key) + or _binding(key, record, state) is None + ): + raise SkillExecutionError( + "context_fields must equal acquired expanded context objects" + ) + actual = self.metadata_lookup.expand(record, [f["field_name"] for f in value]) + if value != actual: + raise SkillExecutionError("context_fields differ from actual bounded neighbors") + elif key == "selected_context_fields": + if ( + key not in provenance + or value != state.get(key) + or _binding(key, record, state) is None + ): + raise SkillExecutionError( + "selected_context_fields must equal actual acquired selection" + ) + self.metadata_lookup.expand(record, value) + + def execute(self, call, record, state, contract, *, correction_context=None): + if self.loader.load(call.tool) != contract: + raise SkillExecutionError("contract mismatch") + spec = self.loader.catalog[call.tool] + allowed = set(spec.required_inputs) | set(spec.optional_inputs) + if set(call.arguments) - allowed or any( + k not in call.arguments for k in spec.required_inputs + ): + raise SkillExecutionError("arguments must satisfy the selected native contract") + resolved = self._resolved_arguments(call, record, state) + if any(not present(resolved[k]) for k in spec.required_inputs): + raise SkillExecutionError("required inputs must be nonempty actual values") + self._validate_consumed_raw(record, resolved, state) + if spec.role == "metadata_acquisition" and call.tool != "SELECT_CONTEXT_FIELDS": + return self._validate_deterministic(self._metadata(call, record, resolved, state), spec) if call.tool in SEARCH_NAMES: - query=resolved[spec.required_inputs[0]] - internal=ToolCall('SELECT_CATEGORY_TOPK',{'semantic_query':query}) + query = resolved[spec.required_inputs[0]] + internal = ToolCall("SELECT_CATEGORY_TOPK", {"semantic_query": query}) # The internal engine role is compatible; contract/header remains requested native Skill. - observation=self._execute_two_stage(internal,record,{'semantic_query':query},state,contract) - return replace(observation,skill=call.tool,metadata={**observation.metadata,'standard_backend':'model-catalog-top5-v1','requested_skill':call.tool}) - if call.tool=='INFER_CATEGORY': - internal=ToolCall('INFER_CATEGORY_FROM_TOPK',call.arguments) - observation=self._execute_two_stage(internal,record,resolved,state,contract) - return replace(observation,skill=call.tool,metadata={**observation.metadata,'requested_skill':call.tool}) - if call.tool=='INFER_GRADING_LEVEL': - category=resolved['aligned_category']; entry=resolved['aligned_standard_entry'] - if category!=state.get('category') or entry!=state.get('aligned_standard_entry') or entry!=self.category_catalog.frozen_entry(category): - raise SkillExecutionError('grade must consume actual selected canonical standard entry') - return Observation(call.tool,'success',f'Frozen standard {category} assigns {entry["grading_level"]}',{'grading_level':entry['grading_level']},metadata={'controller_bound_grade':True}) - if call.tool in ('SELECT_CATEGORY_TOPK','INFER_CATEGORY_FROM_TOPK','FINALIZE_CLASSIFICATION'): - return super().execute(call,record,state,contract) - if call.tool=='SELECT_CONTEXT_FIELDS': - self._scoped_inputs(record,resolved) - actual=self.metadata_lookup.table_fields(record) - if resolved['table_fields']!=actual: raise SkillExecutionError('context selection must consume actual same-table candidates') - if call.tool=='COMPARE_STANDARD_CANDIDATES': - return self._execute_comparison(record,state,resolved,contract,correction_context=correction_context) + observation = self._execute_two_stage( + internal, record, {"semantic_query": query}, state, contract + ) + return replace( + observation, + skill=call.tool, + metadata={ + **observation.metadata, + "standard_backend": "model-catalog-top5-v1", + "requested_skill": call.tool, + }, + ) + if call.tool == "INFER_CATEGORY": + internal = ToolCall("INFER_CATEGORY_FROM_TOPK", call.arguments) + observation = self._execute_two_stage(internal, record, resolved, state, contract) + return replace( + observation, + skill=call.tool, + metadata={**observation.metadata, "requested_skill": call.tool}, + ) + if call.tool == "INFER_GRADING_LEVEL": + category = resolved["aligned_category"] + entry = resolved["aligned_standard_entry"] + if ( + category != state.get("category") + or entry != state.get("aligned_standard_entry") + or entry != self.category_catalog.frozen_entry(category) + ): + raise SkillExecutionError( + "grade must consume actual selected canonical standard entry" + ) + return Observation( + call.tool, + "success", + f'Frozen standard {category} assigns {entry["grading_level"]}', + {"grading_level": entry["grading_level"]}, + metadata={"controller_bound_grade": True}, + ) + if call.tool in ( + "SELECT_CATEGORY_TOPK", + "INFER_CATEGORY_FROM_TOPK", + "FINALIZE_CLASSIFICATION", + ): + return super().execute(call, record, state, contract) + if call.tool == "SELECT_CONTEXT_FIELDS": + self._scoped_inputs(record, resolved) + actual = self.metadata_lookup.table_fields(record) + if resolved["table_fields"] != actual: + raise SkillExecutionError( + "context selection must consume actual same-table candidates" + ) + if call.tool == "COMPARE_STANDARD_CANDIDATES": + return self._execute_comparison( + record, state, resolved, contract, correction_context=correction_context + ) # Alignment evidence receives actual descriptions for already selected candidates. - if spec.role=='standard_alignment' and 'standard_candidates' in resolved: - if resolved['standard_candidates']!=state.get('standard_candidates'): raise SkillExecutionError('alignment must consume actual prior candidates') - ids=[item['category'] for item in resolved['standard_candidates']] - resolved={**resolved,'standard_candidate_details':self.category_catalog.details(ids)} + if spec.role == "standard_alignment" and "standard_candidates" in resolved: + if resolved["standard_candidates"] != state.get("standard_candidates"): + raise SkillExecutionError("alignment must consume actual prior candidates") + ids = [item["category"] for item in resolved["standard_candidates"]] + resolved = { + **resolved, + "standard_candidate_details": self.category_catalog.details(ids), + } grounding_context = None if call.tool in GROUNDED_TARGETS: - actual_raw = acquired_raw(record,state) - grounding_context = {k: actual_raw[k] for k in ('field_name','field_description','table_name','table_description') if k in actual_raw} - messages = grounded_messages(contract,resolved,grounding_context) + actual_raw = acquired_raw(record, state) + grounding_context = { + k: actual_raw[k] + for k in ("field_name", "field_description", "table_name", "table_description") + if k in actual_raw + } + messages = grounded_messages(contract, resolved, grounding_context) else: - messages=self._messages(contract,resolved) + messages = self._messages(contract, resolved) try: - raw=self.generate(messages) - observation=parse_skill_observation(raw,spec) + raw = self.generate(messages) + observation = parse_skill_observation(raw, spec) if grounding_context is not None: validate_grounded(observation, grounding_context) - if call.tool=='SELECT_CONTEXT_FIELDS': - self.metadata_lookup.expand(record,observation.data['selected_context_fields']) + if call.tool == "SELECT_CONTEXT_FIELDS": + self.metadata_lookup.expand(record, observation.data["selected_context_fields"]) else: - observation=self._validate_semantic(observation,spec,state) + observation = self._validate_semantic(observation, spec, state) except Exception as exc: - if isinstance(exc,SkillExecutionError): - exc.metadata={'messages':messages,'raw_response':locals().get('raw'),**_generation_metadata(self.generate)} + if isinstance(exc, SkillExecutionError): + exc.metadata = { + "messages": messages, + "raw_response": locals().get("raw"), + **_generation_metadata(self.generate), + } raise - raise SkillExecutionError(str(exc),metadata={'messages':messages,'raw_response':locals().get('raw'),**_generation_metadata(self.generate)}) from exc - return replace(observation,metadata={'messages':messages,'raw_response':raw,**_generation_metadata(self.generate)}) + raise SkillExecutionError( + str(exc), + metadata={ + "messages": messages, + "raw_response": locals().get("raw"), + **_generation_metadata(self.generate), + }, + ) from exc + return replace( + observation, + metadata={ + "messages": messages, + "raw_response": raw, + **_generation_metadata(self.generate), + }, + ) class PoolController(AgentLoopController): - def _normalize_policy_decision(self,decision,record,state,spec): - call,audit=bind_call(decision.call,spec,record,state,_binding) + def _normalize_policy_decision(self, decision, record, state, spec): + call, audit = bind_call(decision.call, spec, record, state, _binding) if self.policy.missing_awareness: from pool_availability import blocked - denied=blocked(call,state) - if denied: raise ActionError(f'availability repeat target blocked: {denied}') - return replace(decision,call=call,metadata={**decision.metadata,'binding':audit}) - def _rejected_policy_metadata(self,decision,error): - return {'binding':{'version':BINDING_RULE_VERSION,'status':'rejected', - 'raw_call':decision.call.to_dict() if decision is not None else None, - 'normalized_call':None,'changes':[]}} + denied = blocked(call, state) + if denied: + raise ActionError(f"availability repeat target blocked: {denied}") + return replace(decision, call=call, metadata={**decision.metadata, "binding": audit}) - def _available_evidence(self,record,state): - return assemble_pool_evidence(record,state) + def _rejected_policy_metadata(self, decision, error): + return { + "binding": { + "version": BINDING_RULE_VERSION, + "status": "rejected", + "raw_call": decision.call.to_dict() if decision is not None else None, + "normalized_call": None, + "changes": [], + } + } - def _final_evidence_state(self,record,state): - return pool_final_evidence(record,state) + def _available_evidence(self, record, state): + return assemble_pool_evidence(record, state) - def _normalize_observation(self,call,observation,state): + def _final_evidence_state(self, record, state): + return pool_final_evidence(record, state) + + def _normalize_observation(self, call, observation, state): if self.policy.missing_awareness: from pool_availability import observe - observe(call,observation,state) - if observation.status=='success' and call.tool in ('INFER_CATEGORY','INFER_CATEGORY_FROM_TOPK'): - category=observation.data.get('category') + + observe(call, observation, state) + if observation.status == "success" and call.tool in ( + "INFER_CATEGORY", + "INFER_CATEGORY_FROM_TOPK", + ): + category = observation.data.get("category") if category in self.registry_entries: - frozen={'category':category,**self.registry_entries[category]} - if observation.data.get('aligned_standard_entry')!=frozen: - return Observation(call.tool,'error','category alignment differs from frozen Registry',{}) + frozen = {"category": category, **self.registry_entries[category]} + if observation.data.get("aligned_standard_entry") != frozen: + return Observation( + call.tool, "error", "category alignment differs from frozen Registry", {} + ) # Both native and compatibility category engines bind the same canonical entry. - normalized=super()._normalize_observation(call,observation,state) - if normalized.status=='success': - return replace(normalized,data={**normalized.data,'aligned_standard_entry':frozen}) + normalized = super()._normalize_observation(call, observation, state) + if normalized.status == "success": + return replace( + normalized, data={**normalized.data, "aligned_standard_entry": frozen} + ) return normalized - return super()._normalize_observation(call,observation,state) + return super()._normalize_observation(call, observation, state) -def build_pool_controller(generate,registry,metadata_path,pool,config,*,missing_awareness=False, - metadata_prefetch=False,top1_selection_mode='model'): +def build_pool_controller( + generate, + registry, + metadata_path, + pool, + config, + *, + missing_awareness=False, + metadata_prefetch=False, + top1_selection_mode="model", +): """Build P14 controls; fixed prefetch needs at least 2 budgeted turns.""" - if type(missing_awareness) is not bool: raise ValueError('missing_awareness must be boolean') - if type(metadata_prefetch) is not bool: raise ValueError('metadata_prefetch must be boolean') - if type(top1_selection_mode) is not str or top1_selection_mode not in ('model','first'): - raise ValueError('top1_selection_mode must be model or first') - if pool!='P14' and (metadata_prefetch or top1_selection_mode!='model'): - raise ValueError('nondefault controls require P14') - catalog=pool_catalog(pool) - if isinstance(registry,(str,Path)): - registry=json.loads(Path(registry).read_text(encoding='utf-8')) - if isinstance(registry,Mapping) and 'categories' in registry: - entries={item['category_id']:{k:v for k,v in item.items() if k not in ('category','category_id')} for item in registry['categories']} - elif isinstance(registry,Mapping): entries={k:dict(v) for k,v in registry.items()} - else: raise ValueError('registry must be a frozen category mapping or Registry file') - loader=SkillLoader(ROOT/'runtime/skills/full_pool',catalog,strict_catalog=False) + if type(missing_awareness) is not bool: + raise ValueError("missing_awareness must be boolean") + if type(metadata_prefetch) is not bool: + raise ValueError("metadata_prefetch must be boolean") + if type(top1_selection_mode) is not str or top1_selection_mode not in ("model", "first"): + raise ValueError("top1_selection_mode must be model or first") + if pool != "P14" and (metadata_prefetch or top1_selection_mode != "model"): + raise ValueError("nondefault controls require P14") + catalog = pool_catalog(pool) + if isinstance(registry, (str, Path)): + registry = json.loads(Path(registry).read_text(encoding="utf-8")) + if isinstance(registry, Mapping) and "categories" in registry: + entries = { + item["category_id"]: { + k: v for k, v in item.items() if k not in ("category", "category_id") + } + for item in registry["categories"] + } + elif isinstance(registry, Mapping): + entries = {k: dict(v) for k, v in registry.items()} + else: + raise ValueError("registry must be a frozen category mapping or Registry file") + loader = SkillLoader(ROOT / "runtime/skills/full_pool", catalog, strict_catalog=False) loader.validate_all() # Installation is a separate explicit pre-freeze action. - metadata=PoolMetadata.from_canonical(metadata_path) - category_catalog=CategoryCatalog(entries) - executor=PoolExecutor(generate,loader,metadata,category_catalog,top1_selection_mode=top1_selection_mode) + metadata = PoolMetadata.from_canonical(metadata_path) + category_catalog = CategoryCatalog(entries) + executor = PoolExecutor( + generate, loader, metadata, category_catalog, top1_selection_mode=top1_selection_mode + ) if config is None: - config=LoopConfig(recover_ready_finalization=True) - elif isinstance(config,Mapping): - config=LoopConfig(**config) - if metadata_prefetch and config.max_turns<2: - raise ValueError('metadata_prefetch requires at least 2 turns') - def derive(record,state,catalog): - from pool_availability import initialize,filter_callable - named=state.named_state if isinstance(state,LoopState) else state - initialize(record,named) - return filter_callable(named,derive_pool_callable(record,state,catalog)) - return PoolController(policy=PoolPolicy(generate,catalog,missing_awareness=missing_awareness, - metadata_prefetch=metadata_prefetch),executor=executor,catalog=catalog, - skill_loader=loader,config=config,registry_entries=entries, - approved_levels={e['grading_level'] for e in entries.values()}, - callable_derivation=derive if missing_awareness else derive_pool_callable,state_publication=publish_state) + config = LoopConfig(recover_ready_finalization=True) + elif isinstance(config, Mapping): + config = LoopConfig(**config) + if metadata_prefetch and config.max_turns < 2: + raise ValueError("metadata_prefetch requires at least 2 turns") + + def derive(record, state, catalog): + from pool_availability import initialize, filter_callable + + named = state.named_state if isinstance(state, LoopState) else state + initialize(record, named) + return filter_callable(named, derive_pool_callable(record, state, catalog)) + + return PoolController( + policy=PoolPolicy( + generate, + catalog, + missing_awareness=missing_awareness, + metadata_prefetch=metadata_prefetch, + ), + executor=executor, + catalog=catalog, + skill_loader=loader, + config=config, + registry_entries=entries, + approved_levels={e["grading_level"] for e in entries.values()}, + callable_derivation=derive if missing_awareness else derive_pool_callable, + state_publication=publish_state, + ) diff --git a/research/finance_program_v1/evaluation/runtime/vendor/runtime/code/agent/orchestration/model_skill_executor.py b/research/finance_program_v1/evaluation/runtime/vendor/runtime/code/agent/orchestration/model_skill_executor.py index f61f797..e1f705f 100644 --- a/research/finance_program_v1/evaluation/runtime/vendor/runtime/code/agent/orchestration/model_skill_executor.py +++ b/research/finance_program_v1/evaluation/runtime/vendor/runtime/code/agent/orchestration/model_skill_executor.py @@ -1,3 +1,5 @@ +# 原版Skill provider边界:组装契约/实际输入,验证回应后才发布canonical输出。 +# 公开body与output_rule按原版保留;本次不修schema、不替换模型或插入候选。 """Model-independent adapters for policy generation and semantic Skill execution.""" from __future__ import annotations @@ -198,11 +200,7 @@ def parse_skill_observation(text: str, spec: SkillSpec) -> Observation: extra = sorted(actual - expected) if extra: raise SkillExecutionError(f"unexpected produced keys: {extra}") - empty = sorted( - key - for key in expected - if data.get(key) is None or data.get(key) == "" - ) + empty = sorted(key for key in expected if data.get(key) is None or data.get(key) == "") if empty: raise SkillExecutionError(f"produced keys must be non-empty: {empty}") return Observation(spec.name, "success", summary.strip(), dict(data)) @@ -226,7 +224,9 @@ def load_few_shot_messages(path: str | Path) -> tuple[dict[str, str], ...]: raise ValueError(f"few-shot message {index} has an invalid role or content") lowered = content.lower() if any(marker in lowered for marker in forbidden): - raise ValueError("few-shot examples must not contain ground-truth or source identifiers") + raise ValueError( + "few-shot examples must not contain ground-truth or source identifiers" + ) messages.append({"role": role, "content": content}) return tuple(messages) @@ -322,9 +322,9 @@ def select_action( "INFER_CATEGORY_FROM_TOPK." ) if self.metadata_guidance: - messages[0]["content"] += ( - " Finish grading and finalization without repeating diagnostic Skills." - ) + messages[0][ + "content" + ] += " Finish grading and finalization without repeating diagnostic Skills." if self.description_skills and "field_metadata" in state.named_state: messages[0]["content"] += ( " Real descriptions in field_metadata may be interpreted through " @@ -337,14 +337,14 @@ def select_action( ) elif self.metadata_guidance: messages[0]["content"] += ( - "\nIf GET_FIELD_METADATA is callable and field_metadata is absent, " - "call GET_FIELD_METADATA before semantic interpretation or retrieval. " - "When real field_metadata has been obtained and standard_candidates " - "are absent, call SEARCH_STANDARD with " - "{\"semantic_query\":\"$state.field_metadata\"}; do not search only " - "the guessed field_semantics. Once candidates are available, " - "proceed toward category, level, and finalization without " - "repeating diagnostic Skills." + "\nIf GET_FIELD_METADATA is callable and field_metadata is absent, " + "call GET_FIELD_METADATA before semantic interpretation or retrieval. " + "When real field_metadata has been obtained and standard_candidates " + "are absent, call SEARCH_STANDARD with " + '{"semantic_query":"$state.field_metadata"}; do not search only ' + "the guessed field_semantics. Once candidates are available, " + "proceed toward category, level, and finalization without " + "repeating diagnostic Skills." ) if self.few_shot_messages: messages[1:1] = [dict(message) for message in self.few_shot_messages] @@ -352,16 +352,23 @@ def select_action( raw = self.generate(messages) except Exception as exc: # pragma: no cover - backend-specific error = ActionError(f"policy generator failed: {exc}") - error.metadata = {"messages": messages, "raw_response": None, - "error": str(exc), "generation": _generation_metadata(self.generate)} + error.metadata = { + "messages": messages, + "raw_response": None, + "error": str(exc), + "generation": _generation_metadata(self.generate), + } raise error from exc if not isinstance(raw, str): raise ActionError("policy generator must return a string") try: parsed = parse_policy_action(raw) except ActionError as exc: - exc.metadata = {"messages": messages, "raw_response": raw, - "generation": _generation_metadata(self.generate)} + exc.metadata = { + "messages": messages, + "raw_response": raw, + "generation": _generation_metadata(self.generate), + } raise return PolicyDecision( call=parsed, @@ -392,7 +399,7 @@ def __init__( include_comparison_explanation: bool = True, ) -> None: if type(include_comparison_explanation) is not bool: - raise ValueError('include_comparison_explanation must be bool') + raise ValueError("include_comparison_explanation must be bool") self.include_comparison_explanation = include_comparison_explanation if top1_evidence_mode not in {"all", "raw"}: raise ValueError("top1_evidence_mode must be all or raw") @@ -488,8 +495,10 @@ def execute( return self._execute_two_stage(call, record, resolved, state, contract) except SkillExecutionError as exc: if call.tool == "INFER_CATEGORY_FROM_TOPK": - exc.metadata.update(top1_selection_mode=self.top1_selection_mode, - top1_evidence_mode=self.top1_evidence_mode) + exc.metadata.update( + top1_selection_mode=self.top1_selection_mode, + top1_evidence_mode=self.top1_evidence_mode, + ) raise if call.tool == "FINALIZE_CLASSIFICATION" and self.guard_two_stage_evidence: return self._finalize_guarded_two_stage(call, resolved, state) @@ -501,16 +510,25 @@ def execute( try: raw = self.generate(messages) except Exception as exc: # pragma: no cover - backend-specific - raise SkillExecutionError(f"Skill generator failed: {exc}", metadata={ - "messages": messages, "raw_response": None, "error": str(exc), - "generation": _generation_metadata(self.generate)}) from exc + raise SkillExecutionError( + f"Skill generator failed: {exc}", + metadata={ + "messages": messages, + "raw_response": None, + "error": str(exc), + "generation": _generation_metadata(self.generate), + }, + ) from exc if not isinstance(raw, str): raise SkillExecutionError("Skill generator must return a string") try: observation = parse_skill_observation(raw, spec) except SkillExecutionError as exc: - exc.metadata = {"messages": messages, "raw_response": raw, - "generation": _generation_metadata(self.generate)} + exc.metadata = { + "messages": messages, + "raw_response": raw, + "generation": _generation_metadata(self.generate), + } raise return replace( observation, @@ -591,7 +609,8 @@ def _execute_two_stage( elif self.topk_evidence_mode == "raw-flat": semantic_query = { **state["field_metadata"], - "domain": record.domain, "field_name": record.field_name, + "domain": record.domain, + "field_name": record.field_name, } else: semantic_query = resolved["semantic_query"] @@ -608,13 +627,13 @@ def _execute_two_stage( output_rule = ( 'Return exactly one JSON object: {"option_ids":["C001",...],' f'"summary":"reason"}}. The list MUST contain exactly {self.top_k} distinct ' - f'option IDs from category_options, ranked best first. If fewer than {self.top_k} ' - 'are strong matches, include weaker but plausible supplied options to fill every slot. ' - 'Copy the short option_id exactly. Do not output long category paths, canonical ' - 'category IDs, duplicates, invented option IDs, or a different top-N. ' - 'Limit summary to one short phrase (at most 20 characters); do not put ' - 'quotation marks, line breaks, or a long explanation inside summary. ' - 'Close the summary string and the JSON object.' + f"option IDs from category_options, ranked best first. If fewer than {self.top_k} " + "are strong matches, include weaker but plausible supplied options to fill every slot. " + "Copy the short option_id exactly. Do not output long category paths, canonical " + "category IDs, duplicates, invented option IDs, or a different top-N. " + "Limit summary to one short phrase (at most 20 characters); do not put " + "quotation marks, line breaks, or a long explanation inside summary. " + "Close the summary string and the JSON object." ) else: prior = state.get("standard_candidates") @@ -631,15 +650,33 @@ def _execute_two_stage( raise SkillExecutionError(str(exc)) from exc if self.top1_selection_mode == "first": category = ids[0] - return Observation(call.tool, "success", "Selected actual first frozen candidate", - {"category": category, "aligned_standard_entry": self.category_catalog.frozen_entry(category)}, - metadata={"top1_selection_mode": "first", "top1_evidence_mode": self.top1_evidence_mode, - "controller_bound_selection": True, "model_call_count": 0, "attempts": []}) + return Observation( + call.tool, + "success", + "Selected actual first frozen candidate", + { + "category": category, + "aligned_standard_entry": self.category_catalog.frozen_entry(category), + }, + metadata={ + "top1_selection_mode": "first", + "top1_evidence_mode": self.top1_evidence_mode, + "controller_bound_selection": True, + "model_call_count": 0, + "attempts": [], + }, + ) evidence = resolved["all_available_evidence"] if self.top1_evidence_mode == "raw": - evidence = {"domain": record.domain, "field_name": record.field_name, - "observations": {"field_metadata": dict(state["field_metadata"])} - if isinstance(state.get("field_metadata"), Mapping) else {}} + evidence = { + "domain": record.domain, + "field_name": record.field_name, + "observations": ( + {"field_metadata": dict(state["field_metadata"])} + if isinstance(state.get("field_metadata"), Mapping) + else {} + ), + } prompt_input = { "all_available_evidence": evidence, "candidate_details": details, @@ -648,30 +685,44 @@ def _execute_two_stage( prompt_input["available_evidence"] = self.evidence_assembly(record, state) if not self.include_comparison_explanation: from evidence_roles import project_top1_evidence - for key in ('all_available_evidence', 'available_evidence'): + + for key in ("all_available_evidence", "available_evidence"): if key in prompt_input: - prompt_input[key] = project_top1_evidence(prompt_input[key], state.get('standard_comparison')) + prompt_input[key] = project_top1_evidence( + prompt_input[key], state.get("standard_comparison") + ) output_rule = ( 'Return exactly one JSON object: {"option_id":"one supplied short option ID",' '"summary":"reason"}. Do not choose outside candidate_details. ' - 'Limit summary to one short phrase (at most 20 characters); do not put ' - 'quotation marks, line breaks, or a long explanation inside summary. ' - 'Close the summary string and the JSON object.' + "Limit summary to one short phrase (at most 20 characters); do not put " + "quotation marks, line breaks, or a long explanation inside summary. " + "Close the summary string and the JSON object." ) messages = [ - {"role": "system", "content": f"Execute only the selected Skill {contract.name}.\n{contract.body}\n{output_rule}"}, + { + "role": "system", + "content": f"Execute only the selected Skill {contract.name}.\n{contract.body}\n{output_rule}", + }, {"role": "user", "content": json.dumps(prompt_input, ensure_ascii=False, indent=2)}, ] if call.tool == "SELECT_CATEGORY_TOPK" and self.topk_selection_mode == "balanced-vote": - return self._execute_balanced_topk(record, prompt_input, messages[0], evidence_assembled) + return self._execute_balanced_topk( + record, prompt_input, messages[0], evidence_assembled + ) attempts: list[dict[str, Any]] = [] max_attempts = 2 for attempt_index in range(max_attempts): try: raw = self.generate(messages) except Exception as exc: - attempts.append({"messages": messages, "raw_response": None, "error": str(exc), - "generation": _generation_metadata(self.generate)}) + attempts.append( + { + "messages": messages, + "raw_response": None, + "error": str(exc), + "generation": _generation_metadata(self.generate), + } + ) raise SkillExecutionError( f"two-stage Skill generator failed: {exc}", metadata=_attempt_metadata(attempts), @@ -684,7 +735,9 @@ def _execute_two_stage( raise SkillExecutionError("two-stage Skill requires a nonempty summary") if call.tool == "SELECT_CATEGORY_TOPK": if set(payload) != {"option_ids", "summary"}: - raise SkillExecutionError("Top-K response must contain option_ids and summary only") + raise SkillExecutionError( + "Top-K response must contain option_ids and summary only" + ) canonical_ids = self.category_catalog.resolve_option_ids( payload["option_ids"], self.top_k ) @@ -692,15 +745,28 @@ def _execute_two_stage( data = {"standard_candidates": [label_map[item] for item in canonical_ids]} else: if set(payload) != {"option_id", "summary"}: - raise SkillExecutionError("Top-1 response must contain option_id and summary only") - category = self.category_catalog.resolve_option_ids([payload["option_id"]], 1)[0] + raise SkillExecutionError( + "Top-1 response must contain option_id and summary only" + ) + category = self.category_catalog.resolve_option_ids([payload["option_id"]], 1)[ + 0 + ] if category not in ids: raise SkillExecutionError("Top-1 category is outside prior Top-K") - data = {"category": category, "aligned_standard_entry": self.category_catalog.frozen_entry(category)} + data = { + "category": category, + "aligned_standard_entry": self.category_catalog.frozen_entry(category), + } except (SkillExecutionError, ValueError, TypeError, KeyError) as exc: error = str(exc) - attempts.append({"messages": messages, "raw_response": raw, - "error": error, "generation": generation}) + attempts.append( + { + "messages": messages, + "raw_response": raw, + "error": error, + "generation": generation, + } + ) if attempt_index + 1 < max_attempts: if call.tool == "SELECT_CATEGORY_TOPK": feedback = ( @@ -728,22 +794,27 @@ def _execute_two_stage( f"invalid two-stage Skill response: {error}", metadata=_attempt_metadata(attempts), ) from exc - attempts.append({"messages": messages, "raw_response": raw, - "generation": generation}) + attempts.append({"messages": messages, "raw_response": raw, "generation": generation}) metadata = _attempt_metadata(attempts) if call.tool == "INFER_CATEGORY_FROM_TOPK": - metadata.update({"top1_evidence_mode": self.top1_evidence_mode, - "top1_selection_mode": self.top1_selection_mode}) + metadata.update( + { + "top1_evidence_mode": self.top1_evidence_mode, + "top1_selection_mode": self.top1_selection_mode, + } + ) if evidence_assembled: metadata["controller_evidence_assembled"] = True metadata["topk_evidence_mode"] = self.topk_evidence_mode - return Observation(call.tool, "success", summary.strip(), data, - metadata=metadata) + return Observation(call.tool, "success", summary.strip(), data, metadata=metadata) raise AssertionError("unreachable") def _execute_balanced_topk( - self, record: MetadataRecord, prompt_input: Mapping[str, Any], - system_message: Mapping[str, str], evidence_assembled: bool, + self, + record: MetadataRecord, + prompt_input: Mapping[str, Any], + system_message: Mapping[str, str], + evidence_assembled: bool, ) -> Observation: """Make exactly three independent calls, retaining failures without retry.""" assert self.category_catalog is not None @@ -751,18 +822,29 @@ def _execute_balanced_topk( rankings: list[list[str]] = [] options = prompt_input["category_options"] allowed = [item["option_id"] for item in options] - for index, presented in enumerate(balanced_options( - options, record.domain, record.field_name, self.topk_selection_seed - ), start=1): - messages = [dict(system_message), { - "role": "user", "content": json.dumps( - {**prompt_input, "category_options": presented}, ensure_ascii=False, indent=2 - ), - }] + for index, presented in enumerate( + balanced_options(options, record.domain, record.field_name, self.topk_selection_seed), + start=1, + ): + messages = [ + dict(system_message), + { + "role": "user", + "content": json.dumps( + {**prompt_input, "category_options": presented}, + ensure_ascii=False, + indent=2, + ), + }, + ] attempt: dict[str, Any] = { - "round": index, "presented_option_ids": [item["option_id"] for item in presented], - "valid": False, "error": None, "raw_response": None, - "messages": messages, "generation": {}, + "round": index, + "presented_option_ids": [item["option_id"] for item in presented], + "valid": False, + "error": None, + "raw_response": None, + "messages": messages, + "generation": {}, } # Most generators keep a last-call attribute. Clear it before this call # so a failing backend cannot be charged for the previous completion. @@ -786,40 +868,77 @@ def _execute_balanced_topk( try: payload = _decode_observation_object(raw) if set(payload) != {"option_ids", "summary"}: - raise SkillExecutionError("Top-K response must contain option_ids and summary only") + raise SkillExecutionError( + "Top-K response must contain option_ids and summary only" + ) if not isinstance(payload["summary"], str) or not payload["summary"].strip(): raise SkillExecutionError("two-stage Skill requires a nonempty summary") self.category_catalog.resolve_option_ids(payload["option_ids"], self.top_k) ranking = list(payload["option_ids"]) rankings.append(ranking) - attempt.update({"valid": True, "option_ids": ranking, "votes": [ - {"option_id": item, "vote": 1, "reciprocal_rank_score": f"1/{rank}"} - for rank, item in enumerate(ranking, start=1) - ]}) + attempt.update( + { + "valid": True, + "option_ids": ranking, + "votes": [ + {"option_id": item, "vote": 1, "reciprocal_rank_score": f"1/{rank}"} + for rank, item in enumerate(ranking, start=1) + ], + } + ) except (SkillExecutionError, ValueError, TypeError, KeyError) as exc: attempt["error"] = str(exc) attempts.append(attempt) metadata = _attempt_metadata(attempts) metadata["format_retry_count"] = 0 selection = { - "mode": "balanced-vote", "policy": SELECTION_POLICY, - "seed": self.topk_selection_seed, "rounds": 3, "quorum": 2, - "valid_rounds": len(rankings), "selected_option_ids": [], "scores": [], + "mode": "balanced-vote", + "policy": SELECTION_POLICY, + "seed": self.topk_selection_seed, + "rounds": 3, + "quorum": 2, + "valid_rounds": len(rankings), + "selected_option_ids": [], + "scores": [], } metadata["topk_selection"] = selection if evidence_assembled: - metadata.update({"controller_evidence_assembled": True, "topk_evidence_mode": self.topk_evidence_mode}) + metadata.update( + { + "controller_evidence_assembled": True, + "topk_evidence_mode": self.topk_evidence_mode, + } + ) if len(rankings) < 2: - raise SkillExecutionError("balanced-vote requires at least two valid rankings", metadata=metadata) - selected = aggregate_rankings(rankings, allowed, record.domain, record.field_name, - self.topk_selection_seed, self.top_k) + raise SkillExecutionError( + "balanced-vote requires at least two valid rankings", metadata=metadata + ) + selected = aggregate_rankings( + rankings, + allowed, + record.domain, + record.field_name, + self.topk_selection_seed, + self.top_k, + ) selection["selected_option_ids"] = selected - selection["scores"] = ranking_scores(rankings, allowed, record.domain, record.field_name, - self.topk_selection_seed, self.top_k) + selection["scores"] = ranking_scores( + rankings, + allowed, + record.domain, + record.field_name, + self.topk_selection_seed, + self.top_k, + ) canonical = self.category_catalog.resolve_option_ids(selected, self.top_k) labels = {item["category"]: item for item in self.category_catalog.labels()} - return Observation("SELECT_CATEGORY_TOPK", "success", "Balanced Top-K vote", - {"standard_candidates": [labels[item] for item in canonical]}, metadata=metadata) + return Observation( + "SELECT_CATEGORY_TOPK", + "success", + "Balanced Top-K vote", + {"standard_candidates": [labels[item] for item in canonical]}, + metadata=metadata, + ) __all__ = [ diff --git a/research/finance_program_v1/evaluation/verify_training.py b/research/finance_program_v1/evaluation/verify_training.py index 5e3e2dc..dc38a28 100644 --- a/research/finance_program_v1/evaluation/verify_training.py +++ b/research/finance_program_v1/evaluation/verify_training.py @@ -3,6 +3,7 @@ The original frozen training verifier remains unchanged and its failed exit is preserved. This audit retains all original gates and validates the actual forty expanded layers. """ + # 审计 PEFT 序列化后的目标层集合与实际适配器权重,保留原校验器的失败记录供追溯。 from collections import Counter from pathlib import Path @@ -10,73 +11,140 @@ import json import os import sys -from io_utils import ROOT,read,put,sha,verify +from io_utils import ROOT, read, put, sha, verify from gate import validate_lora_inventory def main(): - parser=argparse.ArgumentParser();parser.add_argument('--training-root',type=Path,required=True);args=parser.parse_args() - root=args.training_root;m=verify();config=m['config'] - if sha(root/'manifest.json')!=config['training_manifest_sha256']:raise ValueError('wrong frozen training identity') - training=read(root/'manifest.json');c=training['config'] - for item in training['files']: - p=root/item['path'] - if not p.resolve().is_relative_to(root.resolve()) or sha(p)!=item['sha256']:raise ValueError('training frozen file differs') - if sha(root/'data/planner200.jsonl')!=config['training_data_sha256']:raise ValueError('training data identity differs') - for name in ('trial','formal','pipeline','archive'): - if read(root/'runs'/(name+'.exit.json'))['exit_code']!=0:raise ValueError('not all training exits succeeded') - sys.path.insert(0,str(root)) + parser = argparse.ArgumentParser() + parser.add_argument("--training-root", type=Path, required=True) + args = parser.parse_args() + root = args.training_root + m = verify() + config = m["config"] + if sha(root / "manifest.json") != config["training_manifest_sha256"]: + raise ValueError("wrong frozen training identity") + training = read(root / "manifest.json") + c = training["config"] + for item in training["files"]: + p = root / item["path"] + if not p.resolve().is_relative_to(root.resolve()) or sha(p) != item["sha256"]: + raise ValueError("training frozen file differs") + if sha(root / "data/planner200.jsonl") != config["training_data_sha256"]: + raise ValueError("training data identity differs") + for name in ("trial", "formal", "pipeline", "archive"): + if read(root / "runs" / (name + ".exit.json"))["exit_code"] != 0: + raise ValueError("not all training exits succeeded") + sys.path.insert(0, str(root)) from training_contract import validate_trial - validate_trial(read(root/'trial/proof.json'),c) - complete=read(root/'formal/completion.json') - if (complete['global_step']!=13 or complete['sources']!=200 or complete['epoch']!=1. - or complete['manifest_sha256']!=sha(root/'manifest.json')):raise ValueError('incomplete/wrong training') - rows=[json.loads(s) for s in (root/'data/planner200.jsonl').read_text(encoding='utf-8').splitlines() if s.strip()] - accounting=read(root/'formal/source-accounting.json');audit=read(root/'reviews/token-audit-01.json') - if (len(rows)!=200 or len({r['source_id'] for r in rows})!=200 or len(audit['per_source'])!=200 - or Counter(accounting['consumed_ids'])!=Counter(r['source_id'] for r in rows) - or accounting['finite_gradient_steps']!=list(range(1,14))):raise ValueError('full source accounting required') - from transformers import AutoTokenizer,AutoConfig,AutoModelForImageTextToText - tok=AutoTokenizer.from_pretrained(c['model'],local_files_only=True) - for row,stat in zip(rows,audit['per_source']): - prompt=tok.apply_chat_template(row['messages'],tokenize=False,add_generation_prompt=True,enable_thinking=False) - prefix=tok(prompt,add_special_tokens=False)['input_ids'] - full=tok(prompt+row['response']+tok.eos_token,add_special_tokens=False)['input_ids'];target=full[len(prefix):] - if (row['source_id']!=stat['source_id'] or full[:len(prefix)]!=prefix or len(full)!=stat['length'] - or len(target)!=stat['supervised_tokens'] or len(full)>c['max_length_limit'] - or tok.decode(target,skip_special_tokens=False)!=row['response']+tok.eos_token - or full[-1]!=tok.eos_token_id):raise ValueError('independent full token/mask/EOS audit failed') + + validate_trial(read(root / "trial/proof.json"), c) + complete = read(root / "formal/completion.json") + if ( + complete["global_step"] != 13 + or complete["sources"] != 200 + or complete["epoch"] != 1.0 + or complete["manifest_sha256"] != sha(root / "manifest.json") + ): + raise ValueError("incomplete/wrong training") + rows = [ + json.loads(s) + for s in (root / "data/planner200.jsonl").read_text(encoding="utf-8").splitlines() + if s.strip() + ] + accounting = read(root / "formal/source-accounting.json") + audit = read(root / "reviews/token-audit-01.json") + if ( + len(rows) != 200 + or len({r["source_id"] for r in rows}) != 200 + or len(audit["per_source"]) != 200 + or Counter(accounting["consumed_ids"]) != Counter(r["source_id"] for r in rows) + or accounting["finite_gradient_steps"] != list(range(1, 14)) + ): + raise ValueError("full source accounting required") + from transformers import AutoTokenizer, AutoConfig, AutoModelForImageTextToText + + tok = AutoTokenizer.from_pretrained(c["model"], local_files_only=True) + for row, stat in zip(rows, audit["per_source"]): + prompt = tok.apply_chat_template( + row["messages"], tokenize=False, add_generation_prompt=True, enable_thinking=False + ) + prefix = tok(prompt, add_special_tokens=False)["input_ids"] + full = tok(prompt + row["response"] + tok.eos_token, add_special_tokens=False)["input_ids"] + target = full[len(prefix) :] + if ( + row["source_id"] != stat["source_id"] + or full[: len(prefix)] != prefix + or len(full) != stat["length"] + or len(target) != stat["supervised_tokens"] + or len(full) > c["max_length_limit"] + or tok.decode(target, skip_special_tokens=False) != row["response"] + tok.eos_token + or full[-1] != tok.eos_token_id + ): + raise ValueError("independent full token/mask/EOS audit failed") import torch from accelerate import init_empty_weights from safetensors.torch import load_file - final=root/'formal/final';adapter=final/'adapter_model.safetensors' - if sha(adapter)!=complete['adapter_sha256'] or sha(final/'adapter_config.json')!=complete['adapter_config_sha256']: - raise ValueError('final adapter/config bytes changed') - tensors=load_file(str(adapter),device='cpu') - if (not tensors or not all(torch.isfinite(t).all().item() for t in tensors.values()) - or not any('lora_B' in n and torch.count_nonzero(t).item() for n,t in tensors.items())): - raise ValueError('adapter nonfinite/empty/not updated') - baseconfig=AutoConfig.from_pretrained(c['model'],local_files_only=True) - with init_empty_weights():model=AutoModelForImageTextToText.from_config(baseconfig,dtype=torch.float16,attn_implementation='sdpa') - if not all(p.device.type=='meta' for p in model.parameters()) or torch.cuda.is_initialized(): - raise RuntimeError('architecture audit must remain meta-only without GPU initialization') - shapes={n:[layer.out_features,layer.in_features] for n,layer in model.named_modules() if isinstance(layer,torch.nn.Linear)} - inventory=[{'name':n,'shape':list(t.shape)} for n,t in tensors.items()] - lora_config=read(final/'adapter_config.json') - if lora_config['base_model_name_or_path']!=c['model']:raise ValueError('wrong adapter base model') - validation=validate_lora_inventory(lora_config,inventory,read(root/'formal/trainable-parameters.json')['targets'],shapes) - for item in read(root/'model-identity.json')['files']: - if sha(Path(c['model'])/item['path'])!=item['sha256']:raise ValueError('original base files changed') - result={'independent_cpu_audit_passed':True,'all_200_full_token_masks_exact':True, - 'global_step':13,'unique_sources':200,'epoch':1.,'adapter_tensors':len(tensors), - 'adapter_sha256':sha(adapter),'adapter_config_sha256':sha(final/'adapter_config.json'), - 'adapter_language_only_finite_nonzero':True,'base_all_files_sha_unchanged':True, - 'manifest_sha256':sha(root/'manifest.json'),'no_gpu_model_or_eval_launched':True, - 'cpu_validator_version':2,'verifier_sha256':sha(ROOT/'verify_training.py'), - 'validator_manifest_sha256':sha(ROOT/'manifest.json'),'target_inventory_validation':validation, - 'original_failed_verifier_preserved':True,'architecture_meta_only':True} - put(root/'reviews/post-training-cpu-proof.json',result) + + final = root / "formal/final" + adapter = final / "adapter_model.safetensors" + if ( + sha(adapter) != complete["adapter_sha256"] + or sha(final / "adapter_config.json") != complete["adapter_config_sha256"] + ): + raise ValueError("final adapter/config bytes changed") + tensors = load_file(str(adapter), device="cpu") + if ( + not tensors + or not all(torch.isfinite(t).all().item() for t in tensors.values()) + or not any("lora_B" in n and torch.count_nonzero(t).item() for n, t in tensors.items()) + ): + raise ValueError("adapter nonfinite/empty/not updated") + baseconfig = AutoConfig.from_pretrained(c["model"], local_files_only=True) + with init_empty_weights(): + model = AutoModelForImageTextToText.from_config( + baseconfig, dtype=torch.float16, attn_implementation="sdpa" + ) + if not all(p.device.type == "meta" for p in model.parameters()) or torch.cuda.is_initialized(): + raise RuntimeError("architecture audit must remain meta-only without GPU initialization") + shapes = { + n: [layer.out_features, layer.in_features] + for n, layer in model.named_modules() + if isinstance(layer, torch.nn.Linear) + } + inventory = [{"name": n, "shape": list(t.shape)} for n, t in tensors.items()] + lora_config = read(final / "adapter_config.json") + if lora_config["base_model_name_or_path"] != c["model"]: + raise ValueError("wrong adapter base model") + validation = validate_lora_inventory( + lora_config, inventory, read(root / "formal/trainable-parameters.json")["targets"], shapes + ) + for item in read(root / "model-identity.json")["files"]: + if sha(Path(c["model"]) / item["path"]) != item["sha256"]: + raise ValueError("original base files changed") + result = { + "independent_cpu_audit_passed": True, + "all_200_full_token_masks_exact": True, + "global_step": 13, + "unique_sources": 200, + "epoch": 1.0, + "adapter_tensors": len(tensors), + "adapter_sha256": sha(adapter), + "adapter_config_sha256": sha(final / "adapter_config.json"), + "adapter_language_only_finite_nonzero": True, + "base_all_files_sha_unchanged": True, + "manifest_sha256": sha(root / "manifest.json"), + "no_gpu_model_or_eval_launched": True, + "cpu_validator_version": 2, + "verifier_sha256": sha(ROOT / "verify_training.py"), + "validator_manifest_sha256": sha(ROOT / "manifest.json"), + "target_inventory_validation": validation, + "original_failed_verifier_preserved": True, + "architecture_meta_only": True, + } + put(root / "reviews/post-training-cpu-proof.json", result) print(json.dumps(result)) -if __name__=='__main__':main() +if __name__ == "__main__": + main() diff --git a/research/finance_program_v1/evaluation/watch.py b/research/finance_program_v1/evaluation/watch.py index 1265ce3..8525c19 100644 --- a/research/finance_program_v1/evaluation/watch.py +++ b/research/finance_program_v1/evaluation/watch.py @@ -1,4 +1,5 @@ """Detached CPU watcher; no GPU allocations before completed training acceptance.""" + # 监控器先在 CPU 上核对训练退出状态与审计身份,通过门禁后才检查资源并调度后续评估。 import argparse import datetime @@ -8,152 +9,316 @@ import sys import time import traceback -from io_utils import ROOT,read,put,sha,verify -from gate import training_ready,cpu_proof_identity +from io_utils import ROOT, read, put, sha, verify +from gate import training_ready, cpu_proof_identity -def now():return datetime.datetime.now(datetime.timezone.utc).isoformat() +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() -def live(pid,needle): - p=Path('/proc')/str(pid) +def live(pid, needle): + p = Path("/proc") / str(pid) try: - return bool(p.exists() and needle in (p/'cmdline').read_bytes().decode(errors='replace') - and (p/'stat').read_text().split()[2]!='Z') - except (FileNotFoundError,ProcessLookupError):return False + return bool( + p.exists() + and needle in (p / "cmdline").read_bytes().decode(errors="replace") + and (p / "stat").read_text().split()[2] != "Z" + ) + except (FileNotFoundError, ProcessLookupError): + return False -def event(kind,**value): - folder=ROOT/'runs/events';folder.mkdir(parents=True,exist_ok=True) - put(folder/('%05d.json'%(len(list(folder.glob('*.json')))+1)),{'kind':kind,'time':now(),**value}) - print(kind,now(),flush=True) +def event(kind, **value): + folder = ROOT / "runs/events" + folder.mkdir(parents=True, exist_ok=True) + put( + folder / ("%05d.json" % (len(list(folder.glob("*.json"))) + 1)), + {"kind": kind, "time": now(), **value}, + ) + print(kind, now(), flush=True) def parent_state(c): - root=Path(c['training_root']) + root = Path(c["training_root"]) + def optional(n): - try:return read(root/n) if (root/n).is_file() else None - except __import__('json').JSONDecodeError:return None # a stage writer may still be flushing a new receipt - worker=optional('runs/worker.json');formal=optional('runs/formal.pid.json') - exits={k:optional('runs/'+k+'.exit.json') for k in ('trial','formal','pipeline','archive')} - return {'manifest_sha256':sha(root/'manifest.json'), - 'writer_live':any(live(p['pid'],needle) for p,needle in ((worker,'pipeline.py'),(formal,'train_student.py')) if p), - 'exits':{k:v['exit_code'] if v else None for k,v in exits.items()}, - 'completion':optional('formal/completion.json'),'cpu_proof':optional('reviews/post-training-cpu-proof.json'), - 'adapter_sha256':sha(Path(c['adapter'])/'adapter_model.safetensors') if (Path(c['adapter'])/'adapter_model.safetensors').is_file() else None} + try: + return read(root / n) if (root / n).is_file() else None + except __import__("json").JSONDecodeError: + return None # a stage writer may still be flushing a new receipt + + worker = optional("runs/worker.json") + formal = optional("runs/formal.pid.json") + exits = { + k: optional("runs/" + k + ".exit.json") for k in ("trial", "formal", "pipeline", "archive") + } + return { + "manifest_sha256": sha(root / "manifest.json"), + "writer_live": any( + live(p["pid"], needle) + for p, needle in ((worker, "pipeline.py"), (formal, "train_student.py")) + if p + ), + "exits": {k: v["exit_code"] if v else None for k, v in exits.items()}, + "completion": optional("formal/completion.json"), + "cpu_proof": optional("reviews/post-training-cpu-proof.json"), + "adapter_sha256": ( + sha(Path(c["adapter"]) / "adapter_model.safetensors") + if (Path(c["adapter"]) / "adapter_model.safetensors").is_file() + else None + ), + } def cpu_proof(c): - state=parent_state(c);root=Path(c['training_root']) - if state['manifest_sha256']!=c['training_manifest_sha256']:raise ValueError('parent signature mismatch') - if any(v not in (0,None) for v in state['exits'].values()):raise RuntimeError('training stage failed; evaluation not authorized') - if state['writer_live'] or any(v!=0 for v in state['exits'].values()):return False - if not state['cpu_proof']: - env=dict(os.environ,CUDA_VISIBLE_DEVICES='',PYTHONDONTWRITEBYTECODE='1',HF_HUB_OFFLINE='1',TOKENIZERS_PARALLELISM='false') - with (ROOT/'runs/training-cpu-verify.log').open('xb') as log: - p=subprocess.run([c['python'],'-B',str(ROOT/'verify_training.py'),'--training-root',str(root)],cwd=ROOT,env=env, - stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT) - put(ROOT/'runs/training-cpu-verify.exit.json',{'exit_code':p.returncode,'time':now()}) - if p.returncode:raise RuntimeError('independent training CPU verification failed') - state=parent_state(c) - if not training_ready(state,c['training_manifest_sha256']):raise ValueError('final adapter/CPU proof gate failed') - cfg=Path(c['adapter'])/'adapter_config.json' - if not cpu_proof_identity(state['cpu_proof'],sha(cfg),state['completion']['adapter_config_sha256'], - sha(ROOT/'verify_training.py'),sha(ROOT/'manifest.json')): - raise ValueError('CPU proof config or full validator identity differs') - put(ROOT/'runs/training-anchor.json',{'training_manifest_sha256':state['manifest_sha256'], - 'adapter_sha256':state['adapter_sha256'],'adapter_config_sha256':sha(cfg), - 'completion_sha256':sha(root/'formal/completion.json'), - 'cpu_proof_sha256':sha(root/'reviews/post-training-cpu-proof.json'), - 'parent_archive':read(root/'exports/final-01/archive.json'),'accepted_at':now()}) + state = parent_state(c) + root = Path(c["training_root"]) + if state["manifest_sha256"] != c["training_manifest_sha256"]: + raise ValueError("parent signature mismatch") + if any(v not in (0, None) for v in state["exits"].values()): + raise RuntimeError("training stage failed; evaluation not authorized") + if state["writer_live"] or any(v != 0 for v in state["exits"].values()): + return False + if not state["cpu_proof"]: + env = dict( + os.environ, + CUDA_VISIBLE_DEVICES="", + PYTHONDONTWRITEBYTECODE="1", + HF_HUB_OFFLINE="1", + TOKENIZERS_PARALLELISM="false", + ) + with (ROOT / "runs/training-cpu-verify.log").open("xb") as log: + p = subprocess.run( + [c["python"], "-B", str(ROOT / "verify_training.py"), "--training-root", str(root)], + cwd=ROOT, + env=env, + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + ) + put(ROOT / "runs/training-cpu-verify.exit.json", {"exit_code": p.returncode, "time": now()}) + if p.returncode: + raise RuntimeError("independent training CPU verification failed") + state = parent_state(c) + if not training_ready(state, c["training_manifest_sha256"]): + raise ValueError("final adapter/CPU proof gate failed") + cfg = Path(c["adapter"]) / "adapter_config.json" + if not cpu_proof_identity( + state["cpu_proof"], + sha(cfg), + state["completion"]["adapter_config_sha256"], + sha(ROOT / "verify_training.py"), + sha(ROOT / "manifest.json"), + ): + raise ValueError("CPU proof config or full validator identity differs") + put( + ROOT / "runs/training-anchor.json", + { + "training_manifest_sha256": state["manifest_sha256"], + "adapter_sha256": state["adapter_sha256"], + "adapter_config_sha256": sha(cfg), + "completion_sha256": sha(root / "formal/completion.json"), + "cpu_proof_sha256": sha(root / "reviews/post-training-cpu-proof.json"), + "parent_archive": read(root / "exports/final-01/archive.json"), + "accepted_at": now(), + }, + ) # Preserve the exact newly trained bytes alongside evaluation evidence, not only an external path. - for source,name in [(root/'manifest.json','manifest.json'),(root/'formal/completion.json','completion.json'), - (root/'reviews/post-training-cpu-proof.json','cpu-proof.json'), - (Path(c['adapter'])/'adapter_model.safetensors','adapter_model.safetensors'), - (cfg,'adapter_config.json')]: - target=ROOT/'evidence/training'/name;target.parent.mkdir(parents=True,exist_ok=True) - with source.open('rb') as src,target.open('xb') as dst:__import__('shutil').copyfileobj(src,dst) + for source, name in [ + (root / "manifest.json", "manifest.json"), + (root / "formal/completion.json", "completion.json"), + (root / "reviews/post-training-cpu-proof.json", "cpu-proof.json"), + (Path(c["adapter"]) / "adapter_model.safetensors", "adapter_model.safetensors"), + (cfg, "adapter_config.json"), + ]: + target = ROOT / "evidence/training" / name + target.parent.mkdir(parents=True, exist_ok=True) + with source.open("rb") as src, target.open("xb") as dst: + __import__("shutil").copyfileobj(src, dst) return True def resource(c): - rows=subprocess.check_output(['nvidia-smi','--query-gpu=index,uuid,memory.free','--format=csv,noheader,nounits'],text=True) - selected=[list(map(str.strip,line.split(','))) for line in rows.splitlines() if line.split(',')[0].strip()==c['gpu_index']] - if len(selected)!=1 or selected[0][1]!=c['gpu_uuid']:raise ValueError('physicalGPU0 UUID changed') - apps=subprocess.check_output(['nvidia-smi','--query-compute-apps=gpu_uuid,pid','--format=csv,noheader,nounits'],text=True) - busy=any(line.split(',')[0].strip()==c['gpu_uuid'] for line in apps.splitlines()) - return {'uuid':selected[0][1],'free_mib':int(selected[0][2]),'compute_busy':busy,'ready':not busy and int(selected[0][2])>=30000} - - -def stage(c,name,args,env): - begin=now() - with (ROOT/'runs'/(name+'.log')).open('xb') as log: - process=subprocess.Popen([c['python'],'-u','-B',*args],cwd=ROOT,env=env,stdin=subprocess.DEVNULL, - stdout=log,stderr=subprocess.STDOUT) - put(ROOT/'runs'/(name+'.pid.json'),{'pid':process.pid,'started_at':begin,'args':args}) - try:code=process.wait(timeout=c['stage_timeout_seconds']) + rows = subprocess.check_output( + ["nvidia-smi", "--query-gpu=index,uuid,memory.free", "--format=csv,noheader,nounits"], + text=True, + ) + selected = [ + list(map(str.strip, line.split(","))) + for line in rows.splitlines() + if line.split(",")[0].strip() == c["gpu_index"] + ] + if len(selected) != 1 or selected[0][1] != c["gpu_uuid"]: + raise ValueError("physicalGPU0 UUID changed") + apps = subprocess.check_output( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, + ) + busy = any(line.split(",")[0].strip() == c["gpu_uuid"] for line in apps.splitlines()) + return { + "uuid": selected[0][1], + "free_mib": int(selected[0][2]), + "compute_busy": busy, + "ready": not busy and int(selected[0][2]) >= 30000, + } + + +def stage(c, name, args, env): + begin = now() + with (ROOT / "runs" / (name + ".log")).open("xb") as log: + process = subprocess.Popen( + [c["python"], "-u", "-B", *args], + cwd=ROOT, + env=env, + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + ) + put( + ROOT / "runs" / (name + ".pid.json"), + {"pid": process.pid, "started_at": begin, "args": args}, + ) + try: + code = process.wait(timeout=c["stage_timeout_seconds"]) except subprocess.TimeoutExpired: process.terminate() - try:process.wait(timeout=30) - except subprocess.TimeoutExpired:process.kill();process.wait() - code=124 - put(ROOT/'runs'/(name+'.exit.json'),{'exit_code':code,'pid':process.pid,'started_at':begin,'ended_at':now()}) - if code:raise RuntimeError(name+' failed exit '+str(code)) - event('stage_completed',stage=name) + try: + process.wait(timeout=30) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + code = 124 + put( + ROOT / "runs" / (name + ".exit.json"), + {"exit_code": code, "pid": process.pid, "started_at": begin, "ended_at": now()}, + ) + if code: + raise RuntimeError(name + " failed exit " + str(code)) + event("stage_completed", stage=name) def run(): import fcntl - m=verify();c=m['config'];deadline=time.monotonic()+c['wait_hours']*3600 - event('WAITING_TRAINING',parent=c['training_root']);rc=1;lock=None + + m = verify() + c = m["config"] + deadline = time.monotonic() + c["wait_hours"] * 3600 + event("WAITING_TRAINING", parent=c["training_root"]) + rc = 1 + lock = None try: while not cpu_proof(c): - if time.monotonic()>=deadline:raise TimeoutError('training wait deadline reached; no evaluation started') - time.sleep(c['poll_seconds']) - event('TRAINING_ACCEPTED_WAITING_GPU0') - lock=open(c['shared_lock'],'a+') + if time.monotonic() >= deadline: + raise TimeoutError("training wait deadline reached; no evaluation started") + time.sleep(c["poll_seconds"]) + event("TRAINING_ACCEPTED_WAITING_GPU0") + lock = open(c["shared_lock"], "a+") while True: - acquired=False + acquired = False try: - fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);acquired=True - status=resource(c) - if status['ready']: - put(ROOT/'runs/resource-gate.json',status);break - except BlockingIOError:pass - if acquired:fcntl.flock(lock,fcntl.LOCK_UN) - if time.monotonic()>=deadline:raise TimeoutError('GPU0 unavailable until wait deadline; no preemption') - time.sleep(c['poll_seconds']) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + acquired = True + status = resource(c) + if status["ready"]: + put(ROOT / "runs/resource-gate.json", status) + break + except BlockingIOError: + pass + if acquired: + fcntl.flock(lock, fcntl.LOCK_UN) + if time.monotonic() >= deadline: + raise TimeoutError("GPU0 unavailable until wait deadline; no preemption") + time.sleep(c["poll_seconds"]) verify() - env=dict(os.environ,CUDA_VISIBLE_DEVICES='0',PYTHONPATH=c['deps'],PYTHONDONTWRITEBYTECODE='1', - HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',TOKENIZERS_PARALLELISM='false', - PYTHONHASHSEED='0',OMP_NUM_THREADS='8',MKL_NUM_THREADS='8') - for cohort in ('smoke','val80'): - event('STARTING_'+cohort.upper()) - stage(c,cohort,['evaluate.py','--cohort',cohort],env) - stage(c,cohort+'-audit',['replay.py','--run','runs/'+cohort,'--output','reviews/'+cohort+'-audit.json','--tokenizer'],dict(env,CUDA_VISIBLE_DEVICES='')) - put(ROOT/'runs/completion.json',{'paired_val80_sources':80,'formal_traces':160,'smoke_traces':4, - 'full_replay_accepted':True,'evaluation_manifest_sha256':sha(ROOT/'manifest.json'), - 'training_anchor':read(ROOT/'runs/training-anchor.json'),'gold_never_uploaded':True,'ended_at':now()}) - rc=0 + env = dict( + os.environ, + CUDA_VISIBLE_DEVICES="0", + PYTHONPATH=c["deps"], + PYTHONDONTWRITEBYTECODE="1", + HF_HUB_OFFLINE="1", + TRANSFORMERS_OFFLINE="1", + TOKENIZERS_PARALLELISM="false", + PYTHONHASHSEED="0", + OMP_NUM_THREADS="8", + MKL_NUM_THREADS="8", + ) + for cohort in ("smoke", "val80"): + event("STARTING_" + cohort.upper()) + stage(c, cohort, ["evaluate.py", "--cohort", cohort], env) + stage( + c, + cohort + "-audit", + [ + "replay.py", + "--run", + "runs/" + cohort, + "--output", + "reviews/" + cohort + "-audit.json", + "--tokenizer", + ], + dict(env, CUDA_VISIBLE_DEVICES=""), + ) + put( + ROOT / "runs/completion.json", + { + "paired_val80_sources": 80, + "formal_traces": 160, + "smoke_traces": 4, + "full_replay_accepted": True, + "evaluation_manifest_sha256": sha(ROOT / "manifest.json"), + "training_anchor": read(ROOT / "runs/training-anchor.json"), + "gold_never_uploaded": True, + "ended_at": now(), + }, + ) + rc = 0 except Exception as exc: - traceback.print_exc();put(ROOT/'runs/failure.json',{'type':type(exc).__name__,'message':str(exc),'time':now()}) + traceback.print_exc() + put( + ROOT / "runs/failure.json", + {"type": type(exc).__name__, "message": str(exc), "time": now()}, + ) finally: - if lock:lock.close() - put(ROOT/'runs/exit.json',{'exit_code':rc,'pid':os.getpid(),'ended_at':now()}) - result=subprocess.run([c['python'],'-B',str(ROOT/'archive.py')],cwd=ROOT,stdin=subprocess.DEVNULL) - put(ROOT/'runs/archive.exit.json',{'exit_code':result.returncode,'ended_at':now()}) + if lock: + lock.close() + put(ROOT / "runs/exit.json", {"exit_code": rc, "pid": os.getpid(), "ended_at": now()}) + result = subprocess.run( + [c["python"], "-B", str(ROOT / "archive.py")], cwd=ROOT, stdin=subprocess.DEVNULL + ) + put(ROOT / "runs/archive.exit.json", {"exit_code": result.returncode, "ended_at": now()}) return rc or result.returncode def main(): - p=argparse.ArgumentParser();p.add_argument('mode',choices=('launch','run'));a=p.parse_args() - if a.mode=='run':raise SystemExit(run()) - m=verify();put(ROOT/'runs/launch-claim.json',{'manifest_sha256':sha(ROOT/'manifest.json'),'time':now()}) - with (ROOT/'runs/watch.log').open('xb') as log: - worker=subprocess.Popen([m['config']['python'],'-u','-B',str(ROOT/'watch.py'),'run'],cwd=ROOT, - stdin=subprocess.DEVNULL,stdout=log,stderr=subprocess.STDOUT,start_new_session=True) - receipt={'pid':worker.pid,'manifest_sha256':sha(ROOT/'manifest.json'),'started_at':now(),'detached':True} - put(ROOT/'runs/worker.json',receipt);print(__import__('json').dumps(receipt)) + p = argparse.ArgumentParser() + p.add_argument("mode", choices=("launch", "run")) + a = p.parse_args() + if a.mode == "run": + raise SystemExit(run()) + m = verify() + put( + ROOT / "runs/launch-claim.json", + {"manifest_sha256": sha(ROOT / "manifest.json"), "time": now()}, + ) + with (ROOT / "runs/watch.log").open("xb") as log: + worker = subprocess.Popen( + [m["config"]["python"], "-u", "-B", str(ROOT / "watch.py"), "run"], + cwd=ROOT, + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + receipt = { + "pid": worker.pid, + "manifest_sha256": sha(ROOT / "manifest.json"), + "started_at": now(), + "detached": True, + } + put(ROOT / "runs/worker.json", receipt) + print(__import__("json").dumps(receipt)) -if __name__=='__main__':main() +if __name__ == "__main__": + main() diff --git a/research/finance_program_v1/nontraining/README.md b/research/finance_program_v1/nontraining/README.md index d368c91..9cbc502 100644 --- a/research/finance_program_v1/nontraining/README.md +++ b/research/finance_program_v1/nontraining/README.md @@ -1,24 +1,7 @@ -# Program 动态引用与事实性恢复(2026-10-11) +# 未训练 Planner 条件(NONT-D / ProgSkill) -这是用户批准的独立新版本,基于上一份115项冻结源码。历史实验及失败结果只读,不替换历史身份。本轮只加强显式动态参数引用约束,以及Program结束后的事实性恢复上下文。 +金融主干的 non-training 是 `evaluation/evaluate.py` 中的 `base` arm:原始 Qwen3.5-9B Planner,加同一 F66 Skill 库。`sft` arm 仅给 Planner 开启第一版 LoRA,Skill 仍关闭 adapter。因此两臂共享 `../evaluation/runtime/`,不再保留第二套 P14 控制器副本。 -Planner 优先使用 `arguments:{}`,由原binder补齐required参数;optional省略仍不注入。显式动态参数(canonical reference以`$state.`开头)必须是确切规范引用,不得手写对象、列表、null、数字或普通字符串。初始domain/field_name等保持原契约。无效计划在执行前拒绝,只计Planner尝试预算,保留原文和具体错误。 +从 [实验协议](../docs/EXPERIMENT_PROTOCOL.md) 和 [运行说明](../REPRODUCE.md) 阅读条件与入口。历史 P14 的 runner、下载器和源码审计不属于422配对结果,已从当前金融主干移除;原代码及文件SHA可从 [历史记录](../docs/HISTORY.md) 追溯。 -模型仍从全部 14 个可选 Skill 中自行选择步骤和顺序,每次 Planner 调用生成一个完整有序 Program。没有必选 Skill、固定完整流程示例、自动插入步骤或改写模型答案。可能生产者只表示静态可能性;元数据取得、输出发布、状态绑定以及最终终止,都必须由真实执行和冻结 guard 验证。`semantic_query`、`semantic_evidence` 与 `field_semantics` 保持各自契约含义,描述语义不能替代字段名语义。 - -核心入口文件: - -- `program_loop/planning_contracts.py`:根据 catalog 和共享校验规则生成无状态值的规划说明。 -- `program_loop/catalog_context.py`:把说明附加到每个 Skill 的原始契约库中,供 Planner 读取。 -- `program_loop/planner.py`:说明参数省略、合法引用、依赖顺序和条件性执行的使用规则。 -- `program_loop/validation.py`:静态依赖与显式动态引用约束,共享取值策略。 -- `program_loop/recovery_context.py`:纯事实性恢复摘要,不执行Skill、不改state。 -- `program_loop/controller.py`:Program级执行/反馈与全局预算循环;不在Skill间规划。 - -恢复消息从真实state与observation陈述实际成功/失败步骤、失败位置、尚未执行的尾部、证据失效与真实剩余预算。尾部是历史意图,不是强制路线;字段存在不等于已验证ready。最后一份Program也仍允许部分计划,代码不自动完成分类或赠送预算。合法终止仍由原terminal guard确认。 - -新增CPU测试只脚本化模型I/O,parser、binder、executor和guard用真实实现。`vendor/`、底层execution、Registry、P14池及`local_smoke.py`/`download_model.py`字节保持不变。完整变更与未改SHA由新source manifest记录,不以人工描述替代哈希证据。 - -用户已授权测试/审查门通过后在新远程目录单次运行同三条无标签输入、同9B基础模型、同生成参数和预算。无新adapter/训练、Val调策略、Test、依赖升级或Git提交推送。工程通过不等于模型成功;真实试跑结果及原始调用见交付后的`实验结果.md`与`SMOKE_README.md`,保留全部失败,不调prompt重复挑结果。 - -RED/GREEN、独立Spec/Quality审查、全CPU验收、完整diff、冻结新签名和证据ZIP在`reviews/`。两项修改同时施加,与历史三条只作描述性比较,不能分别归因或推广为准确率提升。DCG全文输入模式、池规模和训练方式不属本轮改动,不声称已实现导师全部行动指南。 +本次仅归纳原版逻辑,没有合入本地 recovery 的失败记忆、防重复或新预算补丁。原版仍可能出现预算耗尽、反馈覆盖和不合规模型输出,详见协议中的限制。 diff --git a/research/finance_program_v1/nontraining/batch_audit.py b/research/finance_program_v1/nontraining/batch_audit.py deleted file mode 100644 index 36902ae..0000000 --- a/research/finance_program_v1/nontraining/batch_audit.py +++ /dev/null @@ -1,142 +0,0 @@ -"""CPU recorded-I/O replay and separate local gold evaluation.""" -# 先用已记录的模型 I/O 重跑控制器并核对完整轨迹,再在独立评分入口读取私有答案。 -import argparse -from collections import Counter -import json -from pathlib import Path -from prepare_batch import ROOT,BUDGET,read,save,sha,validate_study -from batch_runner import RUN_MODE,verify_study_identity -from reviews.independent_audit_01 import RecordedBackend,AuditError,require,exact,validate_sources,validate_call,REVISION - -def audit(run,*,study_path=ROOT/'data/study.json',allow_scripted_fixture=False): - verify_study_identity(study_path) - run=Path(run); study=validate_study(read(study_path)); summary=read(run/'summary.json') - env=read(run/'environment.json'); validate_sources(ROOT,env) - for key,value in {'seed':20260928,'context_cap':32768,'max_new_tokens':512,'per_generate_max_time':90.0, - 'whole_process_timeout_seconds':7200,'whole_process_timeout_enforced_by':'external coordinator', - 'inference':'FP16 cuda:0 batch1 greedy enable_thinking=False'}.items(): exact(env[key],value,'environment '+key) - exact(summary['study_sha256'],sha(study_path),'study identity') - exact(summary['expected_ids'],study['cohorts'][summary['cohort']],'cohort identity') - exact(summary['expected_count'],len(summary['expected_ids']),'full denominator') - exact([s['id'] for s in summary['samples']],summary['expected_ids'],'sample denominator') - exact(read(run/'inputs.json')['budget'],BUDGET,'fixed budget') - paths=sorted((run/'calls').glob('call-*')) - exact([p.name for p in paths],[f'call-{i:04d}' for i in range(1,len(paths)+1)],'continuous calls') - records=[{'request':read(p/'request.json'),'result':read(p/'result.json')} for p in paths] - if summary['status']=='initialization_failure': - require(all(entry=={'id':ident,'status':'pending'} for entry,ident in zip(summary['samples'],summary['expected_ids'])), - 'initialization failure must retain only untouched pending samples') - require(not records and summary['model_calls']==0,'initialization failure cannot contain model calls') - require(isinstance(summary.get('error'),str) and bool(summary['error'].strip()),'initialization failure error record missing') - for folder in ('ranges','samples','errors'): - require(not any(p.is_file() for p in (run/folder).rglob('*')),'initialization failure has unexpected '+folder+' artifacts') - require(env.get('backend_kind') in ('production','scripted_cpu_test'),'backend evidence kind missing') - require(env['backend_kind']=='production' or allow_scripted_fixture is True,'formal audit requires production backend evidence') - if env['backend_kind']=='production' and summary['status']!='initialization_failure': - backend=read(run/'calls/backend.json') - for key,value in {'repo_id':'Qwen/Qwen3.5-9B','revision':REVISION,'parameter_devices':['cuda:0'],'parameter_dtypes':['torch.float16'], - 'offline_options':{'local_files_only':True,'trust_remote_code':False},'config_type':'qwen3_5','model_class':'Qwen3_5ForConditionalGeneration','attention_implementation':'sdpa', - 'generation':{'do_sample':False,'max_new_tokens':512,'max_time':90.,'eos_token_id':248044,'pad_token_id':248044}}.items(): exact(backend[key],value,'production backend '+key) - for record in records: validate_call(record['request'],record['result'],backend) - for record in records: - text=json.dumps(record['request']['messages'],ensure_ascii=False) - require(all(row['id'] not in text for row in study['rows']),'private ID in model messages') - from program_loop import ProgramConfig,build_program_controller - by_id={r['id']:r for r in study['rows']}; position=0; verified=0; errors=[] - for entry in summary['samples']: - if entry['status']=='pending': - require(summary['status']=='initialization_failure','pending after initialization'); continue - exact(entry['call_start'],position,'sample call start'); end=entry['call_end'] - require(type(end) is int and position<=end<=len(records),'invalid call range') - replay=RecordedBackend(records[position:end]); row=by_id[entry['id']] - input_value={'source_id':row['id'],'domain':row['domain'],'field_name':row['metadata']['field_name']} - try: - controller=build_program_controller(replay,study['registry'],study['rows'],ProgramConfig(**BUDGET)) - trace=controller.run(input_value) - except Exception as exc: - require(not replay.audit_faults,'; '.join(replay.audit_faults)) - require(entry['status']=='error','unexpected independent controller exception') - exact(f'{type(exc).__name__}: {exc}',entry['error'],'independent exception identity') - exact(read(run/'errors'/(row['id']+'.json')),{'input':input_value,'error':entry['error']},'error artifact') - errors.append({'id':row['id'],'independently_reproduced_error':entry['error']}) - else: - require(entry['status']=='completed','saved exception did not reproduce') - trace.execution_mode=RUN_MODE; actual=trace.to_dict() - exact(actual,read(run/'samples'/(row['id']+'.json')),'complete actual trace replay') - exact(entry['terminated'],trace.terminated,'termination summary') - exact(entry['budget'],trace.budget,'budget summary') - exact(entry['stop_reason'],trace.stop_reason,'stop reason summary') - if trace.planner_attempts: - first=json.loads(trace.planner_attempts[0]['messages'][1]['content']) - require(len(first['skill_library'])==14,'P14 library changed') - require('field_description' not in first.get('record',{}),'initial description exposed') - from pool_metadata import FIELDS,present - expected_metadata={k:v for k,v in row['metadata'].items() if k in FIELDS and present(v)} - for program in actual['programs']: - for step in program['steps']: - if step['call']['tool']=='GET_FIELD_METADATA' and step['status']=='success': exact(step['data']['field_metadata'],expected_metadata,'actual filtered metadata identity') - verified+=1 - replay.finish(); position=end - exact(entry,read(run/'ranges'/(row['id']+'.json')),'actual call range artifact') - exact(position,len(records),'all calls consumed') - exact(summary['model_calls'],len(records),'call summary') - for key in ('input_tokens','output_tokens'): - exact(summary[key],sum(r['result'].get(key) or 0 for r in records),'token summary '+key) - exact(summary['generation_seconds'],sum(r['result'].get('seconds') or 0 for r in records),'generation wall time') - exact(summary['terminated_count'],sum(bool(s.get('terminated')) for s in summary['samples']),'termination denominator') - return {'backend_kind':env['backend_kind'],'verified_samples':verified,'independently_verified_errors':errors,'pending_count':sum(s['status']=='pending' for s in summary['samples']), - 'model_calls':len(records),'all_calls_consumed':True,'full_trace_exact':True} - -def macro_f1(golds,predictions,labels): - scores=[] - for label in labels: - tp=sum(g==label and p==label for g,p in zip(golds,predictions)); fp=sum(g!=label and p==label for g,p in zip(golds,predictions)); fn=sum(g==label and p!=label for g,p in zip(golds,predictions)) - scores.append(2*tp/(2*tp+fp+fn) if 2*tp+fp+fn else 0.) - return sum(scores)/len(scores) if scores else 0. - -def evaluate_data(study,summary,traces,gold): - ids=summary['expected_ids']; require(len(ids)==len(set(ids)),'duplicate evaluation IDs') - require(set(ids)<=set(gold['answers']),'gold missing expected IDs') - by_id={t['id']:t['trace'] for t in traces}; require(len(by_id)==len(traces),'duplicate traces') - require(set(by_id)<=set(ids),'unexpected evaluation trace') - counts=Counter(); skills=Counter(); successes=Counter(); unavailable=Counter(); labels=[]; predictions=[] - for ident in ids: - trace=by_id.get(ident,{}); terminated=bool(trace.get('terminated')); final=trace.get('final_result') or {}; answer=gold['answers'][ident] - prediction=final.get('category') if terminated else None; level=final.get('grading_level') if terminated else None - if terminated: require(prediction in study['registry'] and study['registry'][prediction]['grading_level']==level,'invalid terminal Registry binding') - labels.append(answer['category']); predictions.append(prediction) - counts['terminated']+=terminated; counts['category_correct']+=terminated and prediction==answer['category']; counts['grading_correct']+=terminated and level==answer['grading_level']; counts['joint_correct']+=terminated and prediction==answer['category'] and level==answer['grading_level'] - history=[]; recovered=False - for program in trace.get('programs',[]): - for step in program['steps']: - tool=step['call']['tool']; skills[tool]+=1; successes[tool]+=step['status']=='success'; unavailable[tool]+=step['status']=='unavailable' - recovered |= bool(step.get('controller_intervention')) - if tool=='SELECT_CATEGORY_TOPK' and step['status']=='success': - candidates=step['data']['standard_candidates']; candidates=[c.get('category') or c.get('category_id') for c in candidates] - require(len(candidates)==5 and len(set(candidates))==5 and set(candidates)<=set(study['registry']),'invalid successful Top5') - history.append(candidates) - counts['recovered_terminated']+=terminated and recovered; counts['natural_terminated']+=terminated and not recovered - adaptive=len(trace.get('planner_attempts',[]))>1 or len(trace.get('programs',[]))>1 - counts['autonomous_adaptive_replan_terminated']+=terminated and not recovered and adaptive - counts['top5_first_hit']+=bool(history and answer['category'] in history[0]); counts['top5_final_hit']+=bool(history and answer['category'] in history[-1]); counts['top5_any_hit']+=any(answer['category'] in h for h in history) - counts['samples_with_top5']+=bool(history) - for key in ('terminated','category_correct','grading_correct','joint_correct','natural_terminated','recovered_terminated','autonomous_adaptive_replan_terminated','top5_first_hit','top5_final_hit','top5_any_hit','samples_with_top5'): counts[key]+=0 - result={'denominator':len(ids),**dict(counts),'macro_f1_supported':macro_f1(labels,predictions,gold['supported_classes']), - 'macro_f1_fixed12':macro_f1(labels,predictions,sorted(study['registry'])),'supported_class_count':len(gold['supported_classes']), - 'skills_called':dict(skills),'skills_succeeded':dict(successes),'skills_unavailable':dict(unavailable), - 'runner_seconds':summary['seconds'],**{k:summary.get(k,0) for k in ('model_calls','input_tokens','output_tokens','generation_seconds')}} - result['metric_definitions']={ - 'recovered_terminated':'Controller intervention present in at least one executed step of a legally terminated trace.', - 'natural_terminated':'Autonomous legal termination with no controller intervention; includes model-directed adaptive replanning.', - 'autonomous_adaptive_replan_terminated':'Autonomous legal termination after more than one actual planner attempt or accepted program; a subset of natural_terminated.'} - result.update({k+'_rate':counts[k]/len(ids) if ids else 0 for k in counts}) - return result - -def evaluate(run,gold_path,*,study_path=ROOT/'data/study.json'): - run=Path(run); audit(run,study_path=study_path) - return evaluate_data(read(study_path),read(run/'summary.json'),[{'id':p.stem,'trace':read(p)} for p in sorted((run/'samples').glob('*.json'))],read(gold_path)) - -def main(argv=None): - p=argparse.ArgumentParser(description=__doc__); p.add_argument('--run',type=Path,required=True); p.add_argument('--study',type=Path,default=ROOT/'data/study.json'); p.add_argument('--gold',type=Path); p.add_argument('--output',type=Path,required=True) - a=p.parse_args(argv); result=evaluate(a.run,a.gold,study_path=a.study) if a.gold else audit(a.run,study_path=a.study); save(a.output,result); print(json.dumps(result,ensure_ascii=False)); return 0 -if __name__=='__main__': raise SystemExit(main()) diff --git a/research/finance_program_v1/nontraining/batch_runner.py b/research/finance_program_v1/nontraining/batch_runner.py deleted file mode 100644 index 56856b2..0000000 --- a/research/finance_program_v1/nontraining/batch_runner.py +++ /dev/null @@ -1,80 +0,0 @@ -"""One exclusive cohort with the frozen Program controller and Backend.""" -# 按固定 cohort 执行真实控制器,并记录每个样本的模型调用区间,供独立回放逐条核对。 -import argparse -from pathlib import Path -import time -from local_smoke import Backend, environment, reserve_run -from prepare_batch import ROOT, BUDGET, read, save, sha, validate_study - -RUN_MODE='caller supplied backend I/O + real frozen executor; backend evidence in calls/' - -def verify_study_identity(study_path): - path=Path(study_path) - if read(path.with_name('study-manifest.json'))['study_sha256']!=sha(path): raise ValueError('prepared study identity changed') - return True - -#referenced by main(): run_batch(a.model,a.output,a.cohort,study_path=a.study) -def run_batch(model,output,cohort,*,study_path=ROOT/'data/study.json',backend_factory=Backend): - verify_study_identity(study_path) - study:dict=validate_study(read(study_path)) - output=reserve_run(output); started=time.perf_counter() - ids=study['cohorts'][cohort]; by_id={r['id']:r for r in study['rows']} - summary={'status':'initialization_failure','cohort':cohort,'expected_ids':ids,'expected_count':len(ids), - 'study_sha256':sha(study_path),'terminated_count':0,'samples':[{'id':i,'status':'pending'} for i in ids]} - try: - env=environment(model); env['whole_process_timeout_seconds']=7200 - env['backend_kind']='production' if backend_factory is Backend else 'scripted_cpu_test' - save(output/'environment.json',env) - save(output/'inputs.json',{'cohort':cohort,'expected_ids':ids,'study_sha256':sha(study_path),'budget':BUDGET}) - backend=backend_factory(model,output/'calls') - from program_loop import ProgramConfig,build_program_controller - config=ProgramConfig(**BUDGET); summary['status']='completed' - for entry in summary['samples']: - print(f'{cohort} start {entry["id"]}',flush=True) - row=by_id[entry['id']]; entry.update(status='error',call_start=len(backend.calls)) - controller=None - try: - # 控制器初始只暴露 domain、field_name;完整元数据需由模型选择 Skill 获取。 - controller=build_program_controller(backend,study['registry'],study['rows'],config) - # Planner 生成整段 Program,内部顺序执行;失败回到外层重规划,全程共享预算。 - # 新证据会使旧选择失效;只有消费已校验终态证据的终止 Skill 才能完成任务。 - trace=controller.run({'source_id':row['id'],'domain':row['domain'],'field_name':row['metadata']['field_name']}) - trace.execution_mode=RUN_MODE; trace.write_json(output/'samples'/(row['id']+'.json')) - entry.update(status='completed',terminated=trace.terminated,stop_reason=trace.stop_reason,budget=trace.budget) - summary['terminated_count']+=int(trace.terminated) - except Exception as exc: - entry['error']=f'{type(exc).__name__}: {exc}' - summary['status']='runner_failure' - save(output/'errors'/(row['id']+'.json'),{'input':{'source_id':row['id'],'domain':row['domain'],'field_name':row['metadata']['field_name']},'error':entry['error']}) - finally: - entry['call_end']=len(backend.calls) - save(output/'ranges'/(row['id']+'.json'),entry) - save(output/'progress'/f'{summary["samples"].index(entry)+1:04d}.json',summary) - print(f'{cohort} done {entry["id"]} {entry["status"]} terminated={entry.get("terminated",False)}',flush=True) - if backend.failures: summary['status']='backend_failure' - summary['backend_errors']=backend.failures - except Exception as exc: - if summary['status']!='initialization_failure': summary['status']='runner_failure' - summary['error']=f'{type(exc).__name__}: {exc}' - finally: - records=[]; record_errors=[] - for path in sorted((output/'calls').glob('call-*')): - try: records.append(read(path/'result.json')) - except Exception as exc: record_errors.append({'call':path.name,'error':f'{type(exc).__name__}: {exc}'}) - if record_errors: - summary['record_errors']=record_errors - if summary['status']!='initialization_failure': summary['status']='runner_failure' - summary.update(model_calls=len(records),input_tokens=sum(r.get('input_tokens') or 0 for r in records), - output_tokens=sum(r.get('output_tokens') or 0 for r in records),generation_seconds=sum(r.get('seconds') or 0 for r in records),seconds=time.perf_counter()-started) - save(output/'summary.json',summary) - return 0 if summary['status']=='completed' else 2 - -def main(argv=None): - p=argparse.ArgumentParser(description=__doc__); - p.add_argument('--model',required=True,type=Path); - p.add_argument('--output',required=True,type=Path) - p.add_argument('--cohort',required=True,choices=('smoke','pilot','expanded')); - p.add_argument('--study',type=Path,default=ROOT/'data/study.json') - a=p.parse_args(argv); - return run_batch(a.model,a.output,a.cohort,study_path=a.study) -if __name__=='__main__': raise SystemExit(main()) diff --git a/research/finance_program_v1/nontraining/download_model.py b/research/finance_program_v1/nontraining/download_model.py deleted file mode 100644 index f118372..0000000 --- a/research/finance_program_v1/nontraining/download_model.py +++ /dev/null @@ -1,104 +0,0 @@ -"""Pinned, token-free official checkpoint download; never executes remote code.""" -import hashlib -import json -from pathlib import Path -import re - -REPO = 'Qwen/Qwen3.5-9B' -MODEL_DIR = Path(__file__).resolve().parent / 'models' / 'Qwen3.5-9B' -ALLOWED = {'config.json', 'generation_config.json', 'tokenizer.json', 'tokenizer_config.json', - 'special_tokens_map.json', 'chat_template.json', 'chat_template.jinja', 'vocab.json', - 'merges.txt', 'added_tokens.json', 'model.safetensors.index.json'} - - -def write_json(path, value): - with Path(path).open('x', encoding='utf-8') as stream: - json.dump(value, stream, ensure_ascii=False, indent=2, allow_nan=False) - stream.write('\n') - - -def sha256(path): - digest = hashlib.sha256() - with Path(path).open('rb') as stream: - for block in iter(lambda: stream.read(1024 * 1024), b''): - digest.update(block) - return digest.hexdigest() - - -def allowed(name): - return isinstance(name, str) and (name in ALLOWED or re.fullmatch(r'model(?:\.safetensors)?(?:-\d+-of-\d+)?\.safetensors', name) is not None) - - -def validate_identity(identity): - if identity.get('repo_id') != REPO or not re.fullmatch('[0-9a-f]{40}', identity.get('revision', '')): - raise ValueError('invalid official model identity') - entries = identity.get('files', []) - names = [e.get('path') for e in entries] - if not entries or len(set(names)) != len(names) or not all(allowed(n) for n in names): - raise ValueError('invalid model identity file inventory') - if 'config.json' not in names or 'tokenizer.json' not in names or not any(n.endswith('.safetensors') for n in names): - raise ValueError('incomplete model identity') - if any(type(e.get('bytes')) is not int or e['bytes'] < 0 for e in entries): - raise ValueError('model identity requires expected file sizes') - if any(e.get('expected_sha256') is not None and not re.fullmatch('[0-9a-f]{64}', e['expected_sha256']) for e in entries): - raise ValueError('invalid model identity expected hash') - - -def download_model(model_dir=MODEL_DIR, *, api=None, snapshot=None): - model_dir = Path(model_dir) - model_dir.mkdir(parents=True, exist_ok=True) - manifest_path = model_dir / 'model-manifest.json' - if manifest_path.exists(): - raise FileExistsError(f'completed manifest already exists: {manifest_path}') - identity_path = model_dir / 'download-identity.json' - if api is None or snapshot is None: - from huggingface_hub import HfApi, snapshot_download - api = api or HfApi(token=False) - snapshot = snapshot or snapshot_download - if identity_path.exists(): - identity = json.loads(identity_path.read_text(encoding='utf-8')) - else: - if any(model_dir.iterdir()): - raise ValueError('unidentified existing checkpoint directory') - info = api.model_info(REPO, files_metadata=True, token=False) - identity = {'repo_id': REPO, 'revision': info.sha, - 'files': [{'path': f.rfilename, 'bytes': f.size, - 'expected_sha256': getattr(getattr(f, 'lfs', None), 'sha256', None)} - for f in info.siblings if allowed(f.rfilename)]} - validate_identity(identity) - write_json(identity_path, identity) - validate_identity(identity) - snapshot(repo_id=REPO, revision=identity['revision'], local_dir=str(model_dir), - allow_patterns=[e['path'] for e in identity['files']], token=False) - files = [] - for expected in identity['files']: - path = model_dir / expected['path'] - if path.is_symlink() or not path.is_file() or path.stat().st_size != expected['bytes']: - raise ValueError(f'download file size/path mismatch: {expected["path"]}') - actual_hash = sha256(path) - if expected.get('expected_sha256') and actual_hash != expected['expected_sha256']: - raise ValueError(f'download file trusted hash mismatch: {expected["path"]}') - files.append({**expected, 'sha256': actual_hash}) - manifest = {'repo_id': REPO, 'revision': identity['revision'], 'total_bytes': sum(e['bytes'] for e in files), - 'download_identity_sha256': sha256(identity_path), 'files': files} - expected = {e['path'] for e in files} | {'download-identity.json'} - actual = {p.relative_to(model_dir).as_posix() for p in model_dir.rglob('*') if p.is_file() and '.cache' not in p.relative_to(model_dir).parts} - if actual != expected: - raise ValueError('download file inventory mismatch') - write_json(manifest_path, manifest) - verify_model(model_dir) - return manifest - - -def verify_model(model_dir): - """Read-only complete inventory, byte and hash gate before model loading.""" - model_dir = Path(model_dir) - identity_path = model_dir / 'download-identity.json' - identity = json.loads(identity_path.read_text(encoding='utf-8')) - manifest = json.loads(identity_path.read_text(encoding='utf-8')) - return manifest - - -if __name__ == '__main__': - result = download_model() - print(json.dumps({'repo_id': result['repo_id'], 'revision': result['revision'], 'total_bytes': result['total_bytes']})) diff --git a/research/finance_program_v1/nontraining/local_smoke.py b/research/finance_program_v1/nontraining/local_smoke.py deleted file mode 100644 index 3285fb1..0000000 --- a/research/finance_program_v1/nontraining/local_smoke.py +++ /dev/null @@ -1,240 +0,0 @@ -"""Three unlabelled bounded engineering smokes through the frozen Program core.""" -import argparse -from copy import deepcopy -from importlib.metadata import PackageNotFoundError, distribution -import json -import os -from pathlib import Path -import platform -import shutil -import sys -import time - -from download_model import sha256, verify_model, write_json - -OFFLINE = {'local_files_only': True, 'trust_remote_code': False} -CONTEXT_CAP = 32768 -OUTPUT_CAP = 512 -SEED = 20260928 - - -class ContextBudgetExceeded(ValueError): - def __init__(self, tokens): - self.input_tokens = tokens - super().__init__(f'context budget exceeded: {tokens}+{OUTPUT_CAP}>{CONTEXT_CAP}; no truncation') - - -def reserve_run(path): - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True) - #rm -r path - if path.exists(): - shutil.rmtree(path) - path.mkdir() # Atomic directory creation; must precede any CUDA allocation. - return path - - -def smoke_inputs(): - definitions = [('account_balance', '账户余额'), ('contact_phone', '客户联系手机号'), - ('invoice_amount', '发票金额'), ('customer_name', '客户姓名'), - ('order_id', '订单标识'), ('transaction_date', '交易日期')] - registry = {name: {'label': desc, 'description': desc, 'grading_level': 'L2'} for name, desc in definitions} - rows = [{'id': ident, 'domain': '金融', 'metadata': {'field_name': name, 'field_description': desc}} - for ident, name, desc in [('local-balance', 'account_balance', '账户当前余额'), - ('local-phone', 'customer_phone', '客户联系手机号'), - ('local-invoice', 'invoice_amount', '发票金额')]] - return registry, rows - - -def generation_options(config, tokenizer): - eos = getattr(config, 'eos_token_id', None) - if eos is None: - eos = getattr(tokenizer, 'eos_token_id', None) - if eos is None: - raise ValueError('actual model/tokenizer EOS is required') - pad = getattr(tokenizer, 'pad_token_id', None) - if pad is None: - pad = getattr(config, 'pad_token_id', None) - if pad is None: - pad = eos[0] if isinstance(eos, list) else eos - return {'do_sample': False, 'max_new_tokens': OUTPUT_CAP, 'max_time': 90.0, - 'eos_token_id': eos, 'pad_token_id': pad} - - -def encode_messages(tokenizer, messages): - prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False) - encoded = tokenizer(prompt, return_tensors='pt', truncation=False) - tokens = encoded['input_ids'].shape[1] - if encoded['input_ids'].shape[0] != 1: - raise ValueError('batch size must be one') - if tokens + OUTPUT_CAP > CONTEXT_CAP: - raise ContextBudgetExceeded(tokens) - return encoded - - -def environment(model_path): - packages = {} - for package in ('torch', 'transformers', 'accelerate', 'huggingface_hub', 'safetensors'): - try: - packages[package] = distribution(package).metadata.get('Version') - except PackageNotFoundError: - packages[package] = None - root = Path(__file__).resolve().parent - sources = {p.relative_to(root).as_posix(): sha256(p) for base in ('program_loop', 'vendor', 'tools') - for p in (root / base).rglob('*') if p.is_file() and '__pycache__' not in p.parts} - return {'pid': os.getpid(), 'python': sys.version, 'executable': sys.executable, 'platform': platform.platform(), - 'packages': packages, 'model_path': str(Path(model_path).resolve()), 'core_source_sha256': sources, - 'seed': SEED, 'context_cap': CONTEXT_CAP, 'max_new_tokens': OUTPUT_CAP, 'per_generate_max_time': 90.0, - 'whole_process_timeout_seconds': 900, 'whole_process_timeout_enforced_by': 'external coordinator', - 'inference': 'FP16 cuda:1 batch1 greedy enable_thinking=False'} - - -class Backend: - def __init__(self, model_path, call_dir): - self.call_dir = Path(call_dir) - self.call_dir.mkdir(parents=True, exist_ok=True) - self.calls = [] - self.failures = [] - self.identity = verify_model(model_path) - import torch - from transformers import AutoConfig, AutoModelForImageTextToText, AutoTokenizer - self.torch = torch - if not torch.cuda.is_available(): - raise RuntimeError('CUDA is required; no CPU/offload fallback') - cuda_device=1 - torch.cuda.set_device(cuda_device) - free, total = torch.cuda.mem_get_info(cuda_device) - if free <= 0: - raise RuntimeError(f'cuda:{cuda_device} has no free device memory') - torch.manual_seed(SEED) - torch.cuda.manual_seed_all(SEED) - config = AutoConfig.from_pretrained(str(model_path), **OFFLINE) - self.tokenizer = AutoTokenizer.from_pretrained(str(model_path), **OFFLINE) - if config.model_type != 'qwen3_5': - raise ValueError(f'unsupported official checkpoint config: {config.model_type}') - self.attention = 'sdpa' if hasattr(torch.nn.functional, 'scaled_dot_product_attention') else 'eager' - self.model = AutoModelForImageTextToText.from_pretrained(str(model_path), **OFFLINE, dtype=torch.float16, - device_map={'': f'cuda:{cuda_device}'}, attn_implementation=self.attention) - self.model.eval() - self.parameter_devices = sorted({str(p.device) for p in self.model.parameters()}) - self.parameter_dtypes = sorted({str(p.dtype) for p in self.model.parameters() if p.is_floating_point()}) - if self.parameter_devices != [f'cuda:{cuda_device}'] or self.parameter_dtypes != ['torch.float16']: - raise RuntimeError(f'checkpoint must be entirely FP16 cuda:{cuda_device}: {self.parameter_devices}, {self.parameter_dtypes}') - self.options = generation_options(self.model.generation_config, self.tokenizer) - write_json(self.call_dir / 'backend.json', {'repo_id': self.identity.get('repo_id'), 'revision': self.identity['revision'], - 'model_class': type(self.model).__name__, 'config_type': config.model_type, - 'attention_implementation': self.attention, 'parameter_devices': self.parameter_devices, - 'parameter_dtypes': self.parameter_dtypes, 'cuda_device': torch.cuda.get_device_name(cuda_device), - 'torch_cuda_version': torch.version.cuda, 'free_bytes_before_load': free, 'total_device_bytes': total, - 'generation': self.options, 'offline_options': OFFLINE}) - - def __call__(self, messages): - return self.generate(messages) - - def generate(self, messages): - call = self.call_dir / f'call-{len(self.calls) + 1:04d}' - call.mkdir() - self.calls.append(str(call)) - started = time.perf_counter() - result = {'messages': deepcopy(messages), 'raw_text': None, 'input_tokens': None, 'output_tokens': None, - 'input_devices': [], 'parameter_devices': self.parameter_devices, 'parameter_dtypes': self.parameter_dtypes, - 'attention_implementation': self.attention, 'generation': self.options, - 'truncation_at_budget': False, 'error': None} - write_json(call / 'request.json', {'messages': messages, 'generation': self.options}) - try: - encoded = encode_messages(self.tokenizer, messages) - result['input_tokens'] = encoded['input_ids'].shape[1] - encoded = {key: value.to('cuda:1') for key, value in encoded.items()} - result['input_devices'] = sorted({str(value.device) for value in encoded.values()}) - if result['input_devices'] != ['cuda:1']: - raise RuntimeError(f'input tensors must be on cuda:1: {result["input_devices"]}') - self.torch.cuda.reset_peak_memory_stats(1) - self.torch.cuda.synchronize(1) - with self.torch.inference_mode(): - output = self.model.generate(**encoded, **self.options) - self.torch.cuda.synchronize(1) - generated = output[0, result['input_tokens']:] - result['output_tokens'] = len(generated) - result['truncation_at_budget'] = len(generated) >= OUTPUT_CAP - result['raw_text'] = self.tokenizer.decode(generated, skip_special_tokens=True, clean_up_tokenization_spaces=False) - return result['raw_text'] - except Exception as exc: - if isinstance(exc, ContextBudgetExceeded): - result['input_tokens'] = exc.input_tokens - result['error'] = f'{type(exc).__name__}: {exc}' - self.failures.append({'call': str(call), 'error': result['error']}) - raise - finally: - result['seconds'] = time.perf_counter() - started - result['memory'] = {} - result['telemetry_errors'] = {} - for name in ('memory_allocated', 'memory_reserved', 'max_memory_allocated'): - try: - result['memory'][name] = getattr(self.torch.cuda, name)(1) - except Exception as exc: - result['memory'][name] = None - result['telemetry_errors'][name] = f'{type(exc).__name__}: {exc}' - write_json(call / 'result.json', result) - - -def main(argv=None, *, backend_factory=Backend): - parser = argparse.ArgumentParser(description='Three unlabelled local GPU engineering smokes; no accuracy metric') - parser.add_argument('--model', type=Path, required=True) - parser.add_argument('--output', type=Path, required=True) - args = parser.parse_args(argv) - try: - output = reserve_run(args.output) - except Exception as exc: - print(f'{type(exc).__name__}: {exc}', file=sys.stderr) - return 2 - started = time.perf_counter() - summary = {'status': 'initialization_failure', 'terminated_count': 0, 'accepted_plans': 0, - 'planner_attempts': 0, 'skill_steps': 0, 'backend_errors': [], 'samples': []} - try: - write_json(output / 'environment.json', environment(args.model)) - (output / 'samples').mkdir() - backend = backend_factory(args.model, output / 'calls') - from program_loop import ProgramConfig, build_program_controller - config = ProgramConfig(max_programs=3, max_program_steps=10, max_skill_steps=12, - max_planner_attempts=4, max_identical_calls=1) - registry, rows = smoke_inputs() - write_json(output / 'inputs.json', {'registry': registry, 'rows': rows, 'budget': vars(config)}) - summary['status'] = 'completed' - def generate(messages): - try: - return backend(messages) - except Exception as exc: - summary['backend_errors'].append({'error': f'{type(exc).__name__}: {exc}'}) - raise - for row in rows: - controller = build_program_controller(generate, registry, rows, config) - trace = controller.run({'source_id': row['id'], 'domain': row['domain'], 'field_name': row['metadata']['field_name']}) - trace.execution_mode = 'caller supplied backend I/O + real frozen executor; backend evidence in calls/' - trace.write_json(output / 'samples' / (row['id'] + '.json')) - summary['terminated_count'] += int(trace.terminated) - summary['accepted_plans'] += trace.budget['programs'] - summary['planner_attempts'] += trace.budget['planner_attempts'] - summary['skill_steps'] += trace.budget['skill_steps'] - summary['samples'].append({'id': row['id'], 'terminated': trace.terminated, 'stop_reason': trace.stop_reason, - 'budget': trace.budget, 'planner_errors': sum('error' in a for a in trace.planner_attempts), - 'execution_errors': sum(s['status'] != 'success' for p in trace.programs for s in p['steps'])}) - if summary['backend_errors']: - summary['status'] = 'backend_failure' - records = [json.loads(p.read_text(encoding='utf-8')) for p in (output / 'calls').glob('call-*/result.json')] - summary['model_calls'] = len(records) - summary['input_tokens'] = sum(r.get('input_tokens') or 0 for r in records) - summary['output_tokens'] = sum(r.get('output_tokens') or 0 for r in records) - summary['generation_seconds'] = sum(r.get('seconds') or 0 for r in records) - except Exception as exc: - if summary['status'] != 'initialization_failure': - summary['status'] = 'runner_failure' - summary['error'] = f'{type(exc).__name__}: {exc}' - finally: - summary['seconds'] = time.perf_counter() - started - write_json(output / 'summary.json', summary) - print(json.dumps(summary, ensure_ascii=True)) - return 0 if summary['status'] == 'completed' else 2 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/research/finance_program_v1/nontraining/prepare_batch.py b/research/finance_program_v1/nontraining/prepare_batch.py deleted file mode 100644 index 45812bf..0000000 --- a/research/finance_program_v1/nontraining/prepare_batch.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Validate the frozen Val inputs and mechanically separate private gold.""" -# 准备阶段将元数据与私有答案分开保存;后续推理仅使用 study,答案留给离线评分。 -import argparse -import hashlib -import json -from pathlib import Path - -ROOT=Path(__file__).resolve().parent -BUDGET=dict(max_programs=3,max_program_steps=10,max_skill_steps=12,max_planner_attempts=4,max_identical_calls=1) -DATA_SHA={'data/metadata-val.json':'e6792db18afe1ac82a3cae499735182a7bcee366a42251e72a8ccad5e6aee8c5', - 'data/registry.json':'1b19032a3d2d8d283044e05f3f97cab2d4d77d71b68e3fb97e222f75c2705bec'} - -def read(path): return json.loads(Path(path).read_text(encoding='utf-8')) -def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() -def save(path,value): - path=Path(path); path.parent.mkdir(parents=True,exist_ok=True) - with path.open('x',encoding='utf-8') as f: json.dump(value,f,ensure_ascii=False,indent=2,allow_nan=False) - -def validate_study(study): - if study['budget']!=BUDGET: raise ValueError('fixed Program budget changed') - ids=[r['id'] for r in study['rows']] - if len(ids)!=len(set(ids)): raise ValueError('duplicate metadata identity') - if any(set(r)!={'id','domain','metadata'} for r in study['rows']): raise ValueError('labels in metadata rows') - selected=[i for group in study['cohorts'].values() for i in group] - if len(selected)!=len(set(selected)) or not set(selected)<=set(ids): raise ValueError('cohorts overlap or unknown ID') - if set(study['cohorts'])!={'pilot','expanded','smoke'}: raise ValueError('cohort names changed') - return study - -def prepare(source,output=ROOT): - source=Path(source); output=Path(output) - if (output/'data/study.json').exists() or (output/'evaluation/gold.json').exists(): raise FileExistsError('prepared output exists') - manifest=read(source/'frozen/manifest.json') - hashes={} - for name in ('data/metadata-val.json','data/registry.json','data/val.jsonl','data/split_boundaries.json'): - hashes[name]=sha(source/name) - if hashes[name]!=manifest['files'][name] or (name in DATA_SHA and hashes[name]!=DATA_SHA[name]): raise ValueError('frozen input hash mismatch: '+name) - rows=read(source/'data/metadata-val.json') - registry_raw=read(source/'data/registry.json')['categories'] - registry={r['category']:{k:v for k,v in r.items() if k not in ('category','category_id')} for r in registry_raw} - if len(rows)!=422 or len(registry)!=12 or any(r['category']!=r['category_id'] for r in registry_raw): raise ValueError('frozen dataset shape changed') - cohorts={k.removesuffix('20').removesuffix('60').removesuffix('2'):v for k,v in manifest['cohorts'].items()} - if {k:len(v) for k,v in cohorts.items()}!={'pilot':20,'expanded':60,'smoke':2}: raise ValueError('cohort sizes changed') - by_id={r['id']:r for r in rows} - val=[json.loads(line) for line in (source/'data/val.jsonl').read_text(encoding='utf-8').splitlines()] - if len({r['source_id'] for r in val})!=len(val): raise ValueError('duplicate gold identity') - selected={i for group in cohorts.values() for i in group} - answers={} - for r in val: - metadata=by_id[r['source_id']] - if metadata['domain']!=r['domain'] or metadata['metadata']['field_name']!=r['field_name']: raise ValueError('metadata/gold binding mismatch') - if r['ground_truth'] not in registry or registry[r['ground_truth']]['grading_level']!=r['ground_truth_level']: raise ValueError('gold outside registry') - if r['source_id'] in selected: answers[r['source_id']]={'category':r['ground_truth'],'grading_level':r['ground_truth_level']} - if set(answers)!=selected: raise ValueError('missing selected gold') - supported=sorted({answers[i]['category'] for i in cohorts['pilot']+cohorts['expanded']}) - if len(supported)!=8: raise ValueError('Val80 class identity changed') - study=validate_study({'schema':1,'cohorts':cohorts,'rows':rows,'registry':registry,'budget':BUDGET, - 'source_hashes':hashes,'source_manifest_sha256':sha(source/'frozen/manifest.json')}) - save(output/'data/study.json',study) - save(output/'data/study-manifest.json',{'study_sha256':sha(output/'data/study.json')}) - save(output/'evaluation/gold.json',{'answers':answers,'supported_classes':supported,'source_hashes':hashes}) - return study - -def main(argv=None): - p=argparse.ArgumentParser(description=__doc__); p.add_argument('--source',type=Path,required=True); p.add_argument('--output',type=Path,default=ROOT) - a=p.parse_args(argv); result=prepare(a.source,a.output); print(json.dumps({'cohorts':{k:len(v) for k,v in result['cohorts'].items()},'rows':len(result['rows'])})); return 0 -if __name__=='__main__': raise SystemExit(main()) diff --git a/research/finance_program_v1/nontraining/program_loop/__init__.py b/research/finance_program_v1/nontraining/program_loop/__init__.py deleted file mode 100644 index 44a7fe3..0000000 --- a/research/finance_program_v1/nontraining/program_loop/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Public CPU-safe Program orchestration entry point.""" -from .contracts import ProgramConfig, ProgramTrace -from .controller import ProgramController, build_program_controller - -__all__ = ["ProgramConfig", "ProgramTrace", "ProgramController", "build_program_controller"] diff --git a/research/finance_program_v1/nontraining/program_loop/__main__.py b/research/finance_program_v1/nontraining/program_loop/__main__.py deleted file mode 100644 index eb53e2f..0000000 --- a/research/finance_program_v1/nontraining/program_loop/__main__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .cli import main - -raise SystemExit(main()) diff --git a/research/finance_program_v1/nontraining/program_loop/_vendor.py b/research/finance_program_v1/nontraining/program_loop/_vendor.py deleted file mode 100644 index 6222f14..0000000 --- a/research/finance_program_v1/nontraining/program_loop/_vendor.py +++ /dev/null @@ -1,9 +0,0 @@ -"""Locate the immutable local snapshot without requiring model libraries.""" -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[1] -VENDOR = ROOT / "vendor" -for path in (VENDOR, VENDOR / "runtime" / "code"): - if str(path) not in sys.path: - sys.path.insert(0, str(path)) diff --git a/research/finance_program_v1/nontraining/program_loop/catalog_context.py b/research/finance_program_v1/nontraining/program_loop/catalog_context.py deleted file mode 100644 index 9fe8b28..0000000 --- a/research/finance_program_v1/nontraining/program_loop/catalog_context.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Complete P14 contracts and snapshots containing only acquired public state.""" -from copy import deepcopy -from . import _vendor -from pool_catalog import purpose -from .planning_contracts import planning_contract - - -def skill_library(catalog, loader): - return [{"name": spec.name, "purpose": purpose(spec.name), "role": spec.role, - "required_inputs": list(spec.required_inputs), "optional_inputs": list(spec.optional_inputs), - "produces": list(spec.produces), "terminal": spec.terminal, - "contract": loader.load(spec.name).body, - "planning": planning_contract(spec, catalog)} for spec in catalog.values()] - - -def public_state(record, state): - return {"input": {"domain": record.domain, "field_name": record.field_name}, "named_state": deepcopy(state)} diff --git a/research/finance_program_v1/nontraining/program_loop/cli.py b/research/finance_program_v1/nontraining/program_loop/cli.py deleted file mode 100644 index bf13728..0000000 --- a/research/finance_program_v1/nontraining/program_loop/cli.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Local scripted demo, or optional generation from an existing local model.""" -import argparse -import json -from pathlib import Path -import sys - -from . import ProgramConfig, build_program_controller - -DEMO_TOOLS = ("INTERPRET_FIELD_NAME", "SELECT_CATEGORY_TOPK", "INFER_CATEGORY_FROM_TOPK", "INFER_GRADING_LEVEL", "FINALIZE_CLASSIFICATION") - - -def scripted_generate(messages): - system = messages[0]["content"] - if "Global Program Planner" in system: - return json.dumps({"program": [{"tool": tool, "arguments": {}} for tool in DEMO_TOOLS]}) - if "selected Skill INTERPRET_FIELD_NAME." in system: - return json.dumps({"summary": "合成语义", "data": {"field_semantics": "字段表示账户余额"}}) - if "selected Skill SELECT_CATEGORY_TOPK." in system: - return json.dumps({"option_ids": ["C001", "C002", "C003", "C004", "C005"], "summary": "合成候选"}) - if "selected Skill INFER_CATEGORY_FROM_TOPK." in system: - return json.dumps({"option_id": "C001", "summary": "合成选择"}) - raise ValueError("unsupported scripted model request") - - -def local_generate(path): - path = Path(path).resolve() - if not path.is_dir(): raise ValueError(f"local model path does not exist: {path}") - try: - from transformers import AutoModelForCausalLM, AutoTokenizer - except ImportError as exc: - raise RuntimeError("optional local model runtime is unavailable: transformers is not installed") from exc - tokenizer = AutoTokenizer.from_pretrained(str(path), local_files_only=True, trust_remote_code=False) - model = AutoModelForCausalLM.from_pretrained(str(path), local_files_only=True, trust_remote_code=False) - model.eval() - - def generate(messages): - import torch - prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) - encoded = tokenizer(prompt, return_tensors="pt") - with torch.inference_mode(): - output = model.generate(**encoded, do_sample=False, max_new_tokens=1024) - return tokenizer.decode(output[0, encoded["input_ids"].shape[1]:], skip_special_tokens=True) - return generate - - -def main(argv=None): - parser = argparse.ArgumentParser(description="Program loop: scripted model I/O + real executor; no accuracy claim") - parser.add_argument("--output", type=Path, help="new JSON output path; refuses overwrite") - parser.add_argument("--local-model", type=Path, help="existing local model directory; local_files_only") - parser.add_argument("--registry", type=Path, help="frozen Registry JSON; optional for synthetic demo") - parser.add_argument("--metadata", type=Path, help="label-free privately scoped metadata JSON") - parser.add_argument("--source-id", default="synthetic-demo", help="private metadata lookup identity") - parser.add_argument("--domain", default="合成金融") - parser.add_argument("--field-name", default="balance") - for key in ("programs", "program-steps", "skill-steps", "planner-attempts"): - parser.add_argument("--max-" + key, type=int, default=getattr(ProgramConfig(), "max_" + key.replace("-", "_"))) - args = parser.parse_args(argv) - try: - if args.output and args.output.exists(): raise FileExistsError(f"output already exists: {args.output}") - generate = local_generate(args.local_model) if args.local_model else scripted_generate - registry = args.registry or {f"cat{i}": {"label": f"合成类别{i}", "description": f"合成定义{i}", "grading_level": "L2"} for i in range(1, 7)} - metadata = args.metadata or [{"id": args.source_id, "domain": args.domain, "metadata": {"field_name": args.field_name}}] - config = ProgramConfig(max_programs=args.max_programs, max_program_steps=args.max_program_steps, max_skill_steps=args.max_skill_steps, max_planner_attempts=args.max_planner_attempts) - controller = build_program_controller(generate, registry, metadata, config) - trace = controller.run({"domain": args.domain, "field_name": args.field_name, "source_id": args.source_id}) - trace.execution_mode = "local model I/O + real executor" if args.local_model else "scripted model I/O + real executor" - if args.output: trace.write_json(args.output) - print(json.dumps({"execution_mode": trace.execution_mode, "terminated": trace.terminated, "stop_reason": trace.stop_reason, "budget": trace.budget, "output": str(args.output) if args.output else None}, ensure_ascii=True)) - return 0 if trace.terminated else 1 - except Exception as exc: - print(f"blocked: {exc}", file=sys.stderr) - return 2 diff --git a/research/finance_program_v1/nontraining/program_loop/contracts.py b/research/finance_program_v1/nontraining/program_loop/contracts.py deleted file mode 100644 index b7d715c..0000000 --- a/research/finance_program_v1/nontraining/program_loop/contracts.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Run limits and JSON trace; the accepted Program is immutable.""" -from dataclasses import asdict, dataclass, field -import json -import math -from pathlib import Path - -from . import _vendor -from agent.orchestration.contracts import Program, ToolCall - - -def json_snapshot(value): - """Keep valid JSON data exact; represent invalid model I/O explicitly.""" - if value is None or isinstance(value, (str, bool, int)): - return value - if isinstance(value, float) and math.isfinite(value): - return value - if isinstance(value, dict): - return {str(key): json_snapshot(item) for key, item in value.items()} - if isinstance(value, (list, tuple)): - return [json_snapshot(item) for item in value] - return {"invalid_json_type": type(value).__name__, "repr": repr(value)} - - -@dataclass(frozen=True) -class ProgramConfig: - max_programs: int = 4 - max_program_steps: int = 10 - max_skill_steps: int = 20 - max_planner_attempts: int = 8 - max_identical_calls: int = 1 - - def __post_init__(self): - for key, value in asdict(self).items(): - if type(value) is not int or value < 1: - raise ValueError(f"{key} must be a positive integer") - - -@dataclass -class ProgramTrace: - input: dict - execution_mode: str = "caller supplied model I/O + real executor" - planner_attempts: list = field(default_factory=list) - programs: list = field(default_factory=list) - state: dict = field(default_factory=dict) - budget: dict = field(default_factory=lambda: {"programs": 0, "planner_attempts": 0, "skill_steps": 0}) - terminated: bool = False - final_result: dict | None = None - stop_reason: str = "running" - - def to_dict(self): - return json_snapshot(asdict(self)) - - def write_json(self, path): - serialized = json.dumps(self.to_dict(), ensure_ascii=False, indent=2, allow_nan=False) - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("x", encoding="utf-8") as stream: - stream.write(serialized + "\n") diff --git a/research/finance_program_v1/nontraining/program_loop/controller.py b/research/finance_program_v1/nontraining/program_loop/controller.py deleted file mode 100644 index e854784..0000000 --- a/research/finance_program_v1/nontraining/program_loop/controller.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Bounded outer feedback loop; no Planner calls within a Program.""" -from collections import Counter -from collections.abc import Mapping -from copy import deepcopy -import json -from pathlib import Path - -from .contracts import ProgramConfig, ProgramTrace, json_snapshot -from .catalog_context import skill_library -from .execution import ExecutionBridge -from .planner import planner_messages -from .validation import parse_program -from .rejection_context import rejected_program_summary -from agent.orchestration.contracts import MetadataRecord -import local_smoke - -def _load(value): - return json.loads(Path(value).read_text(encoding="utf-8-sig")) if isinstance(value, (str, Path)) else deepcopy(value) - - -class ProgramController: - def __init__(self, generate, registry, metadata, config): - self.generate:local_smoke.Backend = generate - self.config = config - self.bridge = ExecutionBridge(generate, registry, metadata, config) - self.library = skill_library(self.bridge.catalog, self.bridge.loader) - - def remaining(self, trace): - """可用资源(步数)""" - return {"programs": max(0, self.config.max_programs - trace.budget["programs"]), - "planner_attempts": max(0, self.config.max_planner_attempts - trace.budget["planner_attempts"]), - "skill_steps": max(0, self.config.max_skill_steps - trace.budget["skill_steps"]), - "program_steps": self.config.max_program_steps} - - def run(self, record): - if isinstance(record, MetadataRecord): - record = {"domain": record.domain, "field_name": record.field_name, "source_id": record.source_id} - # Ignore caller optional metadata and labels; this boundary exposes only initial fields. - visible = MetadataRecord.from_mapping({"domain": record.get("domain"), "field_name": record.get("field_name") or record.get("metadata", {}).get("field_name"), "source_id": record.get("source_id")}) - trace = ProgramTrace({"domain": visible.domain, "field_name": visible.field_name}) - state = {}; self.bridge.availability.initialize(visible, state) - counts = Counter(); lineage = {"evidence": 0, "candidates": 0, "selection": 0} - feedback = None - while not trace.terminated: - remaining = self.remaining(trace) - exhausted = next((key for key in ("skill_steps", "programs", "planner_attempts") if remaining[key] == 0), None) - if exhausted: - trace.stop_reason = {"skill_steps": "skill_budget_exhausted", "programs": "program_budget_exhausted", "planner_attempts": "planner_budget_exhausted"}[exhausted] - break - messages = planner_messages(visible, state, self.library, remaining, feedback) #sys and user - trace.budget["planner_attempts"] += 1 - attempt = {"attempt": trace.budget["planner_attempts"], "messages": deepcopy(messages), "raw_response": None, "status": "error"} - trace.planner_attempts.append(attempt) - try: - raw = self.generate(messages) # here is request - attempt["raw_response"] = json_snapshot(raw) - attempt["status"] = "rejected" - plan = parse_program(raw, self.bridge.catalog, state, self.config.max_program_steps) - except Exception as exc: - attempt["error"] = str(exc) - feedback = {"status": "planner_" + attempt["status"], "error": str(exc), "remaining_budget": self.remaining(trace)} - if attempt['status'] == 'rejected': - summary = rejected_program_summary(raw, self.bridge.catalog, self.config.max_program_steps) - if summary is not None: - feedback['rejected_program'] = summary - continue - attempt["status"] = "accepted" - trace.budget["programs"] += 1 - observation = {"program_index": trace.budget["programs"], "plan": plan.to_dict(), "steps": [], "status": "completed", "failure_index": None, "terminated": False, "invalidations": []} - trace.programs.append(observation) - for index, call in enumerate(plan.steps): - if self.remaining(trace)["skill_steps"] == 0: - observation.update(status="budget_exhausted", failure_index=index) - break - trace.budget["skill_steps"] += 1 - step = self.bridge.step(call, visible, state, counts, lineage) - step["step_index"] = index - observation["steps"].append(step) - observation["invalidations"].extend(step["invalidations"]) - if step["status"] != "success": - observation.update(status="failed", failure_index=index) - break - if self.bridge.catalog[call.tool].terminal: - trace.terminated = True - trace.final_result = deepcopy(step["data"]["final_result"]) - trace.stop_reason = "validated_terminal" - observation.update(status="terminated", terminated=True) - break - observation["remaining_budget"] = self.remaining(trace) - observation["lineage"] = dict(lineage) - feedback = deepcopy(observation) - trace.state = deepcopy(state) - return trace - - -def build_program_controller(generate, registry_entries, metadata_rows, config=None): - if not callable(generate): raise TypeError("generate must be callable") - registry = _load(registry_entries) - if isinstance(registry, Mapping) and "categories" in registry: - registry = {item["category_id"]: {k: v for k, v in item.items() if k not in ("category", "category_id")} for item in registry["categories"]} - if not isinstance(registry, Mapping) or not registry: raise ValueError("nonempty frozen Registry mapping is required") - for category, entry in registry.items(): - if not isinstance(category, str) or not category or not isinstance(entry, Mapping) or not isinstance(entry.get("grading_level"), str) or not entry["grading_level"]: - raise ValueError("Registry entries require category and frozen grading_level") - config = ProgramConfig(**config) if isinstance(config, Mapping) else config or ProgramConfig() - return ProgramController(generate, registry, _load(metadata_rows), config) diff --git a/research/finance_program_v1/nontraining/program_loop/execution.py b/research/finance_program_v1/nontraining/program_loop/execution.py deleted file mode 100644 index 5e86304..0000000 --- a/research/finance_program_v1/nontraining/program_loop/execution.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Thin bridge to real frozen binding, executor, publication and terminal guards.""" -from copy import deepcopy -from dataclasses import asdict -import json -from types import SimpleNamespace - -from . import _vendor -from .contracts import json_snapshot -from .validation import SELECTION, GRADE -from agent.orchestration.agent_loop import LoopConfig, PolicyDecision -from agent.orchestration.category_catalog import CategoryCatalog -from agent.orchestration.runtime import Observation -from agent.orchestration.skill_loader import SkillLoader -from agent.orchestration.validator import resolve_reference -from pool_catalog import pool_catalog -from pool_metadata import PoolMetadata -from pool_runtime import PoolController, PoolExecutor, publish_state, SEMANTIC_KEYS, ALIGNMENT_KEYS -import pool_availability - - -class ExecutionBridge: - def __init__(self, generate, registry, rows, config): - self.catalog = pool_catalog("P14") - self.loader = SkillLoader(_vendor.VENDOR / "runtime" / "skills" / "full_pool", self.catalog, strict_catalog=False) - self.loader.validate_all() - self.executor = PoolExecutor(generate, self.loader, PoolMetadata(rows), CategoryCatalog(registry)) - self.guard = PoolController(policy=SimpleNamespace(missing_awareness=True), executor=self.executor, - catalog=self.catalog, skill_loader=self.loader, config=LoopConfig(recover_ready_finalization=False), - registry_entries=registry, approved_levels={e["grading_level"] for e in registry.values()}, state_publication=publish_state) - self.availability = pool_availability - self.max_identical_calls = config.max_identical_calls - - @staticmethod - def _drop(state, keys): - removed = sorted(keys & set(state)) - for key in removed: - state.pop(key, None) - state.get("_provenance", {}).pop(key, None) - return removed - - def step(self, call, record, state, counts, lineage): - result = {"call": call.to_dict(), "status": "blocked", "binding": None, "invalidations": []} - canonical = None - try: - spec = self.catalog[call.tool] - decision = self.guard._normalize_policy_decision(PolicyDecision(call, ""), record, state, spec) - canonical = decision.call - result["binding"] = decision.metadata["binding"] - resolved = {k: resolve_reference(v, record, state)[1] for k, v in canonical.arguments.items()} - identity = json.dumps({"call": {"tool": call.tool, "arguments": resolved}, "lineage": lineage}, sort_keys=True, ensure_ascii=False, allow_nan=False) - if counts[identity] >= self.max_identical_calls: - raise ValueError("identical successful call blocked for current evidence lineage") - result["status"] = "error" - observation = self.executor.execute(canonical, record, state, self.loader.load(call.tool)) - # Normalize/availability update is transactional with publication. - updated = deepcopy(state) - observation = self.guard._normalize_observation(canonical, observation, updated) - self.executor._validate_deterministic(observation, spec) - result.update(asdict(observation)) - if observation.status == "success": - changed = {key for key, value in observation.data.items() if state.get(key) != value} - evidence = changed & (set(SEMANTIC_KEYS) | set(ALIGNMENT_KEYS) | {"field_metadata"}) - invalidated = [] - if evidence or "standard_candidates" in changed: - invalidated.extend(self._drop(updated, SELECTION)) - elif "category" in changed or "aligned_standard_entry" in changed: - invalidated.extend(self._drop(updated, GRADE)) - if spec.terminal and not self.guard._valid_terminal(observation.data.get("final_result"), updated): - raise ValueError("invalid terminal result rejected by real PoolController") - publish_state(record, updated, observation.data, call.tool) - state.clear(); state.update(updated) - # Global success dedup consumes the input lineage, before incrementing it. - counts[identity] += 1 - if evidence: lineage["evidence"] += 1 - if "standard_candidates" in changed: lineage["candidates"] += 1 - if "category" in changed or "aligned_standard_entry" in changed: lineage["selection"] += 1 - result["invalidations"] = invalidated - else: - state.clear(); state.update(updated) - except Exception as exc: - if result["status"] == "success": result["status"] = "error" - metadata = {**result.get("metadata", {}), **deepcopy(getattr(exc, "metadata", {}))} - result.update(summary=str(exc), data={}, metadata=metadata) - if canonical is not None and result["status"] == "error": - self.availability.observe(canonical, Observation(call.tool, "error", str(exc), {}), state) - result["lineage"] = dict(lineage) - return json_snapshot(result) diff --git a/research/finance_program_v1/nontraining/program_loop/planner.py b/research/finance_program_v1/nontraining/program_loop/planner.py deleted file mode 100644 index 41f4f90..0000000 --- a/research/finance_program_v1/nontraining/program_loop/planner.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Generate one whole Program per outer attempt.""" -import json -from .catalog_context import public_state -from .recovery_context import recovery_context - -SYSTEM = """You are the Global Program Planner for a database-field classification task. -Plan the complete remaining classification task in one ordered Program, not just the next Skill. -Choose the Skills and their order yourself from the complete P14 library. -Plan all dependencies through a successful terminal; selecting candidates alone does not finish classification. -You need not see a future output now: use its documented canonical reference after its producer; execution will bind the actual verified output. -Conditional outputs may be missing or execution may fail; the Program then stops and its factual observation returns to you at the outer boundary. -The parser accepts partial Programs, but that is a permissive syntax boundary, not the planning objective. -Each Program must fit remaining_budget.program_steps and remaining_budget.skill_steps; these are hard upper bounds, not suggested plan lengths. -Use a sufficient dependency path for the remaining task; complete classification does not require using every Skill or every possible evidence source. -Before returning JSON, count the planned steps and omit nonessential operations if it exceeds either bound, without omitting required dependencies or inventing evidence. -Each possible_producers list contains alternative ways to supply that input, not a sequence that must all be executed; choose a sufficient dependency path and still verify its conditional outputs at execution. -all_available_evidence means the verified evidence actually accumulated by the chosen Skills, not every possible evidence source; only a nonempty requires_all list requires every named prerequisite. -Return exactly one JSON object with only a program key whose value is an ordered array of steps. Each step has only tool (the chosen Skill name) and arguments (an object). -No Skill name is mandatory and the controller inserts no steps. -Only domain and field_name are initially visible. A planned metadata retrieval is not evidence. -Prefer arguments:{} so the existing execution-time binder supplies available required inputs. -To use an available optional input, supply its documented canonical reference explicitly; omitted optional inputs are not automatically inserted. -If an optional input is unavailable, omit it; do not supply null placeholders or invent a value. Explicit supplied parameters remain checked. -Use each Skill's planning.inputs to distinguish required and optional inputs and obtain its canonical_reference. -Follow explicit_value_policy: canonical_reference_only requires the exact documented reference for every explicit dynamic input. Never handwrite dynamic state values, including objects, lists, null, numbers, or ordinary strings; omit required inputs to use the runtime binder. -For state dependencies, choose an appropriate possible_producers Skill before the consumer, unless the input is already in actual state. -Possible producers and conditional_outputs describe static possibilities, not successful execution evidence. Metadata and other outputs are conditional and validated at execution. -Initial bindings are $domain, $metadata.field_name for field_name/target_field, and internal $record for current_record; $record discloses no private identity. -semantic_query is a query input; semantic_evidence is semantic evidence. They have distinct canonical paths and contracts. field_description_semantics does not supply field_semantics. -final_evidence_state requires every prerequisite in planning.inputs.final_evidence_state.requires_all; no single possible producer guarantees it. -Future references are allowed only after a producing Skill. Explicit references must use the documented canonical path; values are checked against actual state at execution. -Finish only by a successful terminal Skill consuming verified final_evidence_state. No steps after terminal. -Each failure ends the current Program. Use its observation to plan within the remaining global budget. -Recovery context reports execution facts only. Unexecuted tail is historical intent, not required steps. State presence and historical success do not establish current readiness; invalidated outputs must be reacquired or recomputed through your chosen Skills. -Consider the remaining complete task and actual budget when choosing the next whole Program, especially the final available Program: one successful recovery step may still leave classification unfinished. Legal partial Programs remain allowed; no automatic completion or bonus budget is provided. -Never invent metadata, candidates, categories, frozen grades, or ground truth.""" - - -def planner_messages(record, state, library, budget, feedback)->list: - """Generate the system and user messages for the planner.""" - payload = {"task": "Plan the complete remaining classification task using verified evidence and frozen Registry grading, through legal terminal execution.", - "current": public_state(record, state), "skill_library": library, - "remaining_budget": budget, "feedback": feedback, - "recovery_context": recovery_context(state, budget, feedback), - "availability_rule": "unknown permits acquisition; canonical source observations establish obtained/unavailable; errors remain retryable; omitted batch attributes remain unknown"} - return [{"role": "system", "content": SYSTEM}, {"role": "user", "content": json.dumps(payload, ensure_ascii=False, allow_nan=False)}] diff --git a/research/finance_program_v1/nontraining/program_loop/planning_contracts.py b/research/finance_program_v1/nontraining/program_loop/planning_contracts.py deleted file mode 100644 index 68fd55f..0000000 --- a/research/finance_program_v1/nontraining/program_loop/planning_contracts.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Value-free planning guidance from catalog contracts and shared static rules. - -Possible producers and outputs are conditional, never proof of execution success. -Actual-state binding and the executor still validate every supplied input/output. -""" -from .validation import canonical_reference, explicit_value_policy, possible_outputs, FINAL_EVIDENCE_REQUIREMENTS - - -def planning_contract(spec, catalog): - known = {key for entry in catalog.values() for key in (*entry.required_inputs, *entry.optional_inputs)} - known.update(key for entry in catalog.values() for key in possible_outputs(entry)) - known.add("final_evidence_state") - inputs = {} - for key in (*spec.required_inputs, *spec.optional_inputs): - ref = canonical_reference(key, known) - target = ref.removeprefix("$state.") if ref and ref.startswith("$state.") else None - inputs[key] = { - "required": key in spec.required_inputs, - "canonical_reference": ref, - "explicit_value_policy": explicit_value_policy(ref), - "source": "state" if target else "initial_binding", - "possible_producers": [other.name for other in catalog.values() if target in possible_outputs(other)] if target and key != "final_evidence_state" else [], - "requires_all": sorted(FINAL_EVIDENCE_REQUIREMENTS) if key == "final_evidence_state" else [], - } - return {"argument_template": {}, "inputs": inputs, "conditional_outputs": sorted(possible_outputs(spec))} diff --git a/research/finance_program_v1/nontraining/program_loop/recovery_context.py b/research/finance_program_v1/nontraining/program_loop/recovery_context.py deleted file mode 100644 index bbb0aa2..0000000 --- a/research/finance_program_v1/nontraining/program_loop/recovery_context.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Summarize actual outer-loop observations without proposing or executing steps.""" -from .contracts import json_snapshot - - -def recovery_context(state, budget, feedback): - """Return detached JSON facts; presence and historical success imply no readiness. - - Feedback is the controller's last observation, not model-authored recovery advice. - Keep raw feedback at its existing boundary; this summary omits values and arguments. - """ - previous = None - if feedback and feedback.get('status') in ('completed', 'failed', 'budget_exhausted', 'terminated') and 'plan' in feedback: - steps = feedback.get('steps', []) - executed = {step['step_index'] for step in steps} - previous = { - 'status': feedback['status'], - 'failure_index': feedback.get('failure_index'), - 'successful_steps': [{'step_index': s['step_index'], 'tool': s['call']['tool']} - for s in steps if s['status'] == 'success'], - 'failed_steps': [{'step_index': s['step_index'], 'tool': s['call']['tool'], 'status': s['status']} - for s in steps if s['status'] != 'success'], - 'unexecuted_tail': [{'step_index': i, 'tool': call['tool']} - for i, call in enumerate(feedback['plan']['program']) if i not in executed], - } - return json_snapshot({ - 'previous_program': previous, - 'classification_completed': bool(previous and previous['status'] == 'terminated' - and feedback.get('terminated') is True - and feedback.get('steps') - and feedback['steps'][-1]['status'] == 'success'), - 'remaining_budget': budget, - 'invalidations': feedback.get('invalidations', []) if previous else [], - 'observed_state_keys': sorted(state), - 'state_rule': 'Observed keys indicate presence only; neither presence nor historical success verifies readiness. Removed invalidated outputs are not available in current state.', - 'availability_observations': [{k: entry[k] for k in ('scope', 'type', 'status', 'skill') if k in entry} - for entry in state.get('availability_ledger', [])], - 'availability_rule': 'These are recorded observations, not new checks. Missing observations remain unknown/unqueried; omitted batch attributes remain unknown. Obtained and canonical unavailable are distinct; error is retryable and does not establish absence. Target details remain in actual public state.', - 'tail_rule': 'Unexecuted tail is historical intent only, without arguments; choose a new whole Program autonomously using current state and contracts.', - 'task_reminder': 'Consider the remaining complete classification task within the actual global budget. Only a validated successful terminal completes classification. A successful recovery step alone may leave the task unfinished, especially on the last available Program. Partial legal Programs remain allowed; no steps or extra budget are supplied.', - }) diff --git a/research/finance_program_v1/nontraining/program_loop/rejection_context.py b/research/finance_program_v1/nontraining/program_loop/rejection_context.py deleted file mode 100644 index a75322b..0000000 --- a/research/finance_program_v1/nontraining/program_loop/rejection_context.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Read-only summary of unexecuted model intent; never execution evidence.""" -import json -import math -from .validation import _unique_object - -def _reject_constant(value): - raise ValueError(f'nonfinite JSON {value}') - -def _finite_float(value): - number = float(value) - if not math.isfinite(number): - raise ValueError('nonfinite JSON number') - return number - -def rejected_program_summary(raw, catalog, max_steps): - if not isinstance(raw, str): - return None - try: - value = json.loads(raw, object_pairs_hook=_unique_object, parse_constant=_reject_constant, parse_float=_finite_float) - except (ValueError, TypeError, RecursionError): - return None - if not isinstance(value, dict) or set(value) != {'program'}: - return None - steps = value['program'] - if not isinstance(steps, list) or not steps: - return None - tools = [] - for item in steps: - if not isinstance(item, dict) or set(item) != {'tool','arguments'}: - return None - name = item['tool'] - if not isinstance(name, str) or name not in catalog or not isinstance(item['arguments'], dict): - return None - tools.append(name) - return {'executed':False,'trusted':False,'step_count':len(steps), - 'max_program_steps':max_steps,'tool_sequence':tools} diff --git a/research/finance_program_v1/nontraining/program_loop/validation.py b/research/finance_program_v1/nontraining/program_loop/validation.py deleted file mode 100644 index 6fc4e49..0000000 --- a/research/finance_program_v1/nontraining/program_loop/validation.py +++ /dev/null @@ -1,82 +0,0 @@ -"""Validate possible dependencies, never pretend a future retrieval succeeded.""" -import json -from .contracts import Program, ToolCall -from pool_metadata import FIELDS -from pool_runtime import SEMANTIC_KEYS, ALIGNMENT_KEYS - -SELECTION = {"category", "aligned_category", "candidate_category", "category_candidate", "aligned_standard_entry", "grading_level", "grading_level_candidate", "final_evidence_state", "final_result"} -GRADE = {"grading_level", "grading_level_candidate", "final_evidence_state", "final_result"} -EVIDENCE_BUNDLES = {"semantic_query", "semantic_evidence", "current_semantic_state", "current_evidence", "current_evidence_state", "all_available_evidence", "available_evidence", "evidence", "evidence_set"} -FINAL_EVIDENCE_REQUIREMENTS = frozenset({"grading_level", "category", "aligned_standard_entry", "standard_candidates"}) - - -def _unique_object(pairs): - result = {} - for key, value in pairs: - if key in result: raise ValueError(f"duplicate JSON key {key}") - result[key] = value - return result - - -def canonical_reference(key, available): - if key == "current_record": return "$record" - if key == "domain": return "$domain" - if key in ("field_name", "target_field"): return "$metadata.field_name" - if key == "candidate_standard_categories" and "standard_candidates" in available: return "$state.standard_candidates" - return "$state." + key if key in available else None - - -_reference = canonical_reference - - -def explicit_value_policy(reference): - return "canonical_reference_only" if reference and reference.startswith("$state.") else "initial_binding_contract" - - -def possible_outputs(spec): - produced = set(spec.produces) - outputs = set(produced) - if produced & set(SEMANTIC_KEYS): outputs.update(EVIDENCE_BUNDLES) - if "field_metadata" in produced: - outputs.update((*FIELDS, "current_metadata", "available_metadata", "semantic_query", "available_evidence", "all_available_evidence")) - if "category" in produced: outputs.update(("aligned_category", "candidate_category", "category_candidate")) - return outputs - - -def advance_available(spec, available): - available = set(available) - produced = set(spec.produces) - if produced & (set(SEMANTIC_KEYS) | set(ALIGNMENT_KEYS) | {"field_metadata"}): available -= SELECTION - if "standard_candidates" in produced: available -= SELECTION - if "category" in produced: available -= GRADE - available.update(possible_outputs(spec)) - if FINAL_EVIDENCE_REQUIREMENTS <= available: available.add("final_evidence_state") - return available - - -def parse_program(raw, catalog, state, max_steps): - if not isinstance(raw, str): raise ValueError("Planner must return JSON text") - value = json.loads(raw, object_pairs_hook=_unique_object, parse_constant=lambda v: (_ for _ in ()).throw(ValueError(f"nonfinite JSON {v}"))) - if not isinstance(value, dict) or set(value) != {"program"}: raise ValueError("Expected exactly one JSON Program object") - steps = value["program"] - if not isinstance(steps, list) or not steps: raise ValueError("Program must be nonempty") - if len(steps) > max_steps: raise ValueError("Program length exceeds max_program_steps") - available = set(state) - calls = [] - for index, item in enumerate(steps): - if not isinstance(item, dict) or set(item) != {"tool", "arguments"}: raise ValueError(f"step {index}: expected only tool and arguments") - name, args = item["tool"], item["arguments"] - if not isinstance(name, str) or name not in catalog: raise ValueError(f"step {index}: unknown Skill") - spec = catalog[name] - if not isinstance(args, dict) or set(args) - set((*spec.required_inputs, *spec.optional_inputs)): raise ValueError(f"step {index}: unknown arguments") - for key in set(spec.required_inputs) | set(args): - reference = canonical_reference(key, available) - if reference is None: raise ValueError(f"step {index}: missing dependency {key}") - supplied = args.get(key) - if key in args and ((explicit_value_policy(reference) == "canonical_reference_only" and supplied != reference) - or (isinstance(supplied, str) and supplied.startswith("$") and supplied != reference)): - raise ValueError(f"step {index}: incorrect canonical reference for {key}; expected {reference}") - if spec.terminal and index != len(steps) - 1: raise ValueError(f"step {index}: terminal Skill must be last") - available = advance_available(spec, available) - calls.append(ToolCall(name, args)) - return Program(tuple(calls)) diff --git a/research/finance_program_v1/nontraining/reviews/__init__.py b/research/finance_program_v1/nontraining/reviews/__init__.py deleted file mode 100644 index e45a911..0000000 --- a/research/finance_program_v1/nontraining/reviews/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Public, CPU-only historical audit helpers; no generated private receipts.""" diff --git a/research/finance_program_v1/nontraining/reviews/independent_audit_01.py b/research/finance_program_v1/nontraining/reviews/independent_audit_01.py deleted file mode 100644 index 9afdf2f..0000000 --- a/research/finance_program_v1/nontraining/reviews/independent_audit_01.py +++ /dev/null @@ -1,284 +0,0 @@ -"""Independent CPU-only audit: recorded model I/O + exact frozen trace replay. - -Run only after the coordinator has closed all writers and verified/extracted the -new immutable snapshot. No torch/transformers import, GPU, network or model load. -""" -import argparse -from collections import Counter -import hashlib -import json -import math -from pathlib import Path -import sys - -ROOT = Path(__file__).resolve().parents[1] -SIGNATURE = '94ae314646625e078d7b0f8ee6315bf37778e1ce81bd8435a1417f43c769da1d' -REVISION = 'c202236235762e1c871ad0ccb60c8ee5ba337b9a' -BUDGET = dict(max_programs=3, max_program_steps=10, max_skill_steps=12, max_planner_attempts=4, max_identical_calls=1) -RUN_MODE = 'caller supplied backend I/O + real frozen executor; backend evidence in calls/' - -class AuditError(AssertionError): - pass - -def require(value, message): - if not value: - raise AuditError(message) - -def read(path): - return json.loads(Path(path).read_text(encoding='utf-8')) - -def sha(path): - return hashlib.sha256(Path(path).read_bytes()).hexdigest() - -def exact(actual, expected, label): - require(actual == expected, f'{label} mismatch') - -class RecordedBackend: - """Replays every external generation call, including retries and faults.""" - def __init__(self, records): - self.records = records - self.position = 0 - self.roles = [] - self.audit_faults = [] - - def __call__(self, messages): - try: - require(self.position < len(self.records), 'replay requested missing call') - record = self.records[self.position] - self.position += 1 - exact(record['request']['messages'], messages, f'call {self.position} request messages') - exact(record['result']['messages'], messages, f'call {self.position} result messages') - self.roles.append('planner' if 'Global Program Planner' in messages[0]['content'] else 'skill') - result = record['result'] - if result.get('error'): - kind, separator, message = result['error'].partition(': ') - require(separator and kind.isidentifier(), 'invalid recorded backend error') - # Exact original class name and str(exc), without backend execution. - raise type(kind, (Exception,), {})(message) - return result['raw_text'] - except AuditError as exc: - # Core deliberately catches generation errors. Retain audit failures - # out of band so they cannot turn into apparently legitimate traces. - self.audit_faults.append(str(exc)) - raise - - def finish(self): - require(not self.audit_faults, '; '.join(self.audit_faults)) - require(self.position == len(self.records), 'unconsumed recorded model calls') - -def replay_trace(saved, backend, registry, rows, budget, row): - from program_loop import build_program_controller, ProgramConfig - require(saved['execution_mode'] in (RUN_MODE, 'caller supplied model I/O + real executor'), 'trace execution mode invalid') - controller = build_program_controller(backend, registry, rows, ProgramConfig(**budget)) - trace = controller.run({'domain':row['domain'], 'field_name':row['metadata']['field_name'], 'source_id':row['id']}) - if saved['execution_mode'] == RUN_MODE: - trace.execution_mode = RUN_MODE - require(not backend.audit_faults, '; '.join(backend.audit_faults)) - actual = trace.to_dict() - # Includes parser raw, every message, full observations/feedback, all binding - # metadata/check-dependencies, invalidations, availability, lineage, budgets, - # state, stop reason and terminal result. No outcome-specific shortcut. - exact(actual, saved, 'complete trace replay') - first = json.loads(saved['planner_attempts'][0]['messages'][1]['content']) - require(row['metadata']['field_description'] not in json.dumps(first,ensure_ascii=False), 'initial metadata description exposed') - require(len(first['skill_library']) == 14, 'P14 library incomplete') - for attempt in saved['planner_attempts']: - combined = json.dumps(attempt['messages'],ensure_ascii=False) - require(all(r['id'] not in combined for r in rows), 'source ID exposed in planner messages') - for program in saved['programs']: - for step in program['steps']: - if step['call']['tool'] == 'GET_FIELD_METADATA' and step['status'] == 'success': - exact(step['data']['field_metadata'],row['metadata'],'actual metadata acquisition') - return actual - -def raw_steps(raw): - try: - parsed = json.loads(raw) - steps = parsed.get('program') if isinstance(parsed,dict) else None - return steps if isinstance(steps,list) else [] - except (TypeError,ValueError): - return [] - -def trace_summary(traces): - attempts, errors, execution = Counter(), Counter(), Counter() - details = [] - for trace in traces: - row_attempts = [] - for attempt in trace['planner_attempts']: - steps = raw_steps(attempt['raw_response']) - attempts[attempt['status']] += 1 - if 'error' in attempt: - errors[(attempt['status'],attempt['error'])] += 1 - row_attempts.append({'attempt':attempt['attempt'],'status':attempt['status'],'raw_steps':len(steps),'tools':[s.get('tool') if isinstance(s,dict) else None for s in steps],'error':attempt.get('error')}) - steps = [s for p in trace['programs'] for s in p['steps']] - for step in steps: - execution[(step['call']['tool'],step['status'])] += 1 - details.append({'input':trace['input'],'attempts':row_attempts,'budget':trace['budget'], - 'raw_multistep_programs':sum(len(raw_steps(a['raw_response']))>1 for a in trace['planner_attempts']), - 'accepted_multistep_programs':sum(len(p['plan']['program'])>1 for p in trace['programs']), - 'executed_multistep_programs':sum(len(p['steps'])>1 for p in trace['programs']), - 'program_status':dict(Counter(p['status'] for p in trace['programs'])), - 'actual_skills':[{'tool':s['call']['tool'],'status':s['status'],'summary':s.get('summary')} for s in steps], - 'terminated':trace['terminated'],'stop_reason':trace['stop_reason'],'final_result':trace['final_result']}) - return {'metric_scope':'unlabelled engineering smoke; no accuracy metric','samples':len(traces), - 'planner_attempts':sum(attempts.values()),'accepted_plans':sum(len(t['programs']) for t in traces), - 'attempt_status':dict(attempts),'planner_errors':[{'status':status,'reason':error,'count':count} for (status,error),count in errors.items()], - 'execution':[{'tool':tool,'status':status,'count':count} for (tool,status),count in execution.items()], - 'skill_steps':sum(execution.values()),'legal_terminations':sum(t['terminated'] for t in traces), - **{key:sum(d[key] for d in details) for key in ('raw_multistep_programs','accepted_multistep_programs','executed_multistep_programs')},'details':details} - -def call_summary(records, roles): - require(len(records)==len(roles),'model call role denominator mismatch') - peaks = [r['memory'].get('max_memory_allocated') for r in records] - return {'model_calls':len(records),'planner_calls':roles.count('planner'),'skill_model_calls':roles.count('skill'), - 'input_tokens':sum(r.get('input_tokens') or 0 for r in records),'output_tokens':sum(r.get('output_tokens') or 0 for r in records), - 'generation_seconds':sum(r.get('seconds') or 0 for r in records), - 'peak_allocated_bytes':max((p for p in peaks if p is not None),default=None), - 'backend_errors':sum(bool(r.get('error')) for r in records),'telemetry_errors':sum(bool(r.get('telemetry_errors')) for r in records), - 'output_budget_truncations':sum(bool(r['truncation_at_budget']) for r in records), - 'unknown_input_token_calls':sum(r.get('input_tokens') is None for r in records), - 'unknown_output_token_calls':sum(r.get('output_tokens') is None for r in records), - 'unknown_peak_vram_calls':sum(p is None for p in peaks)} - -def validate_call(request,result,backend): - exact(request['generation'],backend['generation'],'request generation') - exact(result['generation'],backend['generation'],'result generation') - exact(result['parameter_devices'],['cuda:0'],'parameter devices') - exact(result['parameter_dtypes'],['torch.float16'],'parameter dtypes') - exact(result['attention_implementation'],backend['attention_implementation'],'attention implementation') - require(type(result['seconds']) in (int,float) and math.isfinite(result['seconds']) and result['seconds']>=0,'generation duration invalid') - error = result['error'] - for key in ('input_tokens','output_tokens'): - value = result[key] - require(value is None or type(value) is int and value>=0, f'{key} invalid') - if not error: - require(isinstance(result['raw_text'],str),'successful generation raw text missing') - exact(result['input_devices'],['cuda:0'],'input devices') - require(result['input_tokens'] is not None and result['input_tokens']+512<=32768,'context cap violated') - require(result['output_tokens'] is not None and result['output_tokens']<=512,'output cap violated') - exact(result['truncation_at_budget'],result['output_tokens']>=512,'output budget flag') - else: - require(result['raw_text'] is None,'backend fault with raw text') - if result['output_tokens'] is None: - require(not result['truncation_at_budget'],'backend fault output evidence invalid') - else: - # Backend records tokens/flag before decode, which can itself fail. - exact(result['input_devices'],['cuda:0'],'input devices') - require(result['input_tokens'] is not None and result['input_tokens']+512<=32768,'context cap violated') - require(result['output_tokens']<=512,'output cap violated') - exact(result['truncation_at_budget'],result['output_tokens']>=512,'output budget flag') - if error.startswith('ContextBudgetExceeded:'): - require(result['input_tokens'] is not None and result['input_tokens']+512>32768,'context fault below cap') - exact(result['input_devices'],[],'context failure before tensor transfer') - exact(set(result['memory']),{'memory_allocated','memory_reserved','max_memory_allocated'},'memory telemetry keys') - require(set(result['telemetry_errors'])<=set(result['memory']),'unknown telemetry error') - for name,value in result['memory'].items(): - require((value is None and name in result['telemetry_errors']) or (type(value) is int and value>=0 and name not in result['telemetry_errors']), 'memory metric/error mismatch') - -def validate_sources(snapshot,environment): - manifest = read(ROOT/'reviews/source-manifest-01.json') - entries = manifest['files'] - require(len(entries)==121,'frozen source count mismatch') - signature = hashlib.sha256(''.join(f"{e['path']}\t{e['bytes']}\t{e['sha256']}\n" for e in sorted(entries,key=lambda e:e['path'])).encode()).hexdigest() - exact(signature,SIGNATURE,'frozen source signature') - for entry in entries: - for base in (ROOT,snapshot): - path = base/entry['path'] - require(path.is_file() and path.stat().st_size==entry['bytes'] and sha(path)==entry['sha256'],f'frozen source hash mismatch: {path}') - core = {e['path']:e['sha256'] for e in entries if e['path'].split('/')[0] in ('program_loop','vendor','tools')} - require(len(core)==109,'core manifest count must be exactly 109') - actual = {p.relative_to(snapshot).as_posix() for base in ('program_loop','vendor','tools') for p in (snapshot/base).rglob('*') if p.is_file() and '__pycache__' not in p.parts} - exact(actual,set(core),'core source inventory') - exact(environment['core_source_sha256'],core,'environment all 109 core SHA') - -def audit_snapshot(snapshot,reference_inputs,model_manifest): - snapshot = Path(snapshot).resolve() - run = snapshot/'runs/smoke-01' - inputs = read(run/'inputs.json') - exact(inputs,read(reference_inputs),'same exact historical unlabelled inputs/registry/budget') - exact(inputs['budget'],BUDGET,'fixed smoke budget') - rows,registry = inputs['rows'],inputs['registry'] - require(len(rows)==3 and len(registry)==6,'three rows and six registry entries required') - require(len({r['id'] for r in rows})==3,'source IDs not unique') - require(all(set(r)=={'id','domain','metadata'} and set(r['metadata'])=={'field_name','field_description'} for r in rows),'labels or unexpected initial fields') - env = read(run/'environment.json') - validate_sources(snapshot,env) - expected_env = {'seed':20260928,'context_cap':32768,'max_new_tokens':512,'per_generate_max_time':90.0,'whole_process_timeout_seconds':900, - 'whole_process_timeout_enforced_by':'external coordinator','inference':'FP16 cuda:0 batch1 greedy enable_thinking=False'} - for key,value in expected_env.items(): - exact(env[key],value,f'environment {key}') - require(type(env['pid']) is int and env['pid']>0,'environment PID invalid') - require(all(env['packages'].get(p) for p in ('torch','transformers','accelerate','huggingface_hub','safetensors')),'environment package versions missing') - trusted = read(ROOT/'reviews/trusted-model-manifest-01.json') - exact(read(model_manifest),trusted,'trusted model manifest identity/files/bytes/SHA') - require(trusted['repo_id']=='Qwen/Qwen3.5-9B' and trusted['revision']==REVISION and len(trusted['files'])==11 and trusted['total_bytes']==19329302129,'official pinned identity invalid') - backend = read(run/'calls/backend.json') - for key,value in {'repo_id':'Qwen/Qwen3.5-9B','revision':REVISION,'parameter_devices':['cuda:0'],'parameter_dtypes':['torch.float16'], - 'offline_options':{'local_files_only':True,'trust_remote_code':False},'config_type':'qwen3_5','model_class':'Qwen3_5ForConditionalGeneration'}.items(): - exact(backend[key],value,f'backend {key}') - gen = backend['generation'] - exact(gen,{'do_sample':False,'max_new_tokens':512,'max_time':90.0,'eos_token_id':248044,'pad_token_id':248044},'fixed generation/EOS') - paths = sorted((run/'calls').glob('call-*')) - exact([p.name for p in paths],[f'call-{i:04d}' for i in range(1,len(paths)+1)],'contiguous model call records') - records = [] - for path in paths: - request,result = read(path/'request.json'),read(path/'result.json') - validate_call(request,result,backend) - combined = json.dumps(request['messages'],ensure_ascii=False) - require(all(row['id'] not in combined for row in rows),'source ID exposed in model messages') - records.append({'request':request,'result':result}) - # Import only after validating every source byte; process must not have loaded - # another copy of program_loop before this point. - require('program_loop' not in sys.modules,'audit CLI must run in a fresh process') - sys.path.insert(0,str(snapshot)) - replay = RecordedBackend(records) - traces, row_calls = [], [] - for row in rows: - start = replay.position - traces.append(replay_trace(read(run/'samples'/(row['id']+'.json')),replay,registry,rows,inputs['budget'],row)) - row_calls.append(call_summary([r['result'] for r in records[start:replay.position]],replay.roles[start:replay.position])) - replay.finish() - require('torch' not in sys.modules and 'transformers' not in sys.modules,'CPU audit imported model runtime') - report = {**trace_summary(traces),**call_summary([r['result'] for r in records],replay.roles), - 'source_signature_sha256':SIGNATURE,'core_files_sha_matches':109,'model_revision':REVISION, - 'raw_request_trace_exact_match':True,'full_trace_replay_exact_match':True,'normalized_bindings_dependencies_verified':True, - 'initial_metadata_description_hidden':True,'source_ids_not_in_planner_messages':True,'same_unlabelled_inputs_as_previous_smoke':True, - 'all_source_ids_not_in_model_messages':True, - 'snapshot':str(snapshot),'reference_inputs_sha256':sha(reference_inputs),'trusted_model_manifest_sha256':sha(ROOT/'reviews/trusted-model-manifest-01.json')} - summary = read(run/'summary.json') - for key in ('model_calls','planner_attempts','accepted_plans','skill_steps','input_tokens','output_tokens','generation_seconds'): - exact(summary[key],report[key],f'runner summary {key}') - exact(summary['terminated_count'],report['legal_terminations'],'runner summary legal terminations') - expected_errors = [{'error':r['result']['error']} for r in records if r['result']['error']] - exact(summary['backend_errors'],expected_errors,'all backend failure denominator') - exact(summary['status'],'backend_failure' if expected_errors else 'completed','runner completion status') - expected_samples = [{'id':row['id'],'terminated':t['terminated'],'stop_reason':t['stop_reason'],'budget':t['budget'], - 'planner_errors':sum('error' in a for a in t['planner_attempts']), - 'execution_errors':sum(s['status']!='success' for p in t['programs'] for s in p['steps'])} for row,t in zip(rows,traces)] - exact(summary['samples'],expected_samples,'all runner samples including failures') - for row,detail,calls in zip(rows,report['details'],row_calls): - detail['id'] = row['id'] - detail.update(calls) - detail['execution_errors'] = sum(s['status']!='success' for s in detail['actual_skills']) - report['call_details'] = [{'call':p.name,'role':role,**{key:r['result'][key] for key in ('input_tokens','output_tokens','seconds','memory','telemetry_errors','error','truncation_at_budget')}} for p,r,role in zip(paths,records,replay.roles)] - return report - -def write_report(path,report): - with Path(path).open('x',encoding='utf-8') as stream: - json.dump(report,stream,ensure_ascii=False,indent=2,allow_nan=False) - stream.write('\n') - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--snapshot',type=Path,default=ROOT/'remote-snapshot-01') - parser.add_argument('--reference-inputs',type=Path,default=ROOT/'reviews/reference-inputs.json') - parser.add_argument('--model-manifest',type=Path) - args = parser.parse_args(argv) - target = ROOT/'reviews/independent-smoke-audit-01.json' - require(not target.exists(),'exclusive audit output already exists') - report = audit_snapshot(args.snapshot,args.reference_inputs,args.model_manifest or args.snapshot/'reviews/remote-model-manifest-01.json') - write_report(target,report) - print(json.dumps({k:v for k,v in report.items() if k not in ('details','call_details')},ensure_ascii=True,indent=2)) - -if __name__ == '__main__': - main() diff --git a/research/finance_program_v1/nontraining/reviews/source-manifest-01.json b/research/finance_program_v1/nontraining/reviews/source-manifest-01.json deleted file mode 100644 index 83fac3d..0000000 --- a/research/finance_program_v1/nontraining/reviews/source-manifest-01.json +++ /dev/null @@ -1,618 +0,0 @@ -{ - "source_signature_sha256": "94ae314646625e078d7b0f8ee6315bf37778e1ce81bd8435a1417f43c769da1d", - "file_count": 121, - "core_file_count": 109, - "baseline_signature": "8c9a2d2b51a821942d589150d46814571c4376221945a3d607bc19d9bc9290f8", - "changed_baseline_files": [ - "tests/test_program_loop.py", - "vendor/pool_runtime.py", - "vendor/runtime/skills/full_pool/standard_alignment_COMPARE_STANDARD_CANDIDATES.md" - ], - "files": [ - { - "path": "README.md", - "bytes": 3262, - "sha256": "4a95691f70cfddafe3cb50e4876a0a68cac77883489c13f5da7297d5f7564ca6" - }, - { - "path": "download_model.py", - "bytes": 6312, - "sha256": "5e435d6f87d920d58ff6d305afe61be3a98fec8d12b6f79986072a9a208a8edd" - }, - { - "path": "local_smoke.py", - "bytes": 12705, - "sha256": "30d7f733c0b506f7ac9a4870d7523aa09e485316953df8973b7e7fb049322d88" - }, - { - "path": "program_loop/__init__.py", - "bytes": 270, - "sha256": "8ebc1b9a3937a1848c199126edf97e5862741ede120a491e87a8473d6c0f7c46" - }, - { - "path": "program_loop/__main__.py", - "bytes": 48, - "sha256": "935a1c1166b0c1ea35a82256345000bf2c73ded718d77773bc27a71ecce28f7d" - }, - { - "path": "program_loop/_vendor.py", - "bytes": 305, - "sha256": "cfb187e38a0b8acd86e83476ee24f3aa02928c86fd3deb532f752ae8784bbf80" - }, - { - "path": "program_loop/catalog_context.py", - "bytes": 804, - "sha256": "d59a7d3636fa7cb92ba5fff2126a9aee2b6a2166970b20ec4a834abdd3235409" - }, - { - "path": "program_loop/cli.py", - "bytes": 4594, - "sha256": "82d3841baa287c2d5e0cf519ae2532a4fd5a4d79e89d907e29ad029c17d59335" - }, - { - "path": "program_loop/contracts.py", - "bytes": 2054, - "sha256": "884a776db1a44475943a5b08370bad9d6107cfcbe7f40380622515e85713cb51" - }, - { - "path": "program_loop/controller.py", - "bytes": 6294, - "sha256": "37de0a7bc235c7528b48e95222fd3f291fd4054d063578a46d23327bad4e6c51" - }, - { - "path": "program_loop/execution.py", - "bytes": 5211, - "sha256": "f9f61e8a3e62d827ff0ceccc57f1d08c27b63c017ca3f1506c2955433d5b5bea" - }, - { - "path": "program_loop/planner.py", - "bytes": 5519, - "sha256": "98f1510561808070bbf712f1d319a57453339909b18ca283ed76c02f045da575" - }, - { - "path": "program_loop/planning_contracts.py", - "bytes": 1492, - "sha256": "90d671bb998814249379db93c887ece2df70476d12a4e8bbc15dd6ccd78f6845" - }, - { - "path": "program_loop/recovery_context.py", - "bytes": 3147, - "sha256": "a6660c91d3e77804146b12ce1b77fb0974977bb75fd98cf81c6225f02ae48013" - }, - { - "path": "program_loop/rejection_context.py", - "bytes": 1329, - "sha256": "fd71ad424ff4a201b01f4db7276f2d958fd94eba7aaf26deb16cc54dbcb9de1f" - }, - { - "path": "program_loop/validation.py", - "bytes": 4625, - "sha256": "8ac6c4bfa272c60fb0149eab43b73c9b9b5e210859940eef316dfa00e4723e23" - }, - { - "path": "tests/test_9b_identity.py", - "bytes": 1300, - "sha256": "d350a177fc710dadf08121abe09bd0b89e2a14785e203535ea611a1bff102b5c" - }, - { - "path": "tests/test_dynamic_references.py", - "bytes": 5043, - "sha256": "588688f185f721c742e78f336ab5b42b7f7a695c87a0b8640208412372edc30e" - }, - { - "path": "tests/test_local_smoke.py", - "bytes": 20015, - "sha256": "dfdc361c3a7243c5ee78645d1d2d7bb449927633d061bfd76986fb081e6be601" - }, - { - "path": "tests/test_planning_contracts.py", - "bytes": 13708, - "sha256": "992da01d882c51a288b298db790705589e0cf16f92e9ecd4e611746c96504560" - }, - { - "path": "tests/test_program_loop.py", - "bytes": 22282, - "sha256": "18d251a2781b0bc89e9ff50fe53afe364a9e7a35fb48f19f610af987582a14fd" - }, - { - "path": "tests/test_recovery_context.py", - "bytes": 5958, - "sha256": "ba4e725f74a216831466b56f3b93616ca82dd36d0d77d690185f2e13d14de08e" - }, - { - "path": "tests/test_rejection_context.py", - "bytes": 5316, - "sha256": "48024ea991eceb98c0eb2cc9d292f9092ded253d995cbc4398b3a1dfed9bdce3" - }, - { - "path": "tests/test_source_integrity.py", - "bytes": 2617, - "sha256": "8141193bf6771e3c0a2bedbf5bb7999ba32bbaa6f74adc77fa1a18d941ea37ea" - }, - { - "path": "tests/test_task_level_prompt.py", - "bytes": 11167, - "sha256": "165fe55de77344c81d97de30eb532b7aadd326ce3f91a502025d5ab571ac4fc5" - }, - { - "path": "tools/check_local_gpu.py", - "bytes": 2809, - "sha256": "4b28ea500f7573dedc1801a8b73c8ddaa4b26d8f87e9a6624682a3aa2d8ac7f3" - }, - { - "path": "tools/verify_source.py", - "bytes": 2762, - "sha256": "c1d14bc3f5641a725d9c8d0be05391215bf696d850f3adf7e1239fbec5f02294" - }, - { - "path": "vendor/common.py", - "bytes": 5142, - "sha256": "c79a02e987a169436796f438a415d7c309c0e0cf50bb447e493cd68cb9301fa4" - }, - { - "path": "vendor/pool_availability.py", - "bytes": 6074, - "sha256": "c6fa8e23a678b4451ef78d301efb347507fb0513a9d18bfda76eeefc824d70aa" - }, - { - "path": "vendor/pool_bindings.py", - "bytes": 2822, - "sha256": "3c0c65e78f7bcdc5bb81003b455fd957dba5c4abdbfdaa20b8fddb3b155e07db" - }, - { - "path": "vendor/pool_catalog.py", - "bytes": 7159, - "sha256": "bd19db2c908d41120498eae4afc26e30726b60ddf7fbf834e77ca6251e8c8a82" - }, - { - "path": "vendor/pool_metadata.py", - "bytes": 5969, - "sha256": "0705318048785fd34edd970274145dec359269e5e30756a996eb156e168e3a8a" - }, - { - "path": "vendor/pool_runtime.py", - "bytes": 34139, - "sha256": "506f2b605a32b0a1cf1431cdd4b92f5ccf821909d20726f8aacdd672ab0a893d" - }, - { - "path": "vendor/reference_skills_63.json", - "bytes": 2232, - "sha256": "a63b6ee85f983caf9f55d537fe85d24a283a860ccb0985c8a7fce8b1466e3caf" - }, - { - "path": "vendor/runtime/code/agent/__init__.py", - "bytes": 110, - "sha256": "c2ee5b379bec6f6381e0651bee6078e38ad6ca294f497d40b6d27e583fd1492e" - }, - { - "path": "vendor/runtime/code/agent/orchestration/__init__.py", - "bytes": 946, - "sha256": "64f470fa2d85450ebbd8819a66c63064bcdbf993c829d248c64315285e7aca73" - }, - { - "path": "vendor/runtime/code/agent/orchestration/agent_loop.py", - "bytes": 39927, - "sha256": "176bc72eebd17a7d2e45276654c49cbd5b1828306e11d2579faffe143eebcade" - }, - { - "path": "vendor/runtime/code/agent/orchestration/artifact_projection.py", - "bytes": 2952, - "sha256": "d71939b3e4b04b83d33f7aedbc3173cd44043b8a55d44c149c46f35d5aa3f7d8" - }, - { - "path": "vendor/runtime/code/agent/orchestration/catalog.py", - "bytes": 5851, - "sha256": "66ceb63dd02030cecb3965247a671da64c4d29724ece9a5eb52961a0647c8e6a" - }, - { - "path": "vendor/runtime/code/agent/orchestration/category_catalog.py", - "bytes": 4738, - "sha256": "baf7b0b234822060b48dded26f00d526654749f1384c3e23f9eb07ddc8fa0a58" - }, - { - "path": "vendor/runtime/code/agent/orchestration/contracts.py", - "bytes": 3654, - "sha256": "19ed69938bdc517be14625e0ef886945dc4483faeb6a8260fdfcacaffa83f233" - }, - { - "path": "vendor/runtime/code/agent/orchestration/metadata_lookup.py", - "bytes": 2340, - "sha256": "e338e0d804caa20218637074422b08f26b16fdbdd9faff39077a1cb73beb89fc" - }, - { - "path": "vendor/runtime/code/agent/orchestration/metrics.py", - "bytes": 2007, - "sha256": "fffb69bd3e8efa149e46e3413b4056457840b9cd8f6798fd5e0871cdb7e3a0b3" - }, - { - "path": "vendor/runtime/code/agent/orchestration/model_skill_executor.py", - "bytes": 40196, - "sha256": "03a90c6c58ffad2dddc9fa5c8982045eb2a73a804f521c2c679f61e14e17f3b0" - }, - { - "path": "vendor/runtime/code/agent/orchestration/planner.py", - "bytes": 16361, - "sha256": "5be67a873f8fa54c183c9fa381def425b73cc92181fab6079506eb2296fa53d8" - }, - { - "path": "vendor/runtime/code/agent/orchestration/retrieval.py", - "bytes": 12500, - "sha256": "fbe140936695f38c6bc6838c5a9a0100ca9e6f98b6e77984e587fdbea28b6bf4" - }, - { - "path": "vendor/runtime/code/agent/orchestration/runtime.py", - "bytes": 7641, - "sha256": "887e82115154f043801719b5e292895e3eeef0d25e277748805a0c1dabc39acc" - }, - { - "path": "vendor/runtime/code/agent/orchestration/skill_loader.py", - "bytes": 6180, - "sha256": "7528bada337e98b69ef61ccf558574f5940d26fcfc2106530f8c9d0d765964f6" - }, - { - "path": "vendor/runtime/code/agent/orchestration/table_field_lookup.py", - "bytes": 3864, - "sha256": "93319c4ee044439f9e25449cec220dfaededa1c6b799816486d19402b569dc22" - }, - { - "path": "vendor/runtime/code/agent/orchestration/topk_selection.py", - "bytes": 3147, - "sha256": "a58411d1acb421bd5e5c134f4ceef7ccce76851f684a397446904b7a17b1eb4c" - }, - { - "path": "vendor/runtime/code/agent/orchestration/validator.py", - "bytes": 5283, - "sha256": "15fd2b9faca5addf49f4fdf5d816eb2ecb3723c6b800da3fd591cda93b0bedcd" - }, - { - "path": "vendor/runtime/code/script/orchestration/__init__.py", - "bytes": 72, - "sha256": "7c61249a27a9c7ad011f983e9857e3889ae54837d00faf2660fe2f72350b30d6" - }, - { - "path": "vendor/runtime/code/script/orchestration/run_agent_loop_batch.py", - "bytes": 51611, - "sha256": "6605815bf479e8fc50a3041af3c2430b3f121740bf38b8e6d497212d4425616d" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_ASSESS_CATEGORY_SUPPORT.md", - "bytes": 880, - "sha256": "85ea64633013f69d582707acf4ab1b32201cf5ebbf7e0356041119d6c08c106a" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_CHECK_EVIDENCE_SUFFICIENCY.md", - "bytes": 572, - "sha256": "f879c21470b9daeb773a80a256a07f7a6f43e38e8452347f128eca6391362f4a" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_COMPARE_CATEGORY_HYPOTHESES.md", - "bytes": 844, - "sha256": "3fa31691df6bb353b4171a8c837da229549f8f4eff827bf502f81cb2318432a5" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_DECIDE_NEXT_EVIDENCE_SOURCE.md", - "bytes": 990, - "sha256": "647a447ae584d92e67c17d2d7040ff48d14cb8d2b5039345d65eb072b5c14fd3" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_FINALIZE_CLASSIFICATION.md", - "bytes": 637, - "sha256": "cd66513c1ca4b6728bd217ae57a7ad7cd96257f61443a7af2ac1edd7e746f937" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_CONTEXT_EVIDENCE.md", - "bytes": 867, - "sha256": "b0028a313fa3f81350f07093c5389c7ec0447539119e37930f1f05bceec539d1" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_DATABASE_EVIDENCE.md", - "bytes": 835, - "sha256": "e27e9b2f57b5b1929d5286a10cc15233ab48ba40948fe520fde8853f66bc1e56" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_FIELD_EVIDENCE.md", - "bytes": 870, - "sha256": "6dfef164297cb75a02f64ebbdafecb3f0519f1a5f1992c3bb9a98157b7a7ee54" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_METADATA_EVIDENCE.md", - "bytes": 880, - "sha256": "e3a7e0de334bc39836c3a909edc79233075b0b73f7c30e879d4e087bc94aa6f2" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_STANDARD_EVIDENCE.md", - "bytes": 880, - "sha256": "eddac25de1c3dda0baf876d29a7a32ae4fab980f2ae7ce892def82af3469087a" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_TABLE_EVIDENCE.md", - "bytes": 801, - "sha256": "24c7eb0ea3381b640465e78e41eb2ff43495e7bb3eadcc652e5587c3bd167ab4" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_IDENTIFY_MISSING_EVIDENCE.md", - "bytes": 990, - "sha256": "237695b8b5d6f9a7105902dc32a120297c364ee5f8d1c27f4ead212df110668f" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY.md", - "bytes": 586, - "sha256": "032b758517d3a8535c29d20d8391bd8d27a2ad1d5c7e9f62246578076ddb5197" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY_FROM_TOPK.md", - "bytes": 678, - "sha256": "7af18e11373d633fe4369338336c653b47238c214cb5f1937e0a5b30041f722f" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_INFER_GRADING_LEVEL.md", - "bytes": 588, - "sha256": "276b5e1a8b080d9aecec762762939372f40e56c8fb4b1eb92964c53073b6d603" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_FIELD_CONTEXT_CONFLICT.md", - "bytes": 908, - "sha256": "94e552edccadc03cb55a5ab8e54511a296971363bd4aafb30b3ab1385e5a18f3" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_METADATA_CONFLICT.md", - "bytes": 863, - "sha256": "643472dc5b7e7cdb38f3483857acc94d539884efede9b9ed0f4cccc79a037d0b" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_STANDARD_CONFLICT.md", - "bytes": 878, - "sha256": "be9b9c9c879b964acf4b5f7317dcf90c68833a1f98f6cb8ab9f8199460066b25" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CATEGORY_WITH_STANDARD.md", - "bytes": 944, - "sha256": "deb07baab54b052a9323b475c912d7743115c96dd4b1dd0b7c4a80df3e3d0dfc" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CLASSIFICATION_GRADING_CONSISTENCY.md", - "bytes": 932, - "sha256": "ff8ef17c1ce1408496c6634389ecba87f6d282d0264e4ac1ee9a8c2deb12bab1" - }, - { - "path": "vendor/runtime/skills/full_pool/evidence_reasoning_WEIGH_EVIDENCE.md", - "bytes": 874, - "sha256": "c928a03a7a8f2d8b1a28ffb01c100543000a62e4a388a0e60051a4b6815dd43f" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_ACQUIRE_MISSING_METADATA.md", - "bytes": 998, - "sha256": "cc788f17f7c63e1f7974f220eca3becfb186d3df287a35d814a5387964d20ce3" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_CHECK_METADATA_AVAILABILITY.md", - "bytes": 576, - "sha256": "fe27b6f518a98be4e88414d6180180954572f222fec37dfc4591e2b72a05ad5a" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_EXPAND_SELECTED_CONTEXT.md", - "bytes": 964, - "sha256": "323b136804a9db277d6642b71de277ae3fcd7021910645475872b1b018d79a79" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_DATABASE_CONTEXT.md", - "bytes": 913, - "sha256": "0008e4dc6b220757208cb656912ebb609c8230aaf62ce56a33f247dc5879f7cd" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_TABLE_CONTEXT.md", - "bytes": 914, - "sha256": "09b1f136ca45244c603e98aba0bec6fad8997ca2e618eeaeaf7ac1c1de4fb711" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_DESCRIPTIONS.md", - "bytes": 947, - "sha256": "0b5f7d9ced8902a3a7157d6781a3b3d6bc9fb9f2d2c55da99f31977ceb5609b8" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_TYPES.md", - "bytes": 945, - "sha256": "61cfe7efeb0980d22e72c4069e70cb91d1a007c7352b528b600b7efbcfd313e5" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_VALUES.md", - "bytes": 983, - "sha256": "780305d46253a0ab132f35feee6ba420347f351326827c4be781bd4224349504" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_DATABASE_DESCRIPTION.md", - "bytes": 903, - "sha256": "37b2146b9cd669e1dc0cb0a54c0f6ee36dc0157ce1e4e753d96be08a6fdada21" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_DESCRIPTION.md", - "bytes": 951, - "sha256": "d545962070cb10fa90ee1693261d48ee08df616cad4d098bfcd98643100fce7b" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_METADATA.md", - "bytes": 801, - "sha256": "372ce861fcca6138cda43b693a8fc32f85c0ec380b0c275c3cfe613dbe25f629" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_DESCRIPTION.md", - "bytes": 879, - "sha256": "912334b76f95c6f468cf4bab840ae0ec3a262639c59e545db63bfce866710ea0" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_FIELDS.md", - "bytes": 935, - "sha256": "99c01c5869b511754feccfd335017c7f4290683fbcc46ed6355b95f775d605b0" - }, - { - "path": "vendor/runtime/skills/full_pool/metadata_acquisition_SELECT_CONTEXT_FIELDS.md", - "bytes": 992, - "sha256": "aacb11c41507d2c2743e56a7915c9dae9d6b4e2ff3ece6fec6b3d73babeb6683" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_DISAMBIGUATE_FIELD_SEMANTICS.md", - "bytes": 626, - "sha256": "e497bddaf99da95503677a969926921b507b92ad542055dafaa88ee724a235d0" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_DATABASE_ABBREVIATION.md", - "bytes": 927, - "sha256": "2338078f06cd5276b326747fa0b80790d3c638ba369f6579e4ddcff84882eb51" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_FIELD_ABBREVIATION.md", - "bytes": 576, - "sha256": "6b84b95768e4cc77d193b31871f3b75ab17ff86f526c4000bccd6f8c423cb2a7" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_TABLE_ABBREVIATION.md", - "bytes": 910, - "sha256": "6ce033822d4d4f4ae7babba7bd0b44fa871476353b81fd86ac6742d266b3a426" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_CONTEXT_FIELDS.md", - "bytes": 948, - "sha256": "297bf09515bbbc0a4b9e6f80fb77c7135b7484c5c428da0868d7a0d0732717cb" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_DESCRIPTION.md", - "bytes": 925, - "sha256": "acc57509cff6330476522f8fc5a7b286b0ede3e477c9806000b54542f89070dc" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_NAME.md", - "bytes": 880, - "sha256": "e427e888ac10d742784d390ad2bdce40d0aec7c9a7abd52b5f5497fc83b866fc" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DOMAIN.md", - "bytes": 505, - "sha256": "6e1760ff387797cb4c171f404f744b6b6b87445969659bf8b37c8bca66de5375" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_DESCRIPTION.md", - "bytes": 681, - "sha256": "a833b94c6c7afd5e740d67674662178e9b2f9cef6e0019dd9af8bbf62b324335" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_NAME.md", - "bytes": 610, - "sha256": "99934fabad8007d155624a475b1600b5b8139152efde2a9154cd7035e42ba56e" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_TYPE.md", - "bytes": 893, - "sha256": "93500ee995113eed8ee9d6d8887d6f65f2d4aa6ac52b12697fb8e82982c1b49d" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_VALUE.md", - "bytes": 897, - "sha256": "c0dad806fde006487b38b9d56fc0b5fde6cc2e367b8a46d13adb5c4171ed19ad" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_DESCRIPTION.md", - "bytes": 713, - "sha256": "901cef9276dd30ff1b2e35fb39bbe9138cf42bb4ded47b37fb3afe83c1945ac2" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_NAME.md", - "bytes": 857, - "sha256": "bfd2506982a98615fa40d2a2760893f7634a270a663f65a84547e4a2ec7a4186" - }, - { - "path": "vendor/runtime/skills/full_pool/semantic_interpretation_SYNTHESIZE_METADATA_SEMANTICS.md", - "bytes": 1085, - "sha256": "4d64debe0b8657d6c0960eb5e3eebad7aa5125e34e35f66deb38c050f665ec26" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_ALIGN_CONTEXT_TO_STANDARD.md", - "bytes": 935, - "sha256": "debf2fb145c10526e4952ba7cb322d8a88370ae136d1ae6f0b74b7b9d60734b0" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DATABASE_TO_STANDARD.md", - "bytes": 1007, - "sha256": "5bdb03e45720da5ff53297fae7ce476e6fd46f3af6277e8be147a87033917630" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DESCRIPTION_TO_STANDARD.md", - "bytes": 982, - "sha256": "ec00677a4433b6110f529eafc28d5c0272746f186121ee563ab86eb8a3a9a6ec" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_ALIGN_FIELD_TO_STANDARD.md", - "bytes": 941, - "sha256": "19c1e2c28c4df124d9ef56501635c31443552cc3d103d727b927db78891eb53f" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_ALIGN_TABLE_TO_STANDARD.md", - "bytes": 986, - "sha256": "7fa123b49aca5ec7f2525d3697e0108aaf3d85f61c966eb9492a19b657e2a300" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_ALIGN_VALUE_TO_STANDARD.md", - "bytes": 932, - "sha256": "d71db5f6adcf269897e8c9b662cc31edc18b7a7727db7a241624e319a390588e" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_COMPARE_STANDARD_CANDIDATES.md", - "bytes": 933, - "sha256": "d5e82a8d994155a010de18c15a1923a432e2e039a0aa3016bc1a7689cdfe9fdb" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_REFINE_STANDARD_QUERY.md", - "bytes": 980, - "sha256": "51c1ead62e9d83c194ac1fc24c8f43b9879497477b79054e03384b6ded980420" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_RESEARCH_STANDARD.md", - "bytes": 908, - "sha256": "05ccd5f271a060ed497242c494c34d8ce3cac22f03e6349d0d6edfe0a4b303ac" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD.md", - "bytes": 550, - "sha256": "dcbd3841440dc7bf0ee22c02b9ba1014fff1fa6a68900f270bb8cbb40aa9074c" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_CONTEXT.md", - "bytes": 908, - "sha256": "6c1c9ad8fd7036ddf2504e30bc4f920d9754c8c3de68f2ff5263f760630d839e" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_DATABASE.md", - "bytes": 909, - "sha256": "fc38fe4bccc6637de6abe3b8434f7d069d42b6eabf1a8dc29b98cfcdd443a362" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_FIELD.md", - "bytes": 875, - "sha256": "98862fb615e97f189420455219b484ef990e0f4768f7ba4e49983e237d3998f2" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_TABLE.md", - "bytes": 874, - "sha256": "ae067ae1570ad6e24e5c43a08aa4057223923b45e2593525255419144847ebd0" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_SELECT_CATEGORY_TOPK.md", - "bytes": 742, - "sha256": "c0dac66df87884c2ecd0e6dbfe2af1027b522a1653972ffa4d79e8a957a9bb74" - }, - { - "path": "vendor/runtime/skills/full_pool/standard_alignment_SUMMARIZE_STANDARD_EVIDENCE.md", - "bytes": 996, - "sha256": "ea3ee35fa9ddde244353f533a527bf25674ffb711218f74c8960862183bd664b" - }, - { - "path": "vendor/skill_reference.json", - "bytes": 20313, - "sha256": "752ed72d4ed6e987542197dfff40786ebd4487bcf6b1042cbf769d1fed2392b8" - }, - { - "path": "vendor/study.py", - "bytes": 17396, - "sha256": "d8c78d387e00b13762fb509d23e147210b0016931879c4af7089c593d6eddbb3" - } - ] -} diff --git a/research/finance_program_v1/nontraining/reviews/trusted-model-manifest-01.json b/research/finance_program_v1/nontraining/reviews/trusted-model-manifest-01.json deleted file mode 100644 index fac39da..0000000 --- a/research/finance_program_v1/nontraining/reviews/trusted-model-manifest-01.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "repo_id": "Qwen/Qwen3.5-9B", - "revision": "c202236235762e1c871ad0ccb60c8ee5ba337b9a", - "total_bytes": 19329302129, - "download_identity_sha256": "3087a66dc953b6aaa159fdf5286eb894d805c0c686f6d202452cf7ceb6039dea", - "files": [ - { - "path": "chat_template.jinja", - "bytes": 7756, - "expected_sha256": null, - "sha256": "a4aee8afcf2e0711942cf848899be66016f8d14a889ff9ede07bca099c28f715" - }, - { - "path": "config.json", - "bytes": 3126, - "expected_sha256": null, - "sha256": "d0883072e01861ed0b2d47be3c16c36a8e81c224c7ffaa310c6558fb3f932b05" - }, - { - "path": "merges.txt", - "bytes": 3353259, - "expected_sha256": null, - "sha256": "a9d356d7bdf1ef4949e3e748e95b8e10ad9d4e2e838eddc38a0a7b6b94d1db8d" - }, - { - "path": "model.safetensors-00001-of-00004.safetensors", - "bytes": 5276436216, - "expected_sha256": "db6f444b43d318c92f360a13a25561a6a65b10c0631b8ed305a426dbaa6c380e", - "sha256": "db6f444b43d318c92f360a13a25561a6a65b10c0631b8ed305a426dbaa6c380e" - }, - { - "path": "model.safetensors-00002-of-00004.safetensors", - "bytes": 5335161512, - "expected_sha256": "31c7d7e2dd5d207840b31cc59083c8f4c4718959149e0358c0364052bb9a0330", - "sha256": "31c7d7e2dd5d207840b31cc59083c8f4c4718959149e0358c0364052bb9a0330" - }, - { - "path": "model.safetensors-00003-of-00004.safetensors", - "bytes": 5368717440, - "expected_sha256": "7ec36ba3a4176a44c3c0876ad80c56a2f70c84bf008d82e9501df642f17dadec", - "sha256": "7ec36ba3a4176a44c3c0876ad80c56a2f70c84bf008d82e9501df642f17dadec" - }, - { - "path": "model.safetensors-00004-of-00004.safetensors", - "bytes": 3325995712, - "expected_sha256": "b62b0c4cd7e44edee103ee8f4fe225f246d5e768e07bfd5f25b63a8aa1fdd0c6", - "sha256": "b62b0c4cd7e44edee103ee8f4fe225f246d5e768e07bfd5f25b63a8aa1fdd0c6" - }, - { - "path": "model.safetensors.index.json", - "bytes": 79657, - "expected_sha256": null, - "sha256": "26d3539b516be613f39563617cb9d33b3f83d401298125be392c80cefb8f7fe5" - }, - { - "path": "tokenizer.json", - "bytes": 12807982, - "expected_sha256": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42", - "sha256": "5f9e4d4901a92b997e463c1f46055088b6cca5ca61a6522d1b9f64c4bb81cb42" - }, - { - "path": "tokenizer_config.json", - "bytes": 16710, - "expected_sha256": null, - "sha256": "316230d6a809701f4db5ea8f8fc862bc3a6f3229c937c174e674ff3ca0a64ac8" - }, - { - "path": "vocab.json", - "bytes": 6722759, - "expected_sha256": null, - "sha256": "ce99b4cb2983d118806ce0a8b777a35b093e2000a503ebde25853284c9dfa003" - } - ] -} diff --git a/research/finance_program_v1/nontraining/tests/test_9b_identity.py b/research/finance_program_v1/nontraining/tests/test_9b_identity.py deleted file mode 100644 index 2cee3ef..0000000 --- a/research/finance_program_v1/nontraining/tests/test_9b_identity.py +++ /dev/null @@ -1,36 +0,0 @@ -import importlib -import json -from pathlib import Path - -import pytest - - -def test_downloader_targets_official_9b_repo_and_default_path(): - download = importlib.import_module('download_model') - - assert download.REPO == 'Qwen/Qwen3.5-9B' - assert download.MODEL_DIR == Path(__file__).resolve().parents[1] / 'models' / 'Qwen3.5-9B' - - -def test_old_08b_identity_is_rejected_before_snapshot_or_manifest(tmp_path): - download = importlib.import_module('download_model') - model = tmp_path / 'model' - model.mkdir() - identity = { - 'repo_id': 'Qwen/Qwen3.5-0.8B', - 'revision': 'a' * 40, - 'files': [ - {'path': 'config.json', 'bytes': 2, 'expected_sha256': None}, - {'path': 'tokenizer.json', 'bytes': 2, 'expected_sha256': None}, - {'path': 'model.safetensors', 'bytes': 2, 'expected_sha256': None}, - ], - } - (model / 'download-identity.json').write_text(json.dumps(identity), encoding='utf-8') - - def forbidden_snapshot(**kwargs): - pytest.fail('snapshot invoked for an identity from the old model repo') - - with pytest.raises(ValueError, match='invalid official model identity'): - download.download_model(model, api=object(), snapshot=forbidden_snapshot) - - assert not (model / 'model-manifest.json').exists() diff --git a/research/finance_program_v1/nontraining/tests/test_dynamic_references.py b/research/finance_program_v1/nontraining/tests/test_dynamic_references.py deleted file mode 100644 index e63bca6..0000000 --- a/research/finance_program_v1/nontraining/tests/test_dynamic_references.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Dynamic values must come from current state; only model I/O is scripted.""" -import json - -import pytest - -from test_program_loop import FULL, REGISTRY, ROWS, Script, api, program, run -from program_loop.validation import canonical_reference, parse_program - - -@pytest.fixture -def controller(): - return api().build_program_controller(Script([]), REGISTRY, ROWS) - - -@pytest.mark.parametrize("value", [{}, [], None, 7, True, "handwritten", "$state.wrong"]) -def test_every_dynamic_catalog_input_rejects_noncanonical_explicit_values(controller, value): - catalog = controller.bridge.catalog - available = {key for spec in catalog.values() for key in (*spec.required_inputs, *spec.optional_inputs, *spec.produces)} - for spec in catalog.values(): - for key in (*spec.required_inputs, *spec.optional_inputs): - expected = canonical_reference(key, available) - if not expected.startswith("$state."): - continue - raw = program({"tool": spec.name, "arguments": {key: value}}) - with pytest.raises(ValueError, match=f"step 0: incorrect canonical reference for {key}; expected") as error: - parse_program(raw, catalog, available, 12) - assert expected in str(error.value) - - -def test_catalog_policy_and_prompt_explain_dynamic_values(controller): - from program_loop.planner import SYSTEM - for item in controller.library: - for details in item["planning"]["inputs"].values(): - expected = "canonical_reference_only" if details["canonical_reference"].startswith("$state.") else "initial_binding_contract" - assert details["explicit_value_policy"] == expected - assert "explicit_value_policy" in SYSTEM - assert "Never handwrite dynamic state values" in SYSTEM - - -def test_parser_preserves_omissions_and_canonical_aliases(controller): - raw = program("INTERPRET_FIELD_NAME", {"tool": "SELECT_CATEGORY_TOPK", "arguments": {"semantic_query": "$state.semantic_query"}}, - {"tool": "INFER_CATEGORY_FROM_TOPK", "arguments": {"candidate_standard_categories": "$state.standard_candidates"}}, - "INFER_GRADING_LEVEL", {"tool": "FINALIZE_CLASSIFICATION", "arguments": {"final_evidence_state": "$state.final_evidence_state"}}) - parsed = parse_program(raw, controller.bridge.catalog, {}, 12) - assert parsed.to_dict() == json.loads(raw) - assert parsed.steps[0].arguments == {} - assert "field_abbreviation_semantics" not in parsed.steps[0].arguments - - -def test_initial_literals_remain_legal_in_parser(controller): - raw = program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_name": "balance"}}, - {"tool": "INTERPRET_DOMAIN", "arguments": {"domain": "synthetic domain"}}, - {"tool": "GET_FIELD_METADATA", "arguments": {"current_record": {"field_name": "balance"}}}) - assert parse_program(raw, controller.bridge.catalog, {}, 12).to_dict() == json.loads(raw) - - -def test_unavailable_optional_remains_rejected(controller): - raw = program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_abbreviation_semantics": "$state.field_abbreviation_semantics"}}) - with pytest.raises(ValueError, match="step 0: missing dependency field_abbreviation_semantics"): - parse_program(raw, controller.bridge.catalog, {}, 12) - - -def test_explicit_available_optional_uses_canonical_path(controller): - raw = program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_abbreviation_semantics": "$state.field_abbreviation_semantics"}}) - assert parse_program(raw, controller.bridge.catalog, {"field_abbreviation_semantics": "observed"}, 12).to_dict() == json.loads(raw) - - -@pytest.mark.parametrize("key,value", [("semantic_query", {}), ("semantic_query", "observed text"), ("semantic_query", None)]) -def test_controller_rejects_dynamic_literal_before_any_execution_or_program_budget(key, value): - raw = program("INTERPRET_FIELD_NAME", {"tool": "SELECT_CATEGORY_TOPK", "arguments": {key: value}}) - _, trace, script = run([raw], max_planner_attempts=1) - assert trace.planner_attempts[0]["status"] == "rejected" - assert trace.planner_attempts[0]["raw_response"] == raw - assert f"step 1: incorrect canonical reference for {key}; expected $state.{key}" in trace.planner_attempts[0]["error"] - assert trace.budget == {"programs": 0, "planner_attempts": 1, "skill_steps": 0} - assert trace.programs == [] and script.kinds == ["planner"] - - -def test_canonical_future_query_binds_after_semantic_update(): - raw = program("INTERPRET_DOMAIN", "INTERPRET_FIELD_NAME", {"tool": "SELECT_CATEGORY_TOPK", "arguments": {"semantic_query": "$state.semantic_query"}}, *FULL[2:]) - _, trace, script = run([raw]) - assert trace.terminated - assert trace.programs[0]["steps"][2]["status"] == "success" - query_messages = next(messages for messages in script.messages if "selected Skill SELECT_CATEGORY_TOPK." in messages[0]["content"]) - assert "domain_semantics" in json.dumps(query_messages) - assert "field_semantics" in json.dumps(query_messages) diff --git a/research/finance_program_v1/nontraining/tests/test_local_smoke.py b/research/finance_program_v1/nontraining/tests/test_local_smoke.py deleted file mode 100644 index 06f820e..0000000 --- a/research/finance_program_v1/nontraining/tests/test_local_smoke.py +++ /dev/null @@ -1,393 +0,0 @@ -"""CPU boundary tests: these provide no evidence of actual CUDA generation.""" -import hashlib -import importlib -import json -from pathlib import Path -from types import SimpleNamespace - -import pytest - - -def module(name): - assert (Path(__file__).resolve().parents[1] / (name + '.py')).is_file(), 'missing implementation: ' + name - return importlib.import_module(name) - - -def read(path): - return json.loads(path.read_text(encoding='utf-8')) - - -def test_exclusive_output_reservation(tmp_path): - smoke = module('local_smoke') - smoke.reserve_run(tmp_path / 'run') - with pytest.raises(FileExistsError): - smoke.reserve_run(tmp_path / 'run') - - -def test_frozen_unlabelled_three_rows_and_six_definitions(): - registry, rows = module('local_smoke').smoke_inputs() - assert len(rows) == 3 and len(registry) == 6 - assert [r['id'] for r in rows] == ['local-balance', 'local-phone', 'local-invoice'] - assert [r['metadata']['field_name'] for r in rows] == ['account_balance', 'customer_phone', 'invoice_amount'] - assert [r['metadata']['field_description'] for r in rows] == ['账户当前余额', '客户联系手机号', '发票金额'] - assert all(set(r) == {'id', 'domain', 'metadata'} and r['domain'] == '金融' for r in rows) - assert all(set(r['metadata']) == {'field_name', 'field_description'} for r in rows) - assert set(registry) == {'account_balance', 'contact_phone', 'invoice_amount', 'customer_name', 'order_id', 'transaction_date'} - assert all(e['grading_level'] == 'L2' and e['description'] for e in registry.values()) - - -def test_offline_loading_and_fixed_inference_settings(): - smoke = module('local_smoke') - assert smoke.OFFLINE == {'local_files_only': True, 'trust_remote_code': False} - opts = smoke.generation_options(SimpleNamespace(eos_token_id=[8, 9], pad_token_id=0), SimpleNamespace(eos_token_id=7, pad_token_id=0)) - assert opts == {'do_sample': False, 'max_new_tokens': 512, 'max_time': 90.0, 'eos_token_id': [8, 9], 'pad_token_id': 0} - with pytest.raises(ValueError, match='EOS'): - smoke.generation_options(SimpleNamespace(eos_token_id=None, pad_token_id=None), SimpleNamespace(eos_token_id=None, pad_token_id=None)) - - -def test_context_rejected_without_truncation_and_thinking_disabled(): - smoke = module('local_smoke') - class Tokenizer: - def apply_chat_template(self, messages, **kw): - assert kw == {'tokenize': False, 'add_generation_prompt': True, 'enable_thinking': False} - return 'whole prompt' - def __call__(self, prompt, **kw): - assert prompt == 'whole prompt' and kw == {'return_tensors': 'pt', 'truncation': False} - return {'input_ids': SimpleNamespace(shape=(1, 32257))} - with pytest.raises(ValueError, match='context'): - smoke.encode_messages(Tokenizer(), [{'role': 'user', 'content': 'raw'}]) - - -class BoundaryBackend: - """Generation-only replacement; guard/executor/controller stay real.""" - def __init__(self, model_path, call_dir): - self.failures = [] - self.calls = [] - def __call__(self, messages): - self.calls.append(messages) - return '```json\n{"program": []}\n```' - - -@pytest.fixture -def runner_budget(tmp_path): - output = tmp_path / 'budget-run' - assert module('local_smoke').main( - ['--model', str(tmp_path), '--output', str(output)], backend_factory=BoundaryBackend) == 0 - return read(output / 'inputs.json')['budget'] - - -def test_real_runner_uses_fixed_budget10(runner_budget): - assert runner_budget == dict(max_programs=3, max_program_steps=10, max_skill_steps=12, - max_planner_attempts=4, max_identical_calls=1) - - -@pytest.mark.parametrize('length', [9, 10, 11]) -def test_real_parser_boundary_from_runner_budget(runner_budget, length): - from program_loop import build_program_controller, ProgramConfig - from program_loop.validation import parse_program - registry, rows = module('local_smoke').smoke_inputs() - controller = build_program_controller(lambda messages: '', registry, rows, ProgramConfig(**runner_budget)) - raw = json.dumps({'program': [{'tool': 'INTERPRET_DOMAIN', 'arguments': {}}] * length}) - if length <= 10: - assert len(parse_program(raw, controller.bridge.catalog, {'domain': '金融'}, - runner_budget['max_program_steps']).steps) == length - else: - with pytest.raises(ValueError, match='Program length exceeds max_program_steps'): - parse_program(raw, controller.bridge.catalog, {'domain': '金融'}, runner_budget['max_program_steps']) - - -def test_raw_rejections_independent_budgets_and_normal_nontermination(tmp_path): - smoke = module('local_smoke') - output = tmp_path / 'run' - assert smoke.main(['--model', str(tmp_path), '--output', str(output)], backend_factory=BoundaryBackend) == 0 - summary = read(output / 'summary.json') - assert summary['status'] == 'completed' and summary['terminated_count'] == 0 - assert summary['accepted_plans'] == 0 and summary['planner_attempts'] == 12 - for name in ['local-balance', 'local-phone', 'local-invoice']: - trace = read(output / 'samples' / (name + '.json')) - assert trace['budget'] == {'programs': 0, 'planner_attempts': 4, 'skill_steps': 0} - assert all(a['raw_response'] == '```json\n{"program": []}\n```' for a in trace['planner_attempts']) - assert (output / 'environment.json').is_file() - - -def test_existing_root_refused_before_backend_init(tmp_path): - smoke = module('local_smoke') - output = tmp_path / 'run' - output.mkdir() - def forbidden(*a): - pytest.fail('backend initialized for existing output') - assert smoke.main(['--model', str(tmp_path), '--output', str(output)], backend_factory=forbidden) == 2 - assert list(output.iterdir()) == [] - - -def test_initialization_failure_is_durable(tmp_path): - smoke = module('local_smoke') - def broken(*a): - raise RuntimeError('checkpoint unavailable') - output = tmp_path / 'run' - assert smoke.main(['--model', str(tmp_path), '--output', str(output)], backend_factory=broken) == 2 - summary = read(output / 'summary.json') - assert summary['status'] == 'initialization_failure' and 'checkpoint unavailable' in summary['error'] - assert (output / 'environment.json').is_file() - - -def test_backend_faults_not_hidden_by_core_retry(tmp_path): - smoke = module('local_smoke') - class Broken(BoundaryBackend): - def __call__(self, messages): - raise RuntimeError('generation failed') - output = tmp_path / 'run' - assert smoke.main(['--model', str(tmp_path), '--output', str(output)], backend_factory=Broken) == 2 - summary = read(output / 'summary.json') - assert summary['status'] == 'backend_failure' and len(summary['backend_errors']) == 12 - assert len(list((output / 'samples').glob('*.json'))) == 3 - - -def test_accepted_incomplete_program_is_ordinary_result(tmp_path): - smoke = module('local_smoke') - class Incomplete(BoundaryBackend): - def __call__(self, messages): - if 'Global Program Planner' in messages[0]['content']: - return json.dumps({'program': [{'tool': 'INTERPRET_DOMAIN', 'arguments': {}}]}) - return json.dumps({'summary': '合成解释', 'data': {'domain_semantics': '金融业务'}}) - output = tmp_path / 'run' - assert smoke.main(['--model', str(tmp_path), '--output', str(output)], backend_factory=Incomplete) == 0 - summary = read(output / 'summary.json') - assert summary['status'] == 'completed' and summary['accepted_plans'] == 9 and summary['terminated_count'] == 0 - trace = read(output / 'samples' / 'local-balance.json') - assert trace['programs'][0]['steps'][0]['status'] == 'success' - assert trace['stop_reason'] == 'program_budget_exhausted' - assert trace['state']['domain_semantics'] == '金融业务' - - -def test_downloader_pins_identity_before_snapshot_and_hashes(tmp_path): - download = module('download_model') - model = tmp_path / 'model' - files = {'config.json': b'{"model_type":"qwen3_5"}', 'tokenizer.json': b'{}', 'model.safetensors': b'tensor'} - class Api: - def model_info(self, repo_id, **kw): - assert repo_id == 'Qwen/Qwen3.5-9B' and kw == {'files_metadata': True, 'token': False} - return SimpleNamespace(sha='a' * 40, siblings=[SimpleNamespace(rfilename=n, size=len(b)) for n, b in files.items()] + [SimpleNamespace(rfilename='modeling_remote.py', size=3)]) - def snapshot(**kw): - identity = read(model / 'download-identity.json') - assert kw['revision'] == identity['revision'] == 'a' * 40 - assert kw['token'] is False and kw['repo_id'] == 'Qwen/Qwen3.5-9B' - assert set(kw['allow_patterns']) == set(files) - for n, b in files.items(): - (model / n).write_bytes(b) - manifest = download.download_model(model, api=Api(), snapshot=snapshot) - assert manifest['revision'] == 'a' * 40 and len(manifest['files']) == 3 - assert all(e['sha256'] == hashlib.sha256(files[e['path']]).hexdigest() for e in manifest['files']) - with pytest.raises(FileExistsError): - download.download_model(model, api=Api(), snapshot=snapshot) - - -def test_interrupted_download_resumes_pinned_revision(tmp_path): - download = module('download_model') - model = tmp_path / 'model' - class Api: - def model_info(self, *a, **k): - return SimpleNamespace(sha='b' * 40, siblings=[SimpleNamespace(rfilename=n, size=2) for n in ('config.json', 'tokenizer.json', 'model.safetensors')]) - def interrupted(**kw): - raise RuntimeError('interrupted') - with pytest.raises(RuntimeError, match='interrupted'): - download.download_model(model, api=Api(), snapshot=interrupted) - assert (model / 'download-identity.json').is_file() - class NoResolve: - def model_info(self, *a, **k): - pytest.fail('resume must not resolve a fresh revision') - def resumed(**kw): - assert kw['revision'] == 'b' * 40 - for name in kw['allow_patterns']: - (model / name).write_bytes(b'{}') - assert download.download_model(model, api=NoResolve(), snapshot=resumed)['revision'] == 'b' * 40 - - -def test_download_identity_tamper_and_size_mismatch_rejected(tmp_path): - download = module('download_model') - model = tmp_path / 'model' - model.mkdir() - (model / 'download-identity.json').write_text(json.dumps({'repo_id': 'evil/repo', 'revision': 'a' * 40, 'files': []}), encoding='utf-8') - with pytest.raises(ValueError, match='identity'): - download.download_model(model, api=object(), snapshot=lambda **k: None) - - -@pytest.mark.parametrize('mode', ['raw', 'context', 'generation_error']) -def test_cuda_backend_records_raw_devices_budget_and_offline_options(tmp_path, monkeypatch, mode): - smoke = module('local_smoke') - import sys - import torch - from types import ModuleType - tf = ModuleType('transformers') - config = SimpleNamespace(model_type='qwen3_5', eos_token_id=9, pad_token_id=0) - class Tensor: - shape = (1, 32257 if mode == 'context' else 12) - device = torch.device('cuda:0') - def to(self, device): - assert device == 'cuda:0' - return self - class Output: - def __getitem__(self, key): - assert key == (0, slice(12, None)) - return [2] * 512 - class Tokenizer: - eos_token_id = 9 - pad_token_id = 0 - def apply_chat_template(self, messages, **kw): - assert kw['enable_thinking'] is False - return 'prompt' - def __call__(self, prompt, **kw): - assert kw['truncation'] is False - return {'input_ids': Tensor(), 'attention_mask': Tensor()} - def decode(self, ids, **kw): - assert kw == {'skip_special_tokens': True, 'clean_up_tokenization_spaces': False} - return ' ```json\n{bad json}\n``` ' - class Model: - generation_config = config - def parameters(self): - return iter([SimpleNamespace(device=Tensor.device, dtype=torch.float16, is_floating_point=lambda: True)]) - def eval(self): - return self - def generate(self, **kw): - if mode == 'generation_error': - raise RuntimeError('test generation failure') - assert kw['do_sample'] is False and kw['max_new_tokens'] == 512 and kw['max_time'] == 90.0 - assert kw['eos_token_id'] == 9 - return Output() - def config_load(path, **kw): - assert kw == smoke.OFFLINE - return config - def tokenizer_load(path, **kw): - assert kw == smoke.OFFLINE - return Tokenizer() - def model_load(path, **kw): - assert kw['local_files_only'] is True and kw['trust_remote_code'] is False - assert kw['device_map'] == {'': 'cuda:0'} and kw['dtype'] == torch.float16 - assert kw['attn_implementation'] == 'sdpa' - return Model() - tf.AutoConfig = SimpleNamespace(from_pretrained=config_load) - tf.AutoTokenizer = SimpleNamespace(from_pretrained=tokenizer_load) - tf.AutoModelForImageTextToText = SimpleNamespace(from_pretrained=model_load) - monkeypatch.setitem(sys.modules, 'transformers', tf) - monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) - monkeypatch.setattr(torch.cuda, 'set_device', lambda x: None) - monkeypatch.setattr(torch.cuda, 'manual_seed_all', lambda x: None) - monkeypatch.setattr(torch.cuda, 'mem_get_info', lambda x: (10**10, 12 * 10**9)) - monkeypatch.setattr(torch.cuda, 'get_device_name', lambda x: 'CPU-test-only CUDA device replacement') - monkeypatch.setattr(torch.cuda, 'synchronize', lambda x: None) - monkeypatch.setattr(torch.cuda, 'reset_peak_memory_stats', lambda x: None) - for name in ('memory_allocated', 'memory_reserved', 'max_memory_allocated'): - monkeypatch.setattr(torch.cuda, name, lambda x: 100) - monkeypatch.setattr(smoke, 'verify_model', lambda path: {'revision': 'a' * 40}) - backend = smoke.Backend(tmp_path, tmp_path / 'calls') - if mode != 'raw': - with pytest.raises((ValueError, RuntimeError)): - backend.generate([{'role': 'user', 'content': 'unaltered'}]) - result = read(tmp_path / 'calls' / 'call-0001' / 'result.json') - assert result['input_tokens'] == (32257 if mode == 'context' else 12) - assert result['error'] and result['raw_text'] is None and len(backend.failures) == 1 - assert read(tmp_path / 'calls' / 'call-0001' / 'request.json')['messages'][0]['content'] == 'unaltered' - return - raw = backend.generate([{'role': 'user', 'content': 'unaltered'}]) - assert raw == ' ```json\n{bad json}\n``` ' - result = read(tmp_path / 'calls' / 'call-0001' / 'result.json') - assert result['raw_text'] == raw and result['output_tokens'] == 512 and result['input_tokens'] == 12 - assert result['truncation_at_budget'] is True and result['input_devices'] == ['cuda:0'] - assert result['parameter_devices'] == ['cuda:0'] and result['error'] is None - - -@pytest.mark.parametrize('failed_metric', ['memory_allocated', 'memory_reserved', 'max_memory_allocated']) -def test_cuda_telemetry_failure_retains_context_error_and_result(tmp_path, failed_metric): - smoke = module('local_smoke') - class Tokenizer: - def apply_chat_template(self, messages, **kw): - return 'whole prompt' - def __call__(self, prompt, **kw): - return {'input_ids': SimpleNamespace(shape=(1, 32257))} - def unavailable(device): - raise RuntimeError('telemetry unavailable') - metrics = ('memory_allocated', 'memory_reserved', 'max_memory_allocated') - cuda = SimpleNamespace(**{name: unavailable if name == failed_metric else lambda device: 100 for name in metrics}) - # Replace only external tokenizer/CUDA I/O; execute real encode/generate/finalization. - backend = smoke.Backend.__new__(smoke.Backend) - backend.call_dir = tmp_path / 'calls' - backend.call_dir.mkdir() - backend.calls, backend.failures = [], [] - backend.parameter_devices, backend.parameter_dtypes = ['cuda:0'], ['torch.float16'] - backend.attention, backend.options = 'sdpa', {'max_new_tokens': 512} - backend.tokenizer, backend.torch = Tokenizer(), SimpleNamespace(cuda=cuda) - messages = [{'role': 'user', 'content': 'unaltered'}] - with pytest.raises(smoke.ContextBudgetExceeded, match='32257'): - backend.generate(messages) - call = backend.call_dir / 'call-0001' - assert read(call / 'request.json')['messages'] == messages - result = read(call / 'result.json') - assert result['input_tokens'] == 32257 and result['raw_text'] is None - assert result['error'].startswith('ContextBudgetExceeded: context budget exceeded: 32257') - assert result['telemetry_errors'] == {failed_metric: 'RuntimeError: telemetry unavailable'} - assert result['memory'] == {name: None if name == failed_metric else 100 for name in metrics} - assert backend.failures == [{'call': str(call), 'error': result['error']}] - - -def test_model_verification_detects_modified_file(tmp_path): - download = module('download_model') - model = tmp_path / 'model' - class Api: - def model_info(self, *a, **k): - return SimpleNamespace(sha='c' * 40, siblings=[SimpleNamespace(rfilename=n, size=2) for n in ('config.json', 'tokenizer.json', 'model.safetensors')]) - def snapshot(**kw): - for n in kw['allow_patterns']: - (model / n).write_bytes(b'{}') - download.download_model(model, api=Api(), snapshot=snapshot) - assert download.verify_model(model)['revision'] == 'c' * 40 - (model / 'model.safetensors').write_bytes(b'XX') - with pytest.raises(ValueError, match='hash'): - download.verify_model(model) - - -def test_official_unusual_shard_name_and_trusted_lfs_hash(tmp_path): - download = module('download_model') - model = tmp_path / 'model' - weight = 'model.safetensors-00001-of-00001.safetensors' - payload = b'{}' - digest = hashlib.sha256(payload).hexdigest() - class Api: - def model_info(self, *a, **k): - return SimpleNamespace(sha='d' * 40, siblings=[SimpleNamespace(rfilename=n, size=2, lfs=SimpleNamespace(sha256=digest)) for n in ('config.json', 'tokenizer.json', weight)]) - def snapshot(**kw): - assert weight in kw['allow_patterns'] - for n in kw['allow_patterns']: - (model / n).write_bytes(payload) - result = download.download_model(model, api=Api(), snapshot=snapshot) - assert all(e['expected_sha256'] == digest for e in result['files']) - assert all(e['sha256'] == e['expected_sha256'] for e in result['files']) - - -def test_trusted_lfs_hash_mismatch_retains_identity_without_manifest(tmp_path): - download = module('download_model') - model = tmp_path / 'model' - class Api: - def model_info(self, *a, **k): - return SimpleNamespace(sha='d' * 40, siblings=[SimpleNamespace(rfilename=n, size=2, lfs=SimpleNamespace(sha256='0' * 64)) for n in ('config.json', 'tokenizer.json', 'model.safetensors')]) - def snapshot(**kw): - for n in kw['allow_patterns']: - (model / n).write_bytes(b'{}') - with pytest.raises(ValueError, match='hash'): - download.download_model(model, api=Api(), snapshot=snapshot) - assert (model / 'download-identity.json').is_file() and not (model / 'model-manifest.json').exists() - - -def test_unlisted_executable_prevents_completed_manifest(tmp_path): - download = module('download_model') - model = tmp_path / 'model' - class Api: - def model_info(self, *a, **k): - return SimpleNamespace(sha='e' * 40, siblings=[SimpleNamespace(rfilename=n, size=2) for n in ('config.json', 'tokenizer.json', 'model.safetensors')]) - def snapshot(**kw): - for n in kw['allow_patterns']: - (model / n).write_bytes(b'{}') - (model / 'remote_code.py').write_bytes(b'{}') - with pytest.raises(ValueError, match='inventory'): - download.download_model(model, api=Api(), snapshot=snapshot) - assert not (model / 'model-manifest.json').exists() - diff --git a/research/finance_program_v1/nontraining/tests/test_planning_contracts.py b/research/finance_program_v1/nontraining/tests/test_planning_contracts.py deleted file mode 100644 index 747eb7c..0000000 --- a/research/finance_program_v1/nontraining/tests/test_planning_contracts.py +++ /dev/null @@ -1,212 +0,0 @@ -"""Planning documentation plus real parsing/binding/guards; only model I/O is scripted.""" -import importlib -import json - -import pytest - -from test_program_loop import FULL, REGISTRY, ROWS, Script, api, program, run - - -@pytest.fixture -def controller(): - module = api() - return module.build_program_controller(Script([]), REGISTRY, ROWS) - - -def test_library_documents_canonical_paths_and_distinct_dependencies(controller): - by_name = {item["name"]: item for item in controller.library} - assert len(by_name) == 14 - name_inputs = by_name["INTERPRET_FIELD_NAME"]["planning"]["inputs"] - assert by_name["INTERPRET_FIELD_NAME"]["planning"]["argument_template"] == {} - assert name_inputs["field_name"]["canonical_reference"] == "$metadata.field_name" - assert name_inputs["field_name"]["source"] == "initial_binding" - assert name_inputs["field_name"]["possible_producers"] == [] - assert name_inputs["field_abbreviation_semantics"]["required"] is False - assert name_inputs["field_abbreviation_semantics"]["possible_producers"] == ["EXPAND_FIELD_ABBREVIATION"] - disambiguate_inputs = by_name["DISAMBIGUATE_FIELD_SEMANTICS"]["planning"]["inputs"] - assert disambiguate_inputs["field_semantics"]["required"] is True - assert disambiguate_inputs["field_semantics"]["possible_producers"] == ["INTERPRET_FIELD_NAME"] - top5_inputs = by_name["SELECT_CATEGORY_TOPK"]["planning"]["inputs"] - assert top5_inputs["semantic_query"]["canonical_reference"] == "$state.semantic_query" - compare_inputs = by_name["COMPARE_STANDARD_CANDIDATES"]["planning"]["inputs"] - assert compare_inputs["semantic_evidence"]["canonical_reference"] == "$state.semantic_evidence" - assert "GET_FIELD_METADATA" in top5_inputs["semantic_query"]["possible_producers"] - assert "GET_FIELD_METADATA" not in compare_inputs["semantic_evidence"]["possible_producers"] - infer_inputs = by_name["INFER_CATEGORY_FROM_TOPK"]["planning"]["inputs"] - assert infer_inputs["candidate_standard_categories"]["canonical_reference"] == "$state.standard_candidates" - assert infer_inputs["candidate_standard_categories"]["possible_producers"] == ["SELECT_CATEGORY_TOPK"] - final_inputs = by_name["FINALIZE_CLASSIFICATION"]["planning"]["inputs"] - validation = importlib.import_module("program_loop.validation") - assert final_inputs["final_evidence_state"]["requires_all"] == sorted(validation.FINAL_EVIDENCE_REQUIREMENTS) - assert final_inputs["final_evidence_state"]["possible_producers"] == [] - json.dumps(controller.library, allow_nan=False) - - -def test_planning_interface_is_shared_and_preserves_original_library_contracts(controller): - planning = importlib.import_module("program_loop.planning_contracts") - validation = importlib.import_module("program_loop.validation") - from pool_catalog import purpose - from program_loop.catalog_context import skill_library - - catalog = controller.bridge.catalog - for item in controller.library: - spec = catalog[item["name"]] - assert item["planning"] == planning.planning_contract(spec, catalog) - assert {key: item[key] for key in item if key != "planning"} == { - "name": spec.name, "purpose": purpose(spec.name), "role": spec.role, - "required_inputs": list(spec.required_inputs), "optional_inputs": list(spec.optional_inputs), - "produces": list(spec.produces), "terminal": spec.terminal, - "contract": controller.bridge.loader.load(spec.name).body, - } - assert set(item["planning"]["inputs"]) == set((*spec.required_inputs, *spec.optional_inputs)) - assert item["planning"]["conditional_outputs"] == sorted(validation.possible_outputs(spec)) - for key, details in item["planning"]["inputs"].items(): - assert details["required"] == (key in spec.required_inputs) - assert details["requires_all"] == (sorted(validation.FINAL_EVIDENCE_REQUIREMENTS) if key == "final_evidence_state" else []) - assert skill_library(catalog, controller.bridge.loader) == controller.library - - -def test_shared_helpers_keep_aliases_conditional_outputs_and_invalidation(controller): - validation = importlib.import_module("program_loop.validation") - reference = validation.canonical_reference - assert reference("current_record", set()) == "$record" - assert reference("domain", set()) == "$domain" - assert reference("target_field", set()) == "$metadata.field_name" - assert reference("candidate_standard_categories", {"standard_candidates"}) == "$state.standard_candidates" - assert reference("candidate_standard_categories", set()) is None - assert reference("field_description", set()) is None - assert reference("field_description", {"field_description"}) == "$state.field_description" - catalog = controller.bridge.catalog - metadata = validation.possible_outputs(catalog["GET_FIELD_METADATA"]) - assert {"field_metadata", "field_description", "current_metadata", "semantic_query"} <= metadata - assert "semantic_evidence" not in metadata and "final_evidence_state" not in metadata - assert {"semantic_query", "semantic_evidence"} <= validation.possible_outputs(catalog["INTERPRET_FIELD_NAME"]) - prerequisites = set(validation.FINAL_EVIDENCE_REQUIREMENTS) - before = prerequisites | {"final_evidence_state", "final_result"} - after = validation.advance_available(catalog["INTERPRET_DOMAIN"], before) - assert before == prerequisites | {"final_evidence_state", "final_result"} # Pure: no caller mutation. - assert not ({"category", "grading_level", "aligned_standard_entry", "final_evidence_state", "final_result"} & after) - assert "standard_candidates" in after - after = validation.advance_available(catalog["SELECT_CATEGORY_TOPK"], before) - assert "standard_candidates" in after and "category" not in after and "grading_level" not in after - after = validation.advance_available(catalog["INFER_CATEGORY_FROM_TOPK"], before) - assert {"category", "aligned_category", "candidate_category", "category_candidate"} <= after - assert "grading_level" not in after and "final_evidence_state" not in after - for missing in prerequisites: - after = validation.advance_available(catalog["FINALIZE_CLASSIFICATION"], prerequisites - {missing}) - assert "final_evidence_state" not in after - assert "final_evidence_state" in validation.advance_available(catalog["FINALIZE_CLASSIFICATION"], prerequisites) - - -def test_guidance_visible_in_one_plan_real_executor_success_without_inserted_skills(): - controller, trace, script = run([program(*FULL)]) - payload = json.loads(script.messages[0][1]["content"]) - assert all(item["planning"]["argument_template"] == {} for item in payload["skill_library"]) - assert type(controller.bridge.executor).__name__ == "PoolExecutor" - assert type(controller.bridge.guard).__name__ == "PoolController" - assert trace.terminated and trace.final_result == {"category": "cat1", "grading_level": "L2"} - assert trace.budget == {"programs": 1, "planner_attempts": 1, "skill_steps": 5} - assert [step["call"]["tool"] for step in trace.programs[0]["steps"]] == list(FULL) - assert all(step["binding"]["version"] == "canonical-state-bindings-v1" for step in trace.programs[0]["steps"]) - assert payload["current"]["input"] == {"domain": "合成金融", "field_name": "balance"} - messages = json.dumps(script.messages, ensure_ascii=False) - for secret in ("PRIVATE-ROW-997", "SECRET-GOLD", "SECRET-GRADE", "PRELOADED-SECRET", "当前余额", "accounts"): - assert secret not in messages - - -def test_description_semantics_does_not_supply_name_semantics(controller): - from program_loop.validation import parse_program - raw = program("INTERPRET_FIELD_DESCRIPTION", "DISAMBIGUATE_FIELD_SEMANTICS") - with pytest.raises(ValueError, match="step 1: missing dependency field_semantics"): - parse_program(raw, controller.bridge.catalog, {"field_description": "observed"}, 12) - _, trace, _ = run([program("GET_FIELD_METADATA", "INTERPRET_FIELD_DESCRIPTION", "DISAMBIGUATE_FIELD_SEMANTICS")], max_planner_attempts=1) - assert trace.planner_attempts[0]["status"] == "rejected" - assert "missing dependency field_semantics" in trace.planner_attempts[0]["error"] - assert trace.budget["skill_steps"] == 0 - - -def test_absent_optional_null_is_rejected_and_raw_program_is_preserved(): - raw = program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_abbreviation_semantics": None}}) - _, trace, _ = run([raw], max_planner_attempts=1) - assert trace.planner_attempts[0]["status"] == "rejected" - assert trace.planner_attempts[0]["error"] == "step 0: missing dependency field_abbreviation_semantics" - assert trace.planner_attempts[0]["raw_response"] == raw - assert trace.budget == {"programs": 0, "planner_attempts": 1, "skill_steps": 0} - - -@pytest.mark.parametrize("prefix,tool,key,wrong,expected", [ - ((), "INTERPRET_FIELD_NAME", "field_name", "$state.field_name", "$metadata.field_name"), - (("INTERPRET_FIELD_NAME",), "SELECT_CATEGORY_TOPK", "semantic_query", "$state.semantic_evidence", "$state.semantic_query"), - (("INTERPRET_FIELD_NAME", "SELECT_CATEGORY_TOPK"), "COMPARE_STANDARD_CANDIDATES", "semantic_evidence", "$state.semantic_query", "$state.semantic_evidence"), -]) -def test_wrong_explicit_references_still_reject(prefix, tool, key, wrong, expected): - raw = program(*prefix, {"tool": tool, "arguments": {key: wrong}}) - _, trace, _ = run([raw], max_planner_attempts=1) - assert trace.planner_attempts[0]["status"] == "rejected" - assert trace.planner_attempts[0]["error"] == f"step {len(prefix)}: incorrect canonical reference for {key}; expected {expected}" - assert trace.planner_attempts[0]["raw_response"] == raw - assert trace.budget["skill_steps"] == 0 - - -def test_explicit_canonical_parameters_keep_real_binding(): - raw = program( - {"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_name": "$metadata.field_name"}}, - {"tool": "SELECT_CATEGORY_TOPK", "arguments": {"semantic_query": "$state.semantic_query"}}, - {"tool": "INFER_CATEGORY_FROM_TOPK", "arguments": {"candidate_standard_categories": "$state.standard_candidates"}}, - {"tool": "INFER_GRADING_LEVEL", "arguments": {"aligned_category": "$state.aligned_category"}}, - {"tool": "FINALIZE_CLASSIFICATION", "arguments": {"final_evidence_state": "$state.final_evidence_state"}}, - ) - _, trace, _ = run([raw]) - assert trace.terminated and trace.planner_attempts[0]["raw_response"] == raw - assert all(step["status"] == "success" for step in trace.programs[0]["steps"]) - - -def test_conditional_metadata_blocks_current_program_and_replans_independently(): - rows = [{"id": "PRIVATE-ROW-997", "domain": "合成金融", "metadata": {"field_name": "balance"}}] - raw = program("GET_FIELD_METADATA", "INTERPRET_FIELD_DESCRIPTION", "INTERPRET_DOMAIN") - _, trace, script = run([raw, program(*FULL)], rows=rows) - first = trace.programs[0] - assert first["status"] == "failed" and first["failure_index"] == 1 - assert [step["status"] for step in first["steps"]] == ["success", "blocked"] - assert [step["call"]["tool"] for step in first["steps"]] == ["GET_FIELD_METADATA", "INTERPRET_FIELD_DESCRIPTION"] - assert "field_description" not in trace.state - assert trace.terminated and trace.budget == {"programs": 2, "planner_attempts": 2, "skill_steps": 7} - assert [step["call"]["tool"] for step in trace.programs[1]["steps"]] == list(FULL) - assert script.kinds[:3] == ["planner", "planner", "INTERPRET_FIELD_NAME"] - feedback = json.loads(script.messages[1][1]["content"])["feedback"] - assert feedback["status"] == "failed" and feedback["failure_index"] == 1 - assert trace.planner_attempts[0]["raw_response"] == raw - - -def test_prompt_documents_omission_dependencies_and_conditional_execution(controller): - from program_loop.planner import SYSTEM - assert "Prefer arguments:{}" in SYSTEM - assert "binder supplies available required inputs" in SYSTEM - assert "omitted optional inputs are not automatically inserted" in SYSTEM - assert "omit" in SYSTEM and "null" in SYSTEM - assert "possible_producers" in SYSTEM and "requires_all" in SYSTEM - assert "semantic_query" in SYSTEM and "semantic_evidence" in SYSTEM - assert "field_description_semantics" in SYSTEM and "field_semantics" in SYSTEM - assert "conditional" in SYSTEM and "actual state" in SYSTEM - assert "No Skill name is mandatory" in SYSTEM and "inserts no steps" in SYSTEM - assert all(name not in SYSTEM for name in controller.bridge.catalog) - - -def test_real_binder_injects_required_but_not_omitted_available_optional(controller): - from agent.orchestration.agent_loop import PolicyDecision - from agent.orchestration.contracts import MetadataRecord, ToolCall - - record = MetadataRecord.from_mapping({"domain": "合成金融", "field_name": "balance"}) - state = {"field_abbreviation_semantics": "observed abbreviation interpretation"} - controller.bridge.availability.initialize(record, state) - spec = controller.bridge.catalog["INTERPRET_FIELD_NAME"] - omitted = controller.bridge.guard._normalize_policy_decision( - PolicyDecision(ToolCall(spec.name, {}), ""), record, state, spec) - assert omitted.call.arguments == {"field_name": "$metadata.field_name"} - explicit = controller.bridge.guard._normalize_policy_decision( - PolicyDecision(ToolCall(spec.name, {"field_abbreviation_semantics": "$state.field_abbreviation_semantics"}), ""), - record, state, spec) - assert explicit.call.arguments == { - "field_name": "$metadata.field_name", - "field_abbreviation_semantics": "$state.field_abbreviation_semantics", - } diff --git a/research/finance_program_v1/nontraining/tests/test_program_loop.py b/research/finance_program_v1/nontraining/tests/test_program_loop.py deleted file mode 100644 index 0c66c3d..0000000 --- a/research/finance_program_v1/nontraining/tests/test_program_loop.py +++ /dev/null @@ -1,376 +0,0 @@ -import importlib -import json -import subprocess -import sys - -import pytest - - -REGISTRY = {f"cat{i}": {"label": f"合成类别{i}", "description": f"无标签标准描述{i}", "grading_level": f"L{(i % 4) + 1}"} for i in range(1, 7)} -ROWS = [{"id": "PRIVATE-ROW-997", "domain": "合成金融", "metadata": {"field_name": "balance", "field_description": "当前余额", "table_name": "accounts"}, "gold_category": "SECRET-GOLD", "grading_level": "SECRET-GRADE"}] - - -def api(): - assert importlib.util.find_spec("program_loop") is not None, "Program orchestration package is not implemented" - return importlib.import_module("program_loop") - - -def program(*tools): - return json.dumps({"program": [{"tool": t, "arguments": {}} if isinstance(t, str) else t for t in tools]}) - - -FULL = ("INTERPRET_FIELD_NAME", "SELECT_CATEGORY_TOPK", "INFER_CATEGORY_FROM_TOPK", "INFER_GRADING_LEVEL", "FINALIZE_CLASSIFICATION") - - -class Script: - """Only model I/O is scripted; execution is the frozen production executor.""" - def __init__(self, plans, overrides=None): - self.plans = iter(plans) - self.messages = [] - self.kinds = [] - self.overrides = overrides or {} - - def __call__(self, messages): - self.messages.append(messages) - system = messages[0]["content"] - if "Global Program Planner" in system: - self.kinds.append("planner") - response = next(self.plans) - else: - name = system.split("selected Skill ")[1].split(".")[0] - self.kinds.append(name) - if name in self.overrides: - values = self.overrides[name] - response = values.pop(0) if isinstance(values, list) else values - elif name == "SELECT_CATEGORY_TOPK": - response = json.dumps({"option_ids": [f"C00{i}" for i in range(1, 6)], "summary": "合成排序"}) - elif name == "INFER_CATEGORY_FROM_TOPK": - response = json.dumps({"option_id": "C001", "summary": "合成选择"}) - else: - key = {"INTERPRET_FIELD_NAME": "field_semantics", "INTERPRET_DOMAIN": "domain_semantics", "INTERPRET_FIELD_DESCRIPTION": "field_description_semantics", "INTERPRET_TABLE_DESCRIPTION": "table_description_semantics"}[name] - response = json.dumps({"summary": "合成解释", "data": {key: "已观测的合成语义"}}) - if isinstance(response, Exception): - raise response - return response - - -def run(plans, *, rows=ROWS, overrides=None, **limits): - module = api() - generate = Script(plans, overrides) - controller = module.build_program_controller(generate, REGISTRY, rows, module.ProgramConfig(**limits)) - trace = controller.run({"domain": "合成金融", "field_name": "balance", "source_id": "PRIVATE-ROW-997", "gold_category": "SECRET-GOLD", "metadata": {"field_description": "PRELOADED-SECRET"}}) - return controller, trace, generate - - -def test_one_plan_executes_whole_program_with_real_guards(): - c, trace, generate = run([program(*FULL)]) - assert type(c.bridge.executor).__name__ == "PoolExecutor" - assert type(c.bridge.guard).__name__ == "PoolController" - assert trace.terminated and trace.final_result == {"category": "cat1", "grading_level": "L2"} - assert generate.kinds == ["planner", "INTERPRET_FIELD_NAME", "SELECT_CATEGORY_TOPK", "INFER_CATEGORY_FROM_TOPK"] - assert trace.budget["planner_attempts"] == 1 and trace.budget["skill_steps"] == 5 - assert all(s["status"] == "success" and s["binding"]["version"] == "canonical-state-bindings-v1" for s in trace.programs[0]["steps"]) - assert trace.state["_provenance"]["field_semantics"] == "INTERPRET_FIELD_NAME" - json.dumps(trace.to_dict()) - - -def test_full_catalog_and_only_public_initial_information(): - _, trace, generate = run([program("INTERPRET_DOMAIN")], max_programs=1) - payload = json.loads(generate.messages[0][1]["content"]) - assert len(payload["skill_library"]) == 14 - assert {"SELECT_CATEGORY_TOPK", "INFER_CATEGORY_FROM_TOPK"} <= {s["name"] for s in payload["skill_library"]} - assert all(s["purpose"] and s["contract"] and "required_inputs" in s and "terminal" in s for s in payload["skill_library"]) - assert payload["current"]["input"] == {"domain": "合成金融", "field_name": "balance"} - combined = json.dumps(generate.messages, ensure_ascii=False) - assert all(secret not in combined for secret in ("PRIVATE-ROW-997", "SECRET-GOLD", "SECRET-GRADE", "PRELOADED-SECRET")) - assert [s["call"]["tool"] for s in trace.programs[0]["steps"]] == ["INTERPRET_DOMAIN"] - assert not trace.terminated - - -def test_replan_only_after_program_end_reuses_state_and_feedback(): - _, trace, generate = run([program("INTERPRET_FIELD_NAME"), program(*FULL[1:])]) - assert trace.terminated and trace.budget["programs"] == 2 - assert generate.kinds[:3] == ["planner", "INTERPRET_FIELD_NAME", "planner"] - second = json.loads(generate.messages[2][1]["content"]) - assert second["feedback"]["status"] == "completed" - assert second["feedback"]["plan"]["program"][0]["tool"] == FULL[0] - assert second["current"]["named_state"]["field_semantics"] - assert second["feedback"]["remaining_budget"]["skill_steps"] == 19 - - -@pytest.mark.parametrize("raw", ["{}", "[]", "{\"program\":[]}", "```json\n{\"program\":[]}\n```", "{\"program\":[]} {}", "{\"program\":[],\"x\":1}", "{\"program\":[],\"program\":[]}", program("UNKNOWN"), program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"extra": 1}}), program({"tool": "INTERPRET_FIELD_NAME", "arguments": {}, "extra": 1}), program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_name": "$state.not_yet"}}), program("FINALIZE_CLASSIFICATION", "INTERPRET_DOMAIN"), program("INFER_GRADING_LEVEL"), program("INFER_CATEGORY_FROM_TOPK"), program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_name": "$domain"}})]) -def test_invalid_programs_spend_only_planner_attempt(raw): - _, trace, _ = run([raw], max_planner_attempts=1) - assert not trace.terminated and trace.budget["skill_steps"] == 0 and trace.budget["programs"] == 0 - assert trace.planner_attempts[0]["status"] == "rejected" and trace.planner_attempts[0]["raw_response"] == raw - - -def test_future_references_and_automatic_binding(): - _, trace, _ = run([program({"tool": "INTERPRET_FIELD_NAME", "arguments": {"field_name": "$metadata.field_name"}}, {"tool": "SELECT_CATEGORY_TOPK", "arguments": {"semantic_query": "$state.semantic_query"}}, *FULL[2:])]) - assert trace.terminated - - -def test_static_length_limit_is_independent(): - _, trace, _ = run([program(*FULL)], max_program_steps=4, max_planner_attempts=1) - assert trace.budget["skill_steps"] == 0 and "length" in trace.planner_attempts[0]["error"] - - -def test_total_skill_budget_does_not_reset_or_inject_finalizer(): - _, trace, _ = run([program("INTERPRET_FIELD_NAME"), program(*FULL[1:])], max_skill_steps=3) - assert trace.budget["skill_steps"] == 3 and trace.stop_reason == "skill_budget_exhausted" - assert not trace.terminated and "grading_level" not in trace.state - assert trace.programs[1]["status"] == "budget_exhausted" - - -def test_attempt_budget_survives_invalid_generation_and_generator_exception(): - _, trace, _ = run(["not JSON", RuntimeError("temporary model failure"), program("INTERPRET_DOMAIN")], max_planner_attempts=3) - assert trace.budget["planner_attempts"] == 3 and trace.budget["programs"] == 1 - assert [a["status"] for a in trace.planner_attempts] == ["rejected", "error", "accepted"] - assert trace.stop_reason == "planner_budget_exhausted" - - -def test_missing_metadata_remains_unknown_after_batch_and_fails_at_runtime(): - rows = [{"id": "PRIVATE-ROW-997", "domain": "合成金融", "metadata": {"field_name": "balance"}}] - _, trace, _ = run([program("GET_FIELD_METADATA", "INTERPRET_FIELD_DESCRIPTION"), program(*FULL)], rows=rows) - assert trace.terminated - assert trace.programs[0]["status"] == "failed" and trace.programs[0]["failure_index"] == 1 - assert trace.programs[0]["steps"][1]["status"] == "blocked" - assert not any(e["type"] == "field_description" for e in trace.state["availability_ledger"]) - assert "field_description" not in trace.state - - -def test_scoped_unavailable_blocks_repeat_but_errors_remain_retryable(): - module = api() - from pool_availability import initialize, observe, blocked, status - from agent.orchestration.contracts import MetadataRecord, ToolCall - from agent.orchestration.runtime import Observation - record = MetadataRecord.from_mapping({"domain": "合成金融", "field_name": "balance"}) - state = {}; initialize(record, state) - call = ToolCall("GET_FIELD_DESCRIPTION", {}) - observe(call, Observation(call.tool, "error", "temporary", {}), state) - assert status(state, "record", "balance", "field_description") == "error" and not blocked(call, state) - observe(call, Observation(call.tool, "unavailable", "missing", {}, {"source": "canonical-val", "missing": ["field_description"]}), state) - assert blocked(call, state) - # Bridge must use exactly this production availability module. - c = module.build_program_controller(Script([]), REGISTRY, ROWS) - assert c.bridge.availability is importlib.import_module("pool_availability") - - -def test_duplicate_acquisition_is_counted_and_ends_program(): - _, trace, _ = run([program("GET_FIELD_METADATA"), program("GET_FIELD_METADATA", "INTERPRET_DOMAIN")], max_programs=2) - assert trace.budget["skill_steps"] == 2 - assert trace.programs[1]["steps"][0]["status"] == "blocked" and len(trace.programs[1]["steps"]) == 1 - - -def test_semantic_error_ends_program_then_retries_without_losing_raw_response(): - _, trace, generate = run([program("INTERPRET_FIELD_NAME", "SELECT_CATEGORY_TOPK"), program(*FULL)], overrides={"INTERPRET_FIELD_NAME": ["{\"summary\":\"bad\",\"data\":{\"field_semantics\":{}}}", json.dumps({"summary": "retry", "data": {"field_semantics": "recovered"}})]}) - assert trace.terminated and trace.budget["skill_steps"] == 6 - assert generate.kinds[:4] == ["planner", "INTERPRET_FIELD_NAME", "planner", "INTERPRET_FIELD_NAME"] - assert trace.programs[0]["steps"][0]["metadata"]["raw_response"] - - -def test_outside_actual_topk_selection_fails_real_executor_and_is_retained(): - bad = json.dumps({"option_id": "C006", "summary": "outside"}) - _, trace, _ = run([program(*FULL)], max_programs=1, overrides={"INFER_CATEGORY_FROM_TOPK": [bad, bad]}) - step = trace.programs[0]["steps"][-1] - assert step["status"] == "error" and step["call"]["tool"] == "INFER_CATEGORY_FROM_TOPK" - assert len(step["metadata"]["attempts"]) == 2 and not trace.terminated - - -@pytest.mark.parametrize("tool,argument,value", [("INTERPRET_FIELD_DESCRIPTION", "field_description", "invented raw"), ("INFER_CATEGORY_FROM_TOPK", "candidate_standard_categories", [{"category": "cat6"}]), ("INFER_GRADING_LEVEL", "aligned_category", "cat6"), ("FINALIZE_CLASSIFICATION", "final_evidence_state", {"category": "cat1", "grading_level": "L4"})]) -def test_literal_forgery_never_overrides_actual_state(tool, argument, value): - setup = ["GET_FIELD_METADATA", *FULL[:-1]] - _, trace, _ = run([program(*setup, {"tool": tool, "arguments": {argument: value}})], max_programs=1, max_planner_attempts=1) - assert not trace.terminated - assert trace.planner_attempts[0]["status"] == "rejected" - assert argument in trace.planner_attempts[0]["error"] - assert trace.budget == {"programs": 0, "planner_attempts": 1, "skill_steps": 0} - - -@pytest.mark.parametrize("changed_tool", ["SELECT_CATEGORY_TOPK", "INTERPRET_DOMAIN", "GET_FIELD_METADATA"]) -def test_changed_evidence_or_candidates_invalidates_old_selection_and_grade(changed_tool): - plans = [program(*FULL[:-1]), program(changed_tool), program("FINALIZE_CLASSIFICATION")] - overrides = {"SELECT_CATEGORY_TOPK": [json.dumps({"option_ids": [f"C00{i}" for i in range(1, 6)], "summary": "first"}), json.dumps({"option_ids": [f"C00{i}" for i in range(2, 7)], "summary": "new"})]} - _, trace, _ = run(plans, overrides=overrides, max_planner_attempts=3) - assert not trace.terminated and "category" not in trace.state and "grading_level" not in trace.state and "final_evidence_state" not in trace.state - assert trace.planner_attempts[-1]["status"] == "rejected" - assert trace.programs[1]["invalidations"] - - -def test_model_error_does_not_publish_or_reuse_unverified_evidence(): - _, trace, _ = run([program("INTERPRET_DOMAIN"), program("INTERPRET_DOMAIN")], max_programs=2, overrides={"INTERPRET_DOMAIN": [RuntimeError("transient"), json.dumps({"summary": "ok", "data": {"domain_semantics": "valid"}})]}) - assert trace.programs[0]["steps"][0]["status"] == "error" - assert trace.programs[1]["steps"][0]["status"] == "success" - - -def test_trace_export_refuses_overwrite(tmp_path): - _, trace, _ = run([program(*FULL)]) - target = tmp_path / "trace.json" - trace.write_json(target) - original = target.read_bytes() - with pytest.raises(FileExistsError): trace.write_json(target) - assert target.read_bytes() == original - - -def test_cli_help_demo_and_missing_local_model(tmp_path): - api() - help_result = subprocess.run([sys.executable, "-m", "program_loop", "--help"], capture_output=True, text=True) - assert help_result.returncode == 0 and "--output" in help_result.stdout - target = tmp_path / "demo.json" - demo = subprocess.run([sys.executable, "-m", "program_loop", "--output", str(target)], capture_output=True, text=True) - assert demo.returncode == 0 and "scripted" in demo.stdout - payload = json.loads(target.read_text(encoding="utf-8")) - assert payload["terminated"] and payload["execution_mode"] == "scripted model I/O + real executor" - repeated = subprocess.run([sys.executable, "-m", "program_loop", "--output", str(target)], capture_output=True, text=True) - assert repeated.returncode != 0 - missing = subprocess.run([sys.executable, "-m", "program_loop", "--local-model", str(tmp_path / "missing")], capture_output=True, text=True) - assert missing.returncode != 0 and "local model path" in missing.stderr - - -def test_default_import_does_not_import_torch(): - api() - result = subprocess.run([sys.executable, "-c", "import program_loop,sys; assert 'torch' not in sys.modules; assert 'transformers' not in sys.modules"], capture_output=True, text=True) - assert result.returncode == 0, result.stderr - - -def test_publication_failure_is_transactional_and_retains_model_response(monkeypatch): - api() - import program_loop.execution as bridge_module - - def failed_publication(record, state, data, skill): - state["injected_unverified"] = "must not escape" - raise RuntimeError("publication interrupted") - - monkeypatch.setattr(bridge_module, "publish_state", failed_publication) - _, trace, _ = run([program("INTERPRET_DOMAIN")], max_programs=1) - step = trace.programs[0]["steps"][0] - assert step["status"] == "error" and step["data"] == {} - assert "domain_semantics" not in trace.state and "injected_unverified" not in trace.state - assert step["metadata"]["raw_response"] - assert "publication interrupted" in step["summary"] - - -@pytest.mark.parametrize("response", [b"not text", float("nan")]) -def test_nontext_planner_response_is_rejected_with_serializable_diagnostic(response): - _, trace, _ = run([response], max_planner_attempts=1) - assert trace.planner_attempts[0]["status"] == "rejected" - assert trace.budget == {"programs": 0, "planner_attempts": 1, "skill_steps": 0} - json.dumps(trace.to_dict(), allow_nan=False) - - -def test_real_source_missing_and_lookup_error_have_distinct_retry_semantics(): - _, missing, _ = run([program("GET_FIELD_METADATA", "INTERPRET_DOMAIN"), program("GET_FIELD_METADATA")], rows=[], max_programs=2) - assert [p["steps"][0]["status"] for p in missing.programs] == ["error", "error"] - assert missing.state["availability_ledger"][-1]["status"] == "error" - assert "field_metadata" not in missing.state - rows = [{"id": "PRIVATE-ROW-997", "domain": "合成金融", "metadata": {"field_name": "balance"}}] - _, absent, _ = run([program("GET_FIELD_METADATA", "INTERPRET_FIELD_DESCRIPTION"), program("GET_FIELD_METADATA")], rows=rows, max_programs=2) - assert absent.programs[0]["steps"][0]["status"] == "success" - assert absent.programs[0]["steps"][1]["status"] == "blocked" - assert absent.programs[1]["steps"][0]["status"] == "blocked" - assert absent.budget["skill_steps"] == 3 - assert not any(e["status"] == "unavailable" for e in absent.state["availability_ledger"]) - - -def test_fresh_evidence_can_reselect_and_finalize_in_next_program(): - _, trace, _ = run([program(*FULL[:-1]), program("INTERPRET_DOMAIN"), program(*FULL[1:])]) - assert trace.terminated and trace.budget["programs"] == 3 - assert {"category", "grading_level", "final_evidence_state"} <= set(trace.programs[1]["invalidations"]) - assert trace.programs[2]["steps"][0]["lineage"]["evidence"] == 2 - - -def test_static_future_reference_rejects_stale_grade_after_evidence_step(): - _, trace, _ = run([program(*FULL[:-1]), program("INTERPRET_DOMAIN", "FINALIZE_CLASSIFICATION")], max_planner_attempts=2) - assert trace.planner_attempts[-1]["status"] == "rejected" - assert trace.budget["skill_steps"] == 4 - assert "category" in trace.state # Static rejection leaves prior verified evidence intact. - - -def test_no_name_interpretation_step_is_required_for_legal_terminal(): - _, trace, generate = run([program("GET_FIELD_METADATA", *FULL[1:])]) - assert trace.terminated and "INTERPRET_FIELD_NAME" not in generate.kinds - assert "field_semantics" not in trace.state - - -def test_private_identity_and_labels_stay_out_of_acquisition_replanning_messages(): - _, trace, generate = run([program("GET_FIELD_METADATA"), program(*FULL[1:])]) - assert trace.terminated - combined = json.dumps(generate.messages, ensure_ascii=False) - assert "当前余额" in combined - assert all(secret not in combined for secret in ("PRIVATE-ROW-997", "SECRET-GOLD", "SECRET-GRADE", "PRELOADED-SECRET")) - - -def test_real_terminal_guard_is_used_and_rejection_does_not_publish(monkeypatch): - module = api() - script = Script([program(*FULL)]) - controller = module.build_program_controller(script, REGISTRY, ROWS, module.ProgramConfig(max_programs=1)) - original = controller.bridge.guard._valid_terminal - checked = [] - - def reject_after_real_validation(result, state): - checked.append(original(result, state)) - return False - - monkeypatch.setattr(controller.bridge.guard, "_valid_terminal", reject_after_real_validation) - trace = controller.run({"domain": "合成金融", "field_name": "balance", "source_id": "PRIVATE-ROW-997"}) - assert checked == [True] - assert not trace.terminated and "final_result" not in trace.state - assert trace.programs[0]["steps"][-1]["status"] == "error" - - -def test_nontext_skill_response_is_retained_without_breaking_feedback(): - _, trace, generate = run([program("INTERPRET_DOMAIN"), program(*FULL)], overrides={"INTERPRET_DOMAIN": b"invalid model output"}) - assert trace.terminated - assert trace.programs[0]["steps"][0]["status"] == "error" - assert "invalid model output" in json.dumps(trace.to_dict(), allow_nan=False) - assert generate.kinds[:3] == ["planner", "INTERPRET_DOMAIN", "planner"] - - -def test_raw_metadata_acquisition_does_not_statically_claim_semantic_evidence(): - _, trace, _ = run([program("GET_FIELD_METADATA", "SELECT_CATEGORY_TOPK", "COMPARE_STANDARD_CANDIDATES")], max_planner_attempts=1) - assert trace.planner_attempts[0]["status"] == "rejected" - assert "semantic_evidence" in trace.planner_attempts[0]["error"] - assert trace.budget["skill_steps"] == 0 - - -def comparison_raw(entry, text="候选比较依据为已观测语义"): - return json.dumps({"summary": "比较完成", "data": {"standard_comparison": text, "aligned_standard_entry": entry}}, ensure_ascii=False) - - -@pytest.mark.parametrize("full", [False, True]) -def test_comparison_binds_authoritative_entry_and_continues_to_finalize(full): - entry = {"category": "cat1", **REGISTRY["cat1"]} - if not full: - entry.pop("grading_level") - raw = comparison_raw(entry) - _, trace, generate = run([program(*FULL[:2], "COMPARE_STANDARD_CANDIDATES", *FULL[2:])], - overrides={"COMPARE_STANDARD_CANDIDATES": raw}, max_programs=1) - assert trace.terminated, trace.to_dict() - step = trace.programs[0]["steps"][2] - assert step["metadata"]["raw_response"] == raw - assert trace.state["aligned_standard_entry"] == {"category": "cat1", **REGISTRY["cat1"]} - messages = next(m for m in generate.messages if "selected Skill COMPARE_STANDARD_CANDIDATES." in m[0]["content"]) - payload = json.loads(messages[1]["content"]) - assert "non-empty string" in payload["output_schema"]["data"]["standard_comparison"] - assert "grading_level" not in json.dumps(messages, ensure_ascii=False) - - -@pytest.mark.parametrize("change", ["list", "empty", "outside", "label", "description", "grade", "extra", "partial", "conflict"]) -def test_comparison_rejects_invalid_text_or_candidate_without_publication(change): - entry = {"category": "cat1", "label": REGISTRY["cat1"]["label"], "description": REGISTRY["cat1"]["description"]} - text = "比较依据" - if change == "list": text = ["比较依据"] - elif change == "empty": text = " " - elif change == "outside": entry = {"category": "cat6", **REGISTRY["cat6"]} - elif change in ("label", "description"): entry[change] = "forged" - elif change == "grade": entry["grading_level"] = "L999" - elif change == "extra": entry["extra"] = "forged" - elif change == "partial": entry.pop("description") - elif change == "conflict": entry = {"category": "cat2", **REGISTRY["cat2"]} - raw = comparison_raw(entry, text) - tools = (*FULL[:3], "COMPARE_STANDARD_CANDIDATES") if change == "conflict" else (*FULL[:2], "COMPARE_STANDARD_CANDIDATES") - _, trace, _ = run([program(*tools)], overrides={"COMPARE_STANDARD_CANDIDATES": raw}, max_programs=1) - step = trace.programs[0]["steps"][-1] - assert step["status"] == "error" - assert step["metadata"]["raw_response"] == raw - assert "standard_comparison" not in trace.state and not trace.terminated diff --git a/research/finance_program_v1/nontraining/tests/test_recovery_context.py b/research/finance_program_v1/nontraining/tests/test_recovery_context.py deleted file mode 100644 index 3636507..0000000 --- a/research/finance_program_v1/nontraining/tests/test_recovery_context.py +++ /dev/null @@ -1,97 +0,0 @@ -import importlib -import json -from copy import deepcopy - -from test_program_loop import FULL, program, run - - -def context(state, budget, feedback): - module = importlib.import_module('program_loop.planner') - assert hasattr(module, 'recovery_context'), 'factual recovery context is missing' - return module.recovery_context(state, budget, feedback) - - -def planner_payloads(script): - return [json.loads(m[1]['content']) for m in script.messages if 'Global Program Planner' in m[0]['content']] - - -def test_pure_context_preserves_inputs_and_summarizes_only_execution_facts(): - state = {'category': 'stale-looking', 'final_evidence_state': {}, 'availability_ledger': [ - {'scope': 'record', 'target': 'PRIVATE-ID', 'type': 'field_description', 'status': 'error', 'source': 'PRIVATE-ID'}]} - budget = {'programs': 1, 'planner_attempts': 2, 'skill_steps': 8, 'program_steps': 10} - feedback = {'status': 'failed', 'failure_index': 1, 'terminated': False, - 'plan': {'program': [{'tool': t, 'arguments': {'private': 'PRIVATE-ID'}} for t in FULL]}, - 'steps': [{'step_index': 0, 'call': {'tool': FULL[0]}, 'status': 'success'}, - {'step_index': 1, 'call': {'tool': FULL[1]}, 'status': 'error'}], - 'invalidations': ['grading_level', 'final_evidence_state']} - original = deepcopy((state, budget, feedback)) - result = context(state, budget, feedback) - assert (state, budget, feedback) == original - assert result['previous_program']['successful_steps'] == [{'step_index': 0, 'tool': FULL[0]}] - assert result['previous_program']['failed_steps'] == [{'step_index': 1, 'tool': FULL[1], 'status': 'error'}] - assert result['previous_program']['unexecuted_tail'] == [{'step_index': i, 'tool': FULL[i]} for i in range(2, 5)] - assert result['classification_completed'] is False - assert result['remaining_budget'] == budget and result['invalidations'] == feedback['invalidations'] - assert result['availability_observations'][0]['status'] == 'error' - assert 'PRIVATE-ID' not in json.dumps(result, allow_nan=False) - result['remaining_budget']['programs'] = 99 - assert budget['programs'] == 1 - - -def test_rejected_or_error_attempt_has_no_invented_program(): - for status in ('planner_rejected', 'planner_error'): - result = context({'category': 'cat1', 'grading_level': 'L2'}, {'programs': 1}, {'status': status, 'error': 'bad'}) - assert result['previous_program'] is None and not result['classification_completed'] - - -def test_failure_recovers_actual_state_to_terminal_without_mid_program_planner(): - bad = json.dumps({'option_id': 'C006', 'summary': 'outside'}) - _, trace, script = run([program(*FULL), program(*FULL[2:])], - overrides={'INFER_CATEGORY_FROM_TOPK': [bad, bad, json.dumps({'option_id': 'C001', 'summary': 'recovered'})]}, max_programs=2) - payloads = planner_payloads(script) - assert 'recovery_context' in payloads[1], 'outer planner needs factual recovery context' - recovery = payloads[1]['recovery_context'] - assert recovery['previous_program']['status'] == 'failed' - assert recovery['previous_program']['failure_index'] == 2 - assert recovery['previous_program']['unexecuted_tail'] == [{'step_index': 3, 'tool': FULL[3]}, {'step_index': 4, 'tool': FULL[4]}] - assert recovery['remaining_budget']['programs'] == 1 and not recovery['classification_completed'] - assert payloads[1]['feedback'] == trace.programs[0] - assert trace.terminated and trace.budget['skill_steps'] == 6 - assert script.kinds.count('planner') == 2 - assert script.kinds[:5] == ['planner', FULL[0], FULL[1], FULL[2], FULL[2]] - assert all(x not in json.dumps(script.messages) for x in ('PRIVATE-ROW-997', 'SECRET-GOLD', 'SECRET-GRADE')) - - -def test_one_recovery_step_still_exhausts_program_budget_and_retains_failure(): - bad = json.dumps({'option_id': 'C006', 'summary': 'outside'}) - _, trace, script = run([program(*FULL), program(FULL[2])], - overrides={'INFER_CATEGORY_FROM_TOPK': [bad, bad, json.dumps({'option_id': 'C001', 'summary': 'recovered'})]}, max_programs=2) - assert 'recovery_context' in planner_payloads(script)[1] - assert not trace.terminated and trace.stop_reason == 'program_budget_exhausted' - assert len(trace.programs) == 2 and trace.programs[0]['status'] == 'failed' - assert trace.budget['programs'] == 2 and trace.budget['skill_steps'] == 4 - - -def test_real_invalidation_and_source_error_remain_facts_without_readiness_claims(): - _, trace, script = run([program(*FULL[:-1]), program('INTERPRET_DOMAIN'), program(*FULL[1:])]) - assert 'recovery_context' in planner_payloads(script)[2] - result = planner_payloads(script)[2]['recovery_context'] - assert {'category', 'grading_level', 'final_evidence_state'} <= set(result['invalidations']) - assert 'category' not in result['observed_state_keys'] and not result['classification_completed'] - assert trace.terminated - _, missing, script = run([program('GET_FIELD_METADATA'), program('INTERPRET_DOMAIN')], rows=[], max_programs=2) - result = planner_payloads(script)[1]['recovery_context'] - assert any(x['status'] == 'error' for x in result['availability_observations']) - assert not any(x['status'] == 'unavailable' for x in result['availability_observations']) - assert missing.programs[0]['status'] == 'failed' - - -def test_availability_distinguishes_canonical_unavailable_obtained_and_unqueried(): - result = context({'availability_ledger': [ - {'scope': 'record', 'type': 'field_description', 'status': 'unavailable'}, - {'scope': 'record', 'type': 'field_name', 'status': 'obtained'}]}, {'programs': 1}, None) - assert result['availability_observations'] == [ - {'scope': 'record', 'type': 'field_description', 'status': 'unavailable'}, - {'scope': 'record', 'type': 'field_name', 'status': 'obtained'}] - assert 'unqueried' in result['availability_rule'] - assert result['previous_program'] is None diff --git a/research/finance_program_v1/nontraining/tests/test_rejection_context.py b/research/finance_program_v1/nontraining/tests/test_rejection_context.py deleted file mode 100644 index 3bf7cca..0000000 --- a/research/finance_program_v1/nontraining/tests/test_rejection_context.py +++ /dev/null @@ -1,92 +0,0 @@ -import json -import pytest -from test_program_loop import FULL, program, run - -NINE = ('GET_FIELD_METADATA','INTERPRET_FIELD_DESCRIPTION','INTERPRET_FIELD_NAME', - 'DISAMBIGUATE_FIELD_SEMANTICS','SELECT_CATEGORY_TOPK','COMPARE_STANDARD_CANDIDATES', - 'INFER_CATEGORY_FROM_TOPK','INFER_GRADING_LEVEL','FINALIZE_CLASSIFICATION') - -def payload(trace, index): - return json.loads(trace.planner_attempts[index]['messages'][1]['content']) - -def test_nine_step_rejection_is_factual_and_next_whole_program_can_terminate(): - raw = program(*NINE) - _, trace, script = run([raw, program(*FULL)], max_program_steps=8, - max_programs=3, max_skill_steps=12, max_planner_attempts=4) - first, second = payload(trace, 0), payload(trace, 1) - assert trace.planner_attempts[0]['status'] == 'rejected' - assert trace.planner_attempts[0]['raw_response'] == raw - assert second['feedback']['rejected_program'] == { - 'executed': False,'trusted': False,'step_count': 9,'max_program_steps': 8, - 'tool_sequence': list(NINE)} - assert second['feedback']['error'] == 'Program length exceeds max_program_steps' - assert second['feedback']['remaining_budget'] == { - 'programs':3,'planner_attempts':3,'skill_steps':12,'program_steps':8} - assert second['current'] == first['current'] - assert second['recovery_context']['previous_program'] is None - assert not second['recovery_context']['classification_completed'] - assert trace.terminated and trace.stop_reason == 'validated_terminal' - assert trace.budget == {'programs':1,'planner_attempts':2,'skill_steps':5} - assert len(trace.programs) == 1 - assert [s['call']['tool'] for s in trace.programs[0]['steps']] == list(FULL) - assert script.kinds[:2] == ['planner','planner'] - -def test_rejected_parameters_are_not_rebroadcast_or_published(): - raw = program({'tool':'INTERPRET_FIELD_NAME','arguments':{'field_name':'$state.PRIVATE-FAKE'}}, - *NINE[1:]) - _, trace, _ = run([raw, program(*FULL)], max_program_steps=8) - second = payload(trace, 1) - assert second['feedback']['rejected_program']['tool_sequence'] == ['INTERPRET_FIELD_NAME',*NINE[1:]] - assert 'PRIVATE-FAKE' not in json.dumps(second) - assert 'PRIVATE-FAKE' in trace.planner_attempts[0]['raw_response'] - assert 'PRIVATE-FAKE' not in json.dumps(trace.state) - assert trace.terminated - -@pytest.mark.parametrize('raw', [ - 'not JSON','{}','[]','{"program":[]}', - '{"program":[],"program":[]}', - '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":{"x":NaN}}]}', - '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":{"x":Infinity}}]}', - '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":{"x":1e999}}]}', - '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":{"x":-1e999}}]}', - '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":{"x":[{"v":1e999}]}}]}', - '{"program":[{"tool":"INTERPRET_DOMAIN","tool":"INTERPRET_FIELD_NAME","arguments":{}}]}', - program('PRIVATE-UNKNOWN'), - '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":[]}]}', - '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":{},"extra":1}]}', - b'not text',None]) -def test_unreadable_or_unrecognized_plan_has_no_invented_summary(raw): - _, trace, _ = run([raw, program(*FULL)], max_planner_attempts=2) - second = payload(trace, 1) - assert second['feedback']['status'] == 'planner_rejected' - assert 'rejected_program' not in second['feedback'] - assert second['recovery_context']['previous_program'] is None - assert trace.terminated and trace.budget['programs'] == 1 - -def test_finite_exponent_is_still_summarized_as_unexecuted_intent(): - raw = '{"program":[{"tool":"INTERPRET_DOMAIN","arguments":{"x":1e3}}]}' - _, trace, _ = run([raw, program(*FULL)], max_planner_attempts=2, max_program_steps=8) - second = payload(trace, 1) - assert second['feedback']['rejected_program'] == { - 'executed':False,'trusted':False,'step_count':1,'max_program_steps':8, - 'tool_sequence':['INTERPRET_DOMAIN']} - assert second['feedback']['error'] == 'step 0: unknown arguments' - assert trace.terminated and trace.budget['programs'] == 1 - -def test_backend_error_does_not_reuse_last_rejected_program(): - _, trace, _ = run([program(*NINE), RuntimeError('temporary backend failure'), program(*FULL)], - max_program_steps=8,max_planner_attempts=3) - assert 'rejected_program' in payload(trace, 1)['feedback'] - assert payload(trace, 2)['feedback'] == {'status':'planner_error', - 'error':'temporary backend failure','remaining_budget':{ - 'programs':4,'planner_attempts':1,'skill_steps':20,'program_steps':8}} - assert payload(trace, 2)['recovery_context']['previous_program'] is None - assert trace.terminated - -def test_repeated_invalid_plan_never_executes_or_manufactures_termination(): - _, trace, _ = run([program(*NINE)]*4,max_program_steps=8, - max_programs=3,max_skill_steps=12,max_planner_attempts=4) - assert trace.budget == {'programs':0,'planner_attempts':4,'skill_steps':0} - assert trace.programs == [] and not trace.terminated and trace.final_result is None - assert trace.stop_reason == 'planner_budget_exhausted' - assert all(payload(trace, i)['current'] == payload(trace, 0)['current'] for i in range(4)) diff --git a/research/finance_program_v1/nontraining/tests/test_source_integrity.py b/research/finance_program_v1/nontraining/tests/test_source_integrity.py deleted file mode 100644 index faab8a2..0000000 --- a/research/finance_program_v1/nontraining/tests/test_source_integrity.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Behavior tests for the independent source-snapshot audit.""" -from __future__ import annotations - -import hashlib -import importlib.util -import json -from pathlib import Path - -import pytest - - -def audit_function(): - path = Path(__file__).resolve().parents[1] / 'tools' / 'verify_source.py' - assert path.is_file(), 'source-integrity implementation is not present yet' - spec = importlib.util.spec_from_file_location('source_integrity_tool', path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module.verify_manifest - - -def fixture_manifest(tmp_path): - vendor = tmp_path / 'vendor' - vendor.mkdir() - original = tmp_path / 'original' - original.mkdir() - payload = b'print("original")\n' - (vendor / 'core.py').write_bytes(payload) - (original / 'core.py').write_bytes(payload) - entry = {'path': 'core.py', 'bytes': len(payload), 'sha256': hashlib.sha256(payload).hexdigest()} - manifest = tmp_path / 'source.json' - manifest.write_text(json.dumps({'schema': 1, 'source': str(original), 'files': 1, 'entries': [entry]}), encoding='utf-8') - return manifest, vendor, original - - -def test_exact_snapshot_and_original_pass(tmp_path): - manifest, vendor, _ = fixture_manifest(tmp_path) - result = audit_function()(manifest, vendor, verify_original=True) - assert result['verified'] is True - assert result['files'] == 1 - assert result['original_verified'] is True - - -def test_tampered_snapshot_is_rejected(tmp_path): - manifest, vendor, _ = fixture_manifest(tmp_path) - (vendor / 'core.py').write_bytes(b'changed') - with pytest.raises(ValueError, match='core.py'): - audit_function()(manifest, vendor) - - -def test_extra_source_file_is_rejected(tmp_path): - manifest, vendor, _ = fixture_manifest(tmp_path) - (vendor / 'extra.py').write_bytes(b'new') - with pytest.raises(ValueError, match='inventory'): - audit_function()(manifest, vendor) - - -def test_original_tampering_is_independently_rejected(tmp_path): - manifest, vendor, original = fixture_manifest(tmp_path) - (original / 'core.py').write_bytes(b'changed') - with pytest.raises(ValueError, match='original'): - audit_function()(manifest, vendor, verify_original=True) - - -def test_manifest_parent_traversal_is_rejected(tmp_path): - manifest, vendor, _ = fixture_manifest(tmp_path) - data = json.loads(manifest.read_text(encoding='utf-8')) - data['entries'][0]['path'] = '../core.py' - manifest.write_text(json.dumps(data), encoding='utf-8') - with pytest.raises(ValueError, match='path'): - audit_function()(manifest, vendor) diff --git a/research/finance_program_v1/nontraining/tests/test_task_level_prompt.py b/research/finance_program_v1/nontraining/tests/test_task_level_prompt.py deleted file mode 100644 index 52bf4e4..0000000 --- a/research/finance_program_v1/nontraining/tests/test_task_level_prompt.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Prompt contract and CPU boundaries; scripted I/O is not model efficacy evidence.""" -import json - -import pytest - -from test_program_loop import FULL, program, run - - -OBJECTIVE = "Plan the complete remaining classification task using verified evidence and frozen Registry grading, through legal terminal execution." -INSTRUCTIONS = ( - "Plan the complete remaining classification task in one ordered Program, not just the next Skill.", - "Choose the Skills and their order yourself from the complete P14 library.", - "Plan all dependencies through a successful terminal; selecting candidates alone does not finish classification.", - "You need not see a future output now: use its documented canonical reference after its producer; execution will bind the actual verified output.", - "Conditional outputs may be missing or execution may fail; the Program then stops and its factual observation returns to you at the outer boundary.", - "The parser accepts partial Programs, but that is a permissive syntax boundary, not the planning objective.", -) -PAYLOAD_KEYS = {"task", "current", "skill_library", "remaining_budget", "feedback", "recovery_context", "availability_rule"} - - -def planner_payloads(script): - payloads = [] - for messages in script.messages: - if "Global Program Planner" not in messages[0]["content"]: - continue - assert [message["role"] for message in messages] == ["system", "user"] - assert all(set(message) == {"role", "content"} for message in messages) - system = messages[0]["content"] - assert all(instruction in system for instruction in INSTRUCTIONS) - assert "No Skill name is mandatory and the controller inserts no steps." in system - assert "Programs may be incomplete." not in system - assert '{"program":[{"tool":"SKILL_NAME","arguments":{}}]}' not in system - payload = json.loads(messages[1]["content"]) - assert set(payload) == PAYLOAD_KEYS - assert payload["task"] == OBJECTIVE - assert len(payload["skill_library"]) == 14 - payloads.append(payload) - combined = json.dumps(script.messages, ensure_ascii=False) - assert all(secret not in combined for secret in ("PRIVATE-ROW-997", "SECRET-GOLD", "SECRET-GRADE", "PRELOADED-SECRET")) - return payloads - - -def test_planner_requests_complete_remaining_task_instead_of_one_next_action(): - _, _, script = run([program("INTERPRET_DOMAIN")], max_programs=1, max_planner_attempts=4) - payload = planner_payloads(script)[0] - assert payload["current"]["input"] == {"domain": "合成金融", "field_name": "balance"} - assert payload["feedback"] is None - assert payload["recovery_context"]["previous_program"] is None - assert not payload["recovery_context"]["classification_completed"] - assert payload["remaining_budget"] == {"programs": 1, "planner_attempts": 4, "skill_steps": 20, "program_steps": 10} - - -def test_legal_partial_program_is_not_rejected_or_completed_by_controller(): - _, trace, _ = run([program("INTERPRET_DOMAIN")], max_programs=1) - assert trace.planner_attempts[0]["status"] == "accepted" - assert trace.budget == {"programs": 1, "planner_attempts": 1, "skill_steps": 1} - assert not trace.terminated and trace.final_result is None - assert trace.stop_reason == "program_budget_exhausted" - assert [step["call"]["tool"] for step in trace.programs[0]["steps"]] == ["INTERPRET_DOMAIN"] - - -def test_complete_program_still_uses_real_terminal_guard(): - controller, trace, script = run([program(*FULL)]) - assert type(controller.bridge.guard).__name__ == "PoolController" - assert trace.terminated and trace.stop_reason == "validated_terminal" - assert trace.final_result == {"category": "cat1", "grading_level": "L2"} - assert trace.programs[0]["steps"][-1]["status"] == "success" - assert trace.budget == {"programs": 1, "planner_attempts": 1, "skill_steps": 5} - assert script.kinds.count("planner") == 1 - assert len(planner_payloads(script)) == 1 - - -@pytest.mark.parametrize("first,status,remaining,used", [ - (program("INTERPRET_FIELD_NAME"), "completed", {"programs": 1, "planner_attempts": 1, "skill_steps": 11, "program_steps": 8}, {"programs": 2, "planner_attempts": 2, "skill_steps": 2}), - (program("GET_FIELD_METADATA", "INTERPRET_FIELD_DESCRIPTION", "INTERPRET_DOMAIN"), "failed", {"programs": 1, "planner_attempts": 1, "skill_steps": 10, "program_steps": 8}, {"programs": 2, "planner_attempts": 2, "skill_steps": 3}), - ("not JSON", "planner_rejected", {"programs": 2, "planner_attempts": 1, "skill_steps": 12, "program_steps": 8}, {"programs": 1, "planner_attempts": 2, "skill_steps": 1}), -]) -def test_task_objective_preserves_outer_facts_and_budget(first, status, remaining, used): - rows = [{"id": "PRIVATE-ROW-997", "domain": "合成金融", "metadata": {"field_name": "balance"}}] - _, trace, script = run([first, program("INTERPRET_DOMAIN")], rows=rows, - max_programs=2, max_planner_attempts=2, max_skill_steps=12, max_program_steps=8) - payloads = planner_payloads(script) - assert len(payloads) == 2 and script.kinds.count("planner") == 2 - second = payloads[1] - assert second["feedback"]["status"] == status - assert second["feedback"]["remaining_budget"] == remaining - assert second["remaining_budget"] == second["recovery_context"]["remaining_budget"] == remaining - assert not second["recovery_context"]["classification_completed"] - assert trace.budget == used and not trace.terminated and trace.final_result is None - if status == "planner_rejected": - assert second["recovery_context"]["previous_program"] is None - assert trace.planner_attempts[0]["raw_response"] == first - assert second["feedback"]["error"] == trace.planner_attempts[0]["error"] - else: - assert second["feedback"] == trace.programs[0] - previous = second["recovery_context"]["previous_program"] - assert previous["status"] == status - if status == "completed": - assert second["current"]["named_state"]["field_semantics"] - assert previous["successful_steps"] == [{"step_index": 0, "tool": "INTERPRET_FIELD_NAME"}] - assert previous["unexecuted_tail"] == [] - else: - assert previous["failure_index"] == 1 - assert previous["failed_steps"] == [{"step_index": 1, "tool": "INTERPRET_FIELD_DESCRIPTION", "status": "blocked"}] - assert previous["unexecuted_tail"] == [{"step_index": 2, "tool": "INTERPRET_DOMAIN"}] - assert "field_description" not in second["current"]["named_state"] - - -def test_hard_budget_prompt_keeps_nine_step_raw_program_rejected_at_eight_step_gate(): - raw = program("INTERPRET_DOMAIN", "GET_FIELD_METADATA", "INTERPRET_FIELD_DESCRIPTION", - "INTERPRET_TABLE_DESCRIPTION", "INTERPRET_FIELD_NAME", *FULL[1:]) - assert len(json.loads(raw)["program"]) == 9 - _, trace, script = run([raw], max_programs=3, max_program_steps=8, max_skill_steps=12, max_planner_attempts=1) - payload = planner_payloads(script)[0] - assert payload["remaining_budget"] == {"programs": 3, "planner_attempts": 1, "skill_steps": 12, "program_steps": 8} - assert trace.budget == {"programs": 0, "planner_attempts": 1, "skill_steps": 0} - assert trace.programs == [] and script.kinds == ["planner"] - assert len(trace.planner_attempts) == 1 - assert trace.planner_attempts[0]["status"] == "rejected" - assert trace.planner_attempts[0]["raw_response"] == raw - assert "length" in trace.planner_attempts[0]["error"] - assert not trace.terminated and trace.final_result is None - assert trace.stop_reason == "planner_budget_exhausted" - instructions = ( - "Each Program must fit remaining_budget.program_steps and remaining_budget.skill_steps; these are hard upper bounds, not suggested plan lengths.", - "Use a sufficient dependency path for the remaining task; complete classification does not require using every Skill or every possible evidence source.", - "Before returning JSON, count the planned steps and omit nonessential operations if it exceeds either bound, without omitting required dependencies or inventing evidence.", - ) - system = script.messages[0][0]["content"] - assert INSTRUCTIONS[-1] + "\n" + "\n".join(instructions) + "\n" in system - - -def test_dependency_alternatives_prompt_preserves_five_step_terminal_and_requires_all_boundary(): - limits = {"max_programs": 3, "max_program_steps": 8, "max_skill_steps": 12, "max_planner_attempts": 4} - controller, trace, script = run([program(*FULL)], **limits) - assert type(controller.bridge.executor).__name__ == "PoolExecutor" - assert type(controller.bridge.guard).__name__ == "PoolController" - assert trace.terminated and trace.stop_reason == "validated_terminal" - assert trace.final_result == {"category": "cat1", "grading_level": "L2"} - assert trace.budget == {"programs": 1, "planner_attempts": 1, "skill_steps": 5} - assert script.kinds.count("planner") == 1 - assert len(trace.programs) == 1 and len(trace.programs[0]["steps"]) == 5 - assert tuple(step["call"]["tool"] for step in trace.programs[0]["steps"]) == FULL - assert all(step["status"] == "success" for step in trace.programs[0]["steps"]) - payload = planner_payloads(script)[0] - assert payload["remaining_budget"] == {"programs": 3, "planner_attempts": 4, "skill_steps": 12, "program_steps": 8} - - incomplete = tuple(tool for tool in FULL if tool != "INFER_GRADING_LEVEL") - raw = program(*incomplete) - assert len(json.loads(raw)["program"]) == 4 - _, rejected, rejected_script = run([raw], **{**limits, "max_planner_attempts": 1}) - assert rejected.budget == {"programs": 0, "planner_attempts": 1, "skill_steps": 0} - assert rejected.programs == [] and rejected_script.kinds == ["planner"] - assert len(rejected.planner_attempts) == 1 - assert rejected.planner_attempts[0]["status"] == "rejected" - assert rejected.planner_attempts[0]["raw_response"] == raw - assert "final_evidence_state" in rejected.planner_attempts[0]["error"] - assert not rejected.terminated and rejected.final_result is None - assert rejected.stop_reason == "planner_budget_exhausted" - assert planner_payloads(rejected_script)[0]["remaining_budget"] == {"programs": 3, "planner_attempts": 1, "skill_steps": 12, "program_steps": 8} - - instructions = ( - "Each possible_producers list contains alternative ways to supply that input, not a sequence that must all be executed; choose a sufficient dependency path and still verify its conditional outputs at execution.", - "all_available_evidence means the verified evidence actually accumulated by the chosen Skills, not every possible evidence source; only a nonempty requires_all list requires every named prerequisite.", - ) - anchor = "Before returning JSON, count the planned steps and omit nonessential operations if it exceeds either bound, without omitting required dependencies or inventing evidence." - for generated in (script, rejected_script): - system = generated.messages[0][0]["content"] - assert anchor + "\n" + "\n".join(instructions) + "\n" in system diff --git a/research/finance_program_v1/nontraining/tools/check_local_gpu.py b/research/finance_program_v1/nontraining/tools/check_local_gpu.py deleted file mode 100644 index ccbf06f..0000000 --- a/research/finance_program_v1/nontraining/tools/check_local_gpu.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Short local CUDA arithmetic check. NOT a Planner/LLM inference benchmark.""" -from __future__ import annotations - -import argparse -from datetime import datetime, timezone -import json -from pathlib import Path -import subprocess -import sys - - -def cuda_arithmetic(): - import torch - - if not torch.cuda.is_available(): - raise RuntimeError('PyTorch has no usable CUDA device') - torch.manual_seed(20261010) - torch.backends.cuda.matmul.allow_tf32 = False - left = torch.randn(256, 256, dtype=torch.float32) - right = torch.randn(256, 256, dtype=torch.float32) - cpu = left @ right - gpu = (left.to('cuda:0') @ right.to('cuda:0')).cpu() - torch.cuda.synchronize(0) - error = float((cpu - gpu).abs().max()) - torch.testing.assert_close(gpu, cpu, rtol=1e-4, atol=1e-4) - return {'torch': torch.__version__, 'torch_cuda': torch.version.cuda, - 'device': torch.cuda.get_device_name(0), 'device_count': torch.cuda.device_count(), - 'shape': [256, 256], 'dtype': 'float32', 'max_abs_error': error, - 'passed': True, 'test_kind': 'CUDA arithmetic, not LLM inference'} - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--output', type=Path, help='New report path; existing files are rejected') - parser.add_argument('--timeout', type=int, default=180) - parser.add_argument('--child', action='store_true', help=argparse.SUPPRESS) - args = parser.parse_args() - if args.child: - print(json.dumps(cuda_arithmetic())) - return 0 - if args.timeout < 1: - parser.error('--timeout must be positive') - if args.output is not None and args.output.exists(): - parser.error('output exists; use a new path') - report = {'utc': datetime.now(timezone.utc).isoformat(), 'python': sys.executable, - 'language_model_tested': False} - try: - child = subprocess.run([sys.executable, str(Path(__file__).resolve()), '--child'], - capture_output=True, text=True, timeout=args.timeout) - report.update({'child_exit': child.returncode, 'stderr': child.stderr}) - if child.returncode: - report.update({'passed': False, 'stdout': child.stdout}) - else: - report.update(json.loads(child.stdout)) - except (subprocess.TimeoutExpired, json.JSONDecodeError) as exc: - report.update({'passed': False, 'error': str(exc)}) - encoded = json.dumps(report, ensure_ascii=False, indent=2) + '\n' - if args.output is not None: - args.output.parent.mkdir(parents=True, exist_ok=True) - with args.output.open('x', encoding='utf-8') as stream: - stream.write(encoded) - print(encoded, end='') - return 0 if report.get('passed') else 1 - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/research/finance_program_v1/nontraining/tools/verify_source.py b/research/finance_program_v1/nontraining/tools/verify_source.py deleted file mode 100644 index b6d8016..0000000 --- a/research/finance_program_v1/nontraining/tools/verify_source.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Independent SHA/inventory audit of the reused, immutable executor snapshot.""" -from __future__ import annotations - -import argparse -import hashlib -import json -from pathlib import Path, PurePosixPath - - -SOURCE_EXTENSIONS = {'.py', '.md', '.json'} - - -def sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open('rb') as stream: - for block in iter(lambda: stream.read(1024 * 1024), b''): - digest.update(block) - return digest.hexdigest() - - -def verify_manifest(manifest_path, vendor_root, *, verify_original=False): - manifest = json.loads(Path(manifest_path).read_text(encoding='utf-8')) - root = Path(vendor_root).resolve() - expected = {} - for entry in manifest['entries']: - relative = entry['path'] - pure = PurePosixPath(relative) - if (not isinstance(relative, str) or not relative or '\\' in relative - or pure.is_absolute() or '..' in pure.parts or ':' in relative - or pure.as_posix() != relative or relative in expected): - raise ValueError(f'invalid manifest path: {relative!r}') - expected[relative] = entry - if manifest['files'] != len(expected): - raise ValueError('manifest inventory count mismatch') - actual = {p.relative_to(root).as_posix() for p in root.rglob('*') - if p.is_file() and p.suffix in SOURCE_EXTENSIONS} - if actual != set(expected): - raise ValueError(f'source inventory mismatch: missing={sorted(set(expected)-actual)}, extra={sorted(actual-set(expected))}') - for relative, entry in expected.items(): - path = root / relative - if not path.resolve().is_relative_to(root): - raise ValueError(f'source path escapes vendor: {relative}') - if path.stat().st_size != entry['bytes'] or sha256(path) != entry['sha256']: - raise ValueError(f'source SHA/size mismatch: {relative}') - if verify_original: - original = Path(manifest['source']) / relative - if not original.is_file() or sha256(original) != entry['sha256']: - raise ValueError(f'original source mismatch: {relative}') - return {'verified': True, 'files': len(expected), 'original_verified': verify_original} - - -def main(): - task_root = Path(__file__).resolve().parents[1] - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--manifest', type=Path, default=task_root / 'reviews/source-manifest.json') - parser.add_argument('--vendor', type=Path, default=task_root / 'vendor') - parser.add_argument('--verify-original', action='store_true') - args = parser.parse_args() - print(json.dumps(verify_manifest(args.manifest, args.vendor, verify_original=args.verify_original))) - - -if __name__ == '__main__': - main() diff --git a/research/finance_program_v1/nontraining/vendor/common.py b/research/finance_program_v1/nontraining/vendor/common.py deleted file mode 100644 index 16542c7..0000000 --- a/research/finance_program_v1/nontraining/vendor/common.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Pure helpers for an isolated, assistant-only semantic-Skill SFT pilot.""" -from __future__ import annotations - -import hashlib -import json -from pathlib import Path -import random - -SEED = 20261001 -SKILLS = ("SELECT_CATEGORY_TOPK", "INFER_CATEGORY_FROM_TOPK") -REVISION = "local-zip-003494285b21f01a5a6242cb45ae84394433fe72c41f447f64372720f78a2b20" - - -def sha256(path): - digest = hashlib.sha256() - with Path(path).open("rb") as stream: - for block in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(block) - return digest.hexdigest() - - -def read_json(path): - return json.loads(Path(path).read_text(encoding="utf-8")) - - -def read_jsonl(path): - return [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()] - - -def write_json(path, value): - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True) - temp = path.with_name(path.name + ".tmp") - temp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - temp.replace(path) - - -def fingerprint(value): - return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True).encode()).hexdigest() - - -def validate_completed_adapter(adapter): - adapter=Path(adapter) - completion=read_json(adapter.parent/'completion.json') - for file,key in [('adapter_model.safetensors','adapter_sha256'),('adapter_config.json','adapter_config_sha256')]: - if sha256(adapter/file)!=completion[key]: - raise ValueError(f'adapter {file} differs from completed training') - - -def validate_matched_baseline(base, adapted): - if base['model']['adapter_sha256'] is not None: - raise ValueError('control must use base weights without adapter') - excluded={'adapter_sha256','adapter_config_sha256','adapter_routing'} - if {k:v for k,v in base['model'].items() if k not in excluded} != {k:v for k,v in adapted['model'].items() if k not in excluded}: - raise ValueError('matched model/generation parameters differ') - if base['loop_config']!=adapted['loop_config']: - raise ValueError('matched loop configuration differs') - def behavior(manifest): - return {k:v['sha256'] for k,v in manifest['files'].items() if k not in {'adapter_weights','adapter_config'}} - if behavior(base)!=behavior(adapted): - raise ValueError('matched non-adapter behavior artifacts differ') - - -def selected_skill(messages): - """Route only trusted, exact Skill system headers, never user text.""" - if not messages or messages[0].get("role") != "system": - return None - system = messages[0].get("content", "") - return next((name for name in SKILLS if system.startswith(f"Execute only the selected Skill {name}.\n")), None) - - -def category_of(row): - levels = row["classification"] - return str(row["domain"]) + ":" + "/".join(levels[k] for k in ( - "category_root_level", "category_branch_level", "category_leaf_level" - )) - - -def auxiliary_candidates(gold, categories, source_id, seed=SEED): - """Four reproducible distractors, explicitly NOT a gold semantic ranking.""" - rng = random.Random(f"{seed}:{source_id}") - others = rng.sample(sorted(set(categories) - {gold}), 4) - presented = [gold, *others] - rng.shuffle(presented) - return others, presented - - -def assistant_encoding(tokenizer, row, max_length=3072): - """Mask prompts and weak candidate IDs; fail instead of truncating targets. - - Top-K has one true category only. IDs at positions 2..5 are scaffolding; - any token overlapping these character spans receives label -100. - """ - prompt = tokenizer.apply_chat_template(row["messages"], tokenize=False, - add_generation_prompt=True, enable_thinking=False) - response = row["response"] - if not tokenizer.eos_token: - raise ValueError("tokenizer requires an EOS token") - text = prompt + response + tokenizer.eos_token - encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True) - prefix = tokenizer(prompt, add_special_tokens=False)["input_ids"] - ids = encoded["input_ids"] - if ids[:len(prefix)] != prefix: - raise ValueError("generation prefix is not a token prefix of training sequence") - if len(ids) > max_length: - raise ValueError(f"{row['source_id']} exceeds max_length: {len(ids)} > {max_length}; no silent truncation") - spans = [(len(prompt) + a, len(prompt) + b) for a, b in row["weak_response_spans"]] - labels = [] - for index, (token, (a, b)) in enumerate(zip(ids, encoded["offset_mapping"])): - ignored = index < len(prefix) or any(a < end and b > start for start, end in spans) - labels.append(-100 if ignored else token) - if not any(label != -100 for label in labels): - raise ValueError("empty supervised completion") - return {"input_ids": ids, "attention_mask": [1] * len(ids), "labels": labels}, { - "length": len(ids), "prompt_tokens": len(prefix), - "supervised_tokens": sum(x != -100 for x in labels), - "weak_tokens_masked": sum(index >= len(prefix) and label == -100 for index, label in enumerate(labels)), - } diff --git a/research/finance_program_v1/nontraining/vendor/pool_availability.py b/research/finance_program_v1/nontraining/vendor/pool_availability.py deleted file mode 100644 index 74c15b8..0000000 --- a/research/finance_program_v1/nontraining/vendor/pool_availability.py +++ /dev/null @@ -1,115 +0,0 @@ -"""Record-local query evidence. Never accesses the private metadata lookup.""" -from copy import deepcopy -from pool_metadata import FIELDS, present - -RULE = ('observed-query-availability-v1: unknown permits acquisition; only canonical-val ' - 'query observations establish obtained or unavailable; errors remain retryable; ' - 'reuse obtained values; suppress repeat targets in the same record/object scope; ' - 'CHECK reports visibility and omitted batch fields stay unknown; missing_metadata_types ' - 'retains its acquired-visibility meaning; continue evidence and classification when sufficient.') -DIRECT = {'GET_FIELD_DESCRIPTION':'field_description', 'GET_TABLE_DESCRIPTION':'table_description', - 'GET_DATABASE_DESCRIPTION':'database_description'} -CONTEXT = {'GET_CONTEXT_FIELD_DESCRIPTIONS':('context_field_descriptions','field_description'), - 'GET_CONTEXT_FIELD_TYPES':('context_field_types','field_type'), - 'GET_CONTEXT_FIELD_VALUES':('context_field_values','value')} -BATCH = {'GET_FIELD_METADATA':'field_metadata', 'GET_TABLE_FIELDS':'table_fields', - 'GET_COMPLETE_TABLE_CONTEXT':'table_context', 'GET_COMPLETE_DATABASE_CONTEXT':'database_context', - 'EXPAND_SELECTED_CONTEXT':'context_fields'} - - -def initialize(record, state): - state.setdefault('availability_ledger', [{'scope':'record','target':record.field_name, - 'type':'field_name','status':'obtained','skill':'initial-input','source':'public-input', - 'value':record.field_name}]) - - -def status(state, scope, target, kind): - return next((e['status'] for e in state.get('availability_ledger',[]) - if (e['scope'],e['target'],e['type']) == (scope,target,kind)), 'unknown') - - -def target_name(state): - return next(e['value'] for e in state['availability_ledger'] - if e['scope']=='record' and e['type']=='field_name') - - -def targets(call, state): - name=call.tool; own=target_name(state) - if name in DIRECT: return [('record',own,DIRECT[name])] - if name=='ACQUIRE_MISSING_METADATA': return [('record',own,call.arguments.get('missing_metadata_type'))] - if name in BATCH: - # Expansion depends on the selected context object set, not a global tool flag. - target=own if name!='EXPAND_SELECTED_CONTEXT' else tuple(state.get('selected_context_fields',[])) - return [('query',list(target) if isinstance(target,tuple) else target,BATCH[name])] - if name in CONTEXT: - return [('context-field',f['field_name'],CONTEXT[name][1]) for f in state.get('context_fields',[])] - return [] - - -def blocked(call, state): - queried=targets(call,state) - return queried if queried and all(status(state,*t) in ('obtained','unavailable') for t in queried) else [] - - -def _put(state, scope, target, kind, outcome, skill, source, value=None): - entry={'scope':scope,'target':deepcopy(target),'type':kind,'status':outcome,'skill':skill,'source':source} - if outcome=='obtained': entry['value']=deepcopy(value) - ledger=state['availability_ledger'] - for i,old in enumerate(ledger): - if (old['scope'],old['target'],old['type'])==(scope,target,kind): - if old['status'] in ('obtained','unavailable') and outcome=='error': return - ledger[i]=entry;break - else: ledger.append(entry) - - -def observe(call, observation, state): - if call.tool=='CHECK_METADATA_AVAILABILITY': return - queried=targets(call,state) - if not queried: return - source=observation.metadata.get('source'); outcome=observation.status - if outcome=='error': - for t in queried: _put(state,*t,'error',call.tool,None) - return - if source!='canonical-val': return - own=target_name(state);data=observation.data - if call.tool in CONTEXT: - wrapper=data.get(CONTEXT[call.tool][0],{}) - available={f['field_name']:f[CONTEXT[call.tool][1]] for f in wrapper.get('fields',[]) - if present(f.get(CONTEXT[call.tool][1]))} - missing=wrapper.get('missing_fields',[]) if outcome=='success' else observation.metadata.get('missing_fields',[]) - for scope,target,kind in queried: - if outcome=='success' and target in available: _put(state,scope,target,kind,'obtained',call.tool,source,available[target]) - elif target in missing: _put(state,scope,target,kind,'unavailable',call.tool,source) - return - if outcome=='unavailable': - for t in queried: - if t[0]=='record' and t[2] in observation.metadata.get('missing',[]): - _put(state,*t,'unavailable',call.tool,source) - return - if outcome!='success': return - raw={} - for key in ('field_metadata','acquired_metadata'): - raw.update({k:v for k,v in data.get(key,{}).items() if k in FIELDS and present(v)}) - raw.update({k:v for k,v in data.items() if k in FIELDS and present(v)}) - if 'field_name' in raw and raw['field_name']!=own: raise ValueError('observed field_name differs from initial public input') - # JSON snapshots sort mapping keys; canonical ledger order must survive that - # round trip because the next Planner payload includes this ordered list. - for k,v in sorted(raw.items()): _put(state,'record',own,k,'obtained',call.tool,source,v) - if call.tool in BATCH: - for t in queried: _put(state,*t,'obtained',call.tool,source,data.get(BATCH[call.tool])) - if call.tool=='EXPAND_SELECTED_CONTEXT': - for field in data.get('context_fields',[]): - for key in FIELDS: - if present(field.get(key)): _put(state,'context-field',field['field_name'],key,'obtained',call.tool,source,field[key]) - - -def filter_callable(state, catalog): - result={} - from agent.orchestration.contracts import ToolCall - for name,spec in catalog.items(): - if name=='ACQUIRE_MISSING_METADATA': - if not any(not blocked(ToolCall(name,{'missing_metadata_type':key}),state) - for key in state.get('missing_metadata_types',[])): continue - elif blocked(ToolCall(name,{}),state): continue - result[name]=spec - return result diff --git a/research/finance_program_v1/nontraining/vendor/pool_bindings.py b/research/finance_program_v1/nontraining/vendor/pool_bindings.py deleted file mode 100644 index 18359c0..0000000 --- a/research/finance_program_v1/nontraining/vendor/pool_bindings.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Controller-owned argument transport; no semantic or execution decisions.""" -from copy import deepcopy - -from agent.orchestration.agent_loop import ActionError -from agent.orchestration.contracts import ToolCall -from agent.orchestration.validator import resolve_reference - -BINDING_RULE_VERSION = 'canonical-state-bindings-v1' -EVIDENCE_SCHEMA_VERSION = 'typed-observed-evidence-v2' - - -def strict_equal(left,right): - if type(left) is not type(right): - return False - if isinstance(right,dict): - return left.keys()==right.keys() and all(strict_equal(left[k],v) for k,v in right.items()) - if isinstance(right,(list,tuple)): - return len(left)==len(right) and all(strict_equal(a,b) for a,b in zip(left,right)) - return left==right - - -def bind_call(call,spec,record,state,binding_resolver): - """Fill required state parameters; validate explicit values before normalization.""" - allowed=set(spec.required_inputs)|set(spec.optional_inputs) - if call.tool!=spec.name or set(call.arguments)-allowed: - raise ActionError('binding contains unknown Skill or arguments') - normalized={}; changes=[] - for key in (*spec.required_inputs,*spec.optional_inputs): - supplied=key in call.arguments - if call.tool=='ACQUIRE_MISSING_METADATA' and key=='missing_metadata_type': - choice=call.arguments.get(key) - if not isinstance(choice,str) or choice not in state.get('missing_metadata_types',[]): - raise ActionError('missing_metadata_type choice must be an actual missing type') - normalized[key]=choice - continue - reference=binding_resolver(key,record,state) - if reference is None: - if supplied or key in spec.required_inputs: - raise ActionError(f'binding unavailable for {key}') - continue - found,value=resolve_reference(reference,record,state) - if not found: - raise ActionError(f'binding unresolved for {key}') - if supplied: - original=call.arguments[key] - if not (type(original) is str and original==reference) and not strict_equal(original,value): - raise ActionError(f'argument {key} differs from canonical binding {reference}') - normalized[key]=reference - if original!=reference: - changes.append({'argument':key,'kind':'literal_to_reference','from':deepcopy(original),'to':reference}) - elif key in spec.required_inputs: - normalized[key]=reference - changes.append({'argument':key,'kind':'injected','to':reference}) - canonical=ToolCall(call.tool,normalized) - return canonical,{'version':BINDING_RULE_VERSION,'raw_call':deepcopy(call.to_dict()), - 'normalized_call':deepcopy(canonical.to_dict()),'changes':changes} diff --git a/research/finance_program_v1/nontraining/vendor/pool_catalog.py b/research/finance_program_v1/nontraining/vendor/pool_catalog.py deleted file mode 100644 index 4fd6b2d..0000000 --- a/research/finance_program_v1/nontraining/vendor/pool_catalog.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Frozen P14/F66 interfaces and one-time separate contract installation.""" -from pathlib import Path -from dataclasses import replace -import json -from agent.orchestration.catalog import SkillSpec, default_catalog, dynamic_loop_catalog - -ROOT = Path(__file__).resolve().parent -REFERENCE = json.loads((ROOT/'skill_reference.json').read_text(encoding='utf-8')) -NAMES = json.loads((ROOT/'reference_skills_63.json').read_text(encoding='utf-8')) -SHARED = dynamic_loop_catalog(include_field_metadata=True, include_description_skills=True, two_stage=True) -SEARCH_NAMES = ('SEARCH_STANDARD','SEARCH_STANDARD_BY_FIELD','SEARCH_STANDARD_BY_CONTEXT','SEARCH_STANDARD_BY_TABLE','SEARCH_STANDARD_BY_DATABASE','RESEARCH_STANDARD') -OUTPUTS = { - 'GET_FIELD_DESCRIPTION':'field_description','GET_TABLE_DESCRIPTION':'table_description', - 'GET_DATABASE_DESCRIPTION':'database_description','GET_TABLE_FIELDS':'table_fields', - 'GET_CONTEXT_FIELD_DESCRIPTIONS':'context_field_descriptions','GET_CONTEXT_FIELD_TYPES':'context_field_types', - 'GET_CONTEXT_FIELD_VALUES':'context_field_values','SELECT_CONTEXT_FIELDS':'selected_context_fields', - 'EXPAND_SELECTED_CONTEXT':'context_fields','GET_COMPLETE_TABLE_CONTEXT':'table_context', - 'GET_COMPLETE_DATABASE_CONTEXT':'database_context','ACQUIRE_MISSING_METADATA':'acquired_metadata', - 'INTERPRET_FIELD_TYPE':'field_type_semantics','INTERPRET_FIELD_VALUE':'value_semantics', - 'EXPAND_TABLE_ABBREVIATION':'table_abbreviation_semantics','EXPAND_DATABASE_ABBREVIATION':'database_abbreviation_semantics', - 'INTERPRET_DATABASE_NAME':'database_semantics','INTERPRET_DATABASE_DESCRIPTION':'database_description_semantics', - 'REFINE_STANDARD_QUERY':'refined_semantic_query','SUMMARIZE_STANDARD_EVIDENCE':'standard_evidence_summary', - 'FUSE_FIELD_EVIDENCE':'field_evidence','FUSE_CONTEXT_EVIDENCE':'context_evidence', - 'FUSE_TABLE_EVIDENCE':'table_evidence','FUSE_DATABASE_EVIDENCE':'database_evidence', - 'FUSE_METADATA_EVIDENCE':'metadata_evidence','FUSE_STANDARD_EVIDENCE':'standard_evidence', - 'WEIGH_EVIDENCE':'evidence_weights','RESOLVE_FIELD_CONTEXT_CONFLICT':'field_context_resolution', - 'RESOLVE_METADATA_CONFLICT':'metadata_conflict_resolution','RESOLVE_STANDARD_CONFLICT':'standard_conflict_resolution', - 'ASSESS_CATEGORY_SUPPORT':'category_support','COMPARE_CATEGORY_HYPOTHESES':'category_comparison', - 'IDENTIFY_MISSING_EVIDENCE':'missing_evidence','DECIDE_NEXT_EVIDENCE_SOURCE':'next_evidence_source', - 'VERIFY_CATEGORY_WITH_STANDARD':'category_verification', - 'VERIFY_CLASSIFICATION_GRADING_CONSISTENCY':'grading_consistency', -} - - -def _inputs(text): - return () if text in ('','无') else tuple(v.strip() for v in text.split(',')) - - -def pool_catalog(pool: str): - if pool not in ('P14','F66'): - raise ValueError('pool must be P14 or F66') - if pool=='P14': - return dict(SHARED) - legacy=default_catalog() - result={} - for role,names in NAMES.items(): - if not isinstance(names,list): - continue - for name in names: - if name in SHARED: - result[name]=SHARED[name] - elif name in legacy: - result[name]=legacy[name] - if name=='SYNTHESIZE_METADATA_SEMANTICS': - result[name]=replace(result[name],optional_inputs=_inputs(REFERENCE[name]['optional'])) - else: - ref=REFERENCE[name] - produced='standard_candidates' if name in SEARCH_NAMES else OUTPUTS.get(name,name.lower()) - result[name]=SkillSpec(name,role,_inputs(ref['required']),_inputs(ref['optional']),(produced,)) - result.update(SHARED) - return result - - -def purpose(name): - if name in REFERENCE: - return REFERENCE[name]['purpose'] - return { - 'GET_FIELD_METADATA':'Retrieve actual allowlisted metadata for the privately identified target record.', - 'SELECT_CATEGORY_TOPK':'Rank exactly five actual frozen Registry options by supplied evidence.', - 'INFER_CATEGORY_FROM_TOPK':'Select one actual prior Top-5 option and bind its frozen standard entry.' - }[name] - - -def install_contracts(skill_root): - """Explicit pre-freeze action; creates missing contracts, never edits existing files.""" - destination=Path(skill_root)/'full_pool' - existing=[p for p in (ROOT/'runtime/skills').rglob('*.md') if 'full_pool' not in p.parts] - patches=[] - for name,spec in pool_catalog('F66').items(): - target=destination/f'{spec.role}_{name}.md' - if target.exists(): - continue - source=next((p for p in existing if p.name==target.name and ('neighbor_extra' not in p.parts)),None) - if source is not None and name!='SYNTHESIZE_METADATA_SEMANTICS': - content=source.read_bytes().decode('utf-8') - else: - header='\n'.join([ - '---',f'name: {name}',f'dsl: {spec.role}', - f'required_inputs: [{", ".join(spec.required_inputs)}]', - f'optional_inputs: [{", ".join(spec.optional_inputs)}]', - f'produces: [{", ".join(spec.produces)}]',f'terminal: {str(spec.terminal).lower()}','---','', - ]) - ref=REFERENCE[name] - body=f'# {name}\n\nPurpose: {purpose(name)}\n\nObservation: {ref["output"]}\n\n' - boundaries={ - 'metadata_acquisition':'Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage.', - 'semantic_interpretation':'Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata.', - 'standard_alignment':'Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state.', - 'evidence_reasoning':'Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state.' - } - body+=boundaries[spec.role]+'\n\nReturn exactly {"summary": "nonempty natural-language observation", "data": {...}}. ' - body+=f'Data keys must be exactly {json.dumps(spec.produces)}. ' - body+='Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys.\n' - content=header+body - patches.append((target,content)) - # Runtime contract installation is an explicit artifact generation operation. - destination.mkdir(parents=True,exist_ok=True) - for target,content in patches: - with target.open('xb') as stream: - stream.write(content.encode('utf-8')) - return destination diff --git a/research/finance_program_v1/nontraining/vendor/pool_metadata.py b/research/finance_program_v1/nontraining/vendor/pool_metadata.py deleted file mode 100644 index a7bc2d9..0000000 --- a/research/finance_program_v1/nontraining/vendor/pool_metadata.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Private-identity, label-free access to one canonical Val metadata source.""" -import copy -import json -import math -from pathlib import Path -from collections.abc import Mapping - -FIELDS=('field_name','database_name','database_description','table_name','table_description','field_description','field_type','value') -MISSING={'','none','null','n/a','nan'} - - -def present(value): - if value is None: - return False - if isinstance(value,str): - return value.strip().casefold() not in MISSING - if isinstance(value,float) and math.isnan(value): - return False - return bool(value) or value==0 - - -class PoolMetadata: - def __init__(self,rows): - if not isinstance(rows,list): - raise ValueError('canonical source must be a list') - self._rows={} - for row in rows: - if not isinstance(row,Mapping) or not isinstance(row.get('id'),str) or not row['id'] or row['id'] in self._rows: - raise ValueError('canonical rows require unique nonempty private IDs') - raw=row.get('metadata') - if not isinstance(raw,Mapping) or not present(row.get('domain')) or not present(raw.get('field_name')): - raise ValueError('canonical row requires real domain and field_name') - fields={k:copy.deepcopy(raw[k]) for k in FIELDS if present(raw.get(k))} - self._rows[row['id']]={'domain':row['domain'],'fields':fields} - - @classmethod - def from_canonical(cls,path): - return cls(json.loads(Path(path).read_text(encoding='utf-8'))) - - def _entry(self,record): - entry=self._rows.get(record.source_id) - if entry is None: - raise ValueError('source id is absent from canonical metadata lookup') - if entry['domain']!=record.domain or entry['fields']['field_name']!=record.field_name: - raise ValueError('private lookup does not match domain and field_name') - return entry - - def get(self,record): - return copy.deepcopy(self._entry(record)['fields']) - - def _same_table(self,record): - entry=self._entry(record); fields=entry['fields'] - db,table=fields.get('database_name'),fields.get('table_name') - if not present(db) or not present(table): - return [] - return sorted([r['fields'] for r in self._rows.values() if r['domain']==record.domain and r['fields'].get('database_name')==db and r['fields'].get('table_name')==table],key=lambda r:(str(r['field_name']),json.dumps(r,sort_keys=True,ensure_ascii=False))) - - def table_fields(self,record): - own=self.get(record) - neighbors=[r for r in self._same_table(record) if r['field_name']!=record.field_name] - # One actual field name can have several source rows. Keep deterministic first. - unique={} - for row in neighbors: - unique.setdefault(row['field_name'],row) - neighbors=list(unique.values()) - visible=[{k:copy.deepcopy(v) for k,v in r.items() if k in ('field_name','field_description','field_type','value')} for r in neighbors[:30]] - return {'database_name':own.get('database_name'),'table_name':own.get('table_name'),'fields':visible, - 'available_count':len(neighbors),'returned_count':len(visible),'truncated':len(neighbors)>30, - 'omitted_count':max(0,len(neighbors)-30),'coverage':'canonical-val-same-table-only', - 'missing_locators':[k for k in ('database_name','table_name') if k not in own]} - - def expand(self,record,names): - if not isinstance(names,list) or not names or any(not isinstance(n,str) or not n.strip() for n in names) or len(set(names))!=len(names): - raise ValueError('selected context must be a nonempty distinct list of actual field names') - actual={r['field_name']:r for r in self.table_fields(record)['fields']} - if any(name not in actual for name in names): - raise ValueError('context field is outside actual bounded same-table candidates') - return [copy.deepcopy(actual[n]) for n in names] - - def table_context(self,record): - own=self.get(record) - context=self.table_fields(record) - return {'target':own,**context,'missing_target_attributes':[k for k in FIELDS if k not in own]} - - def database_context(self,record): - own=self.get(record) - db=own.get('database_name') - if not present(db): - return {'tables':[],'coverage':'canonical-val-available-tables-only','missing_locators':['database_name'],'truncated':False,'omitted_count':0,'available_count':0} - tables={} - omitted_rows=0 - for entry in self._rows.values(): - fields=entry['fields'] - if entry['domain']!=record.domain or fields.get('database_name')!=db: - continue - if not present(fields.get('table_name')): - omitted_rows+=1 - continue - table=tables.setdefault(fields['table_name'],{'table_name':fields['table_name'],'field_names':set(),'descriptions':set()}) - table['field_names'].add(fields['field_name']) - if present(fields.get('table_description')): - table['descriptions'].add(fields['table_description']) - ordered=[] - for name in sorted(tables): - table=tables[name]; fields=sorted(table['field_names']) - ordered.append({'table_name':name,'table_descriptions':sorted(table['descriptions']), - 'field_names':fields[:30],'available_field_count':len(fields),'omitted_field_count':max(0,len(fields)-30)}) - return {'database_name':db,'database_description':own.get('database_description'), - 'tables':ordered[:10],'available_count':len(ordered),'returned_count':min(10,len(ordered)), - 'truncated':len(ordered)>10,'omitted_count':max(0,len(ordered)-10),'omitted_unlocated_rows':omitted_rows, - 'coverage':'canonical-val-available-tables-only','missing_locators':[]} diff --git a/research/finance_program_v1/nontraining/vendor/pool_runtime.py b/research/finance_program_v1/nontraining/vendor/pool_runtime.py deleted file mode 100644 index edc9555..0000000 --- a/research/finance_program_v1/nontraining/vendor/pool_runtime.py +++ /dev/null @@ -1,501 +0,0 @@ -"""Common dynamic controller, scoped metadata paths and native semantic execution.""" -import json -from collections.abc import Mapping -from dataclasses import replace -from pathlib import Path - -from agent.orchestration.agent_loop import (AgentLoopController, LoopConfig, LoopState, PolicyDecision, - ActionError, parse_policy_action, build_final_evidence_state) -from agent.orchestration.category_catalog import CategoryCatalog -from agent.orchestration.contracts import ToolCall -from agent.orchestration.model_skill_executor import (ModelSkillExecutor, SkillExecutionError, - parse_skill_observation, _generation_metadata) -from agent.orchestration.runtime import Observation -from agent.orchestration.skill_loader import SkillLoader -from pool_catalog import ROOT, pool_catalog, purpose, SEARCH_NAMES -from pool_metadata import PoolMetadata, FIELDS, present -from pool_bindings import bind_call, BINDING_RULE_VERSION - -POLICY_SYSTEM = '''You are a database-field classification orchestration policy. -Choose exactly one currently callable Skill, using the global capability index to plan a minimum sufficient evidence program. -Only domain and field_name are visible initially. Other raw metadata requires explicit acquisition; pending metadata is not evidence. -Choose the Skill; the controller binds required state arguments. Omit controller-bound arguments, or supply their exact advertised references or strictly identical values. Explicit values are checked before normalization. -ACQUIRE_MISSING_METADATA requires an explicit missing_metadata_type chosen from actual missing_metadata_types. Optional arguments may be supplied only when actually bound. Never use provenance source names as argument data. -Never invent raw metadata, standard entries, labels or grading levels. Intermediate semantic strings are evidence, not acquired raw values. -Stop acquiring when evidence is sufficient, select a supported category, confirm its frozen grade and finalize within the remaining budget. -Return exactly one JSON object: {"tool":"SKILL_NAME","arguments":{}}. No Program, Markdown, plain stop, or extra JSON.''' - -SEMANTIC_KEYS = ( - 'domain_semantics','field_abbreviation_semantics','field_semantics','disambiguated_field_semantics', - 'field_description_semantics','field_type_semantics','value_semantics','table_abbreviation_semantics', - 'table_semantics','table_description_semantics','database_abbreviation_semantics','database_semantics', - 'database_description_semantics','context_field_semantics','metadata_semantics', - 'field_evidence','context_evidence','table_evidence','database_evidence','metadata_evidence', -) -ALIGNMENT_KEYS=('field_standard_alignment','context_standard_alignment','table_standard_alignment', - 'database_standard_alignment','value_standard_alignment','description_standard_alignment','standard_comparison') - -# Every validated, declared-type native output participates in the evidence -# boundary, including refinement, conflict resolution and support assessments. -SEMANTIC_KEYS=tuple(dict.fromkeys((*SEMANTIC_KEYS,*(key for spec in pool_catalog('F66').values() - if spec.role in ('semantic_interpretation','evidence_reasoning') for key in spec.produces - if key not in ('category','grading_level','aligned_standard_entry','final_result'))))) -ALIGNMENT_KEYS=tuple(dict.fromkeys((*ALIGNMENT_KEYS,*(key for spec in pool_catalog('F66').values() - if spec.role=='standard_alignment' for key in spec.produces - if key not in ('standard_candidates','aligned_standard_entry'))))) - - -def valid_evidence_value(key,value): - if key=='evidence_sufficiency': - return (isinstance(value,Mapping) and set(value)=={'sufficient','rationale'} - and type(value['sufficient']) is bool - and isinstance(value['rationale'],str) and bool(value['rationale'].strip())) - return isinstance(value,str) and bool(value.strip()) - - -def validated_evidence_values(state,keys): - catalog=pool_catalog('F66');provenance=state.get('_provenance',{}) - return {key:state[key] for key in keys - if key in state and provenance.get(key) in catalog - and key in catalog[provenance[key]].produces - and valid_evidence_value(key,state[key])} - - -def acquired_raw(record,state): - provenance=state.get('_provenance',{}) - return {'field_name':record.field_name,**{k:state[k] for k in FIELDS - if k!='field_name' and k in provenance and present(state.get(k))}} - - -def assemble_pool_evidence(record,state): - """Single allowlisted boundary for publication, model search and finalization.""" - provenance=state.get('_provenance',{}) - semantics=validated_evidence_values(state,SEMANTIC_KEYS) - alignments=validated_evidence_values(state,ALIGNMENT_KEYS) - observations={k:state[k] for k in ('table_fields','selected_context_fields','context_fields', - 'context_field_descriptions','context_field_types','context_field_values','table_context','database_context') - if k in provenance and present(state.get(k))} - metadata=acquired_raw(record,state) if record is not None else dict(state.get('current_metadata',{})) - names=set(metadata)|set(semantics)|set(alignments)|set(observations) - prior=state.get('available_evidence',{}) - return {'domain':record.domain if record is not None else prior.get('domain'), - 'field_name':record.field_name if record is not None else metadata.get('field_name'), - 'metadata':metadata,'semantics':semantics,'alignments':alignments,'observations':observations, - 'provenance':{k:provenance[k] for k in sorted(names) if k in provenance}} - - -def pool_final_evidence(record,state): - final=build_final_evidence_state(state) - if final is not None: - evidence=assemble_pool_evidence(record,state) - final['semantic_evidence']={**evidence['semantics'],**evidence['alignments']} - final['available_evidence']=evidence - return final - - -def publish_state(record,state,data,skill): - """Publish only typed observed data and explicit evidence bundles, with provenance.""" - spec=pool_catalog('F66').get(skill) - if spec is None or not set(data)<=set(spec.produces): - raise SkillExecutionError('publication contains undeclared outputs or unknown Skill') - for key,value in data.items(): - if key in (*SEMANTIC_KEYS,*ALIGNMENT_KEYS) and not valid_evidence_value(key,value): - raise SkillExecutionError(f'{key} violates its declared evidence type') - state.update(data) - provenance=state.setdefault('_provenance',{}) - provenance.update({k:skill for k in data}) - if isinstance(data.get('metadata_availability'),Mapping): - state['current_metadata']=acquired_raw(record,state) - state['available_metadata']={'domain':record.domain,**state['current_metadata']} - missing=data['metadata_availability'].get('missing',[]) - state['missing_metadata_types']=[k for k in missing if k in FIELDS] - if state['missing_metadata_types']: - state['missing_metadata_type']=state['missing_metadata_types'][0] - provenance['missing_metadata_type']=skill - else: - state.pop('missing_metadata_type',None) - provenance.pop('missing_metadata_type',None) - raw={} - for key in ('field_metadata','acquired_metadata'): - value=data.get(key) - if isinstance(value,Mapping): - raw.update({k:v for k,v in value.items() if k in FIELDS and present(v)}) - if skill.startswith('GET_'): - raw.update({k:v for k,v in data.items() if k in FIELDS and present(v)}) - for key,value in raw.items(): - state[key]=value; provenance[key]=skill - if raw: - # Initial field_name belongs to the record, not necessarily to state. - # Publish the same acquired-only boundary consumed by the executor. - state['current_metadata']=acquired_raw(record,state) - state['available_metadata']={'domain':record.domain,**state['current_metadata']} - state['missing_metadata_types']=[k for k in FIELDS if k not in state['current_metadata']] - if state['missing_metadata_types']: - state['missing_metadata_type']=state['missing_metadata_types'][0] - provenance['missing_metadata_type']=skill - else: - state.pop('missing_metadata_type',None) - provenance.pop('missing_metadata_type',None) - aliases={'context_field_semantics':'context_semantics','field_semantics':'candidate_field_semantics', - 'category':'aligned_category','grading_level':'grading_level_candidate'} - for original,alias in aliases.items(): - if original in state and present(state[original]): - state[alias]=state[original]; provenance[alias]=provenance.get(original,skill) - if 'category' in state: - for alias in ('candidate_category','category_candidate'): - state[alias]=state['category']; provenance[alias]=provenance.get('category',skill) - if isinstance(state.get('standard_candidates'),list) and state['standard_candidates']: - for alias in ('candidate_standard_categories','candidate_categories','previous_standard_results'): - state[alias]=state['standard_candidates']; provenance[alias]=provenance.get('standard_candidates',skill) - semantics=validated_evidence_values(state,SEMANTIC_KEYS) - alignments=validated_evidence_values(state,ALIGNMENT_KEYS) - groups={ - 'available_field_evidence':{k:v for k,v in semantics.items() if k.startswith(('field_','disambiguated_','value_'))}, - 'context_field_evidence':{k:v for k,v in semantics.items() if k.startswith('context_')}, - 'available_table_evidence':{k:v for k,v in semantics.items() if k.startswith('table_')}, - 'available_database_evidence':{k:v for k,v in semantics.items() if k.startswith('database_')}, - 'available_metadata_evidence':semantics,'standard_alignment_evidence':alignments, - 'aligned_standard_candidates':alignments,'available_semantic_context':{k:v for k,v in semantics.items() if k not in ('field_semantics','field_abbreviation_semantics')}, - } - if semantics: - for name in ('semantic_evidence','current_semantic_state','semantic_query','current_evidence', - 'current_evidence_state','all_available_evidence','evidence','evidence_set'): - groups[name]=semantics - if len(semantics)>=2: - groups['conflicting_metadata_evidence']=semantics - if len(alignments)>=2: - groups['conflicting_standard_alignments']=alignments - for name,value in groups.items(): - if value: - state[name]=value; provenance[name]='validated-evidence-bundle' - # Raw retrieved metadata is also usable search evidence, without pretending it is semantics. - if isinstance(state.get('field_metadata'),Mapping) or semantics: - state['available_evidence']=assemble_pool_evidence(record,state) - provenance['available_evidence']='validated-evidence-bundle' - state['all_available_evidence']=state['available_evidence'] - provenance['all_available_evidence']='validated-evidence-bundle' - if 'semantic_query' not in state: - state['semantic_query']=state['available_evidence'] - evidence=pool_final_evidence(record,state) - if evidence is not None: - state['final_evidence_state']=evidence - provenance['final_evidence_state']='frozen-classification-bundle' - - -def _binding(name,record,state): - if name=='current_record': return '$record' - if name=='domain': return '$domain' - if name in ('field_name','target_field'): return '$metadata.field_name' - if name=='table_fields': - value=state.get(name) - if not isinstance(value,Mapping) or value.get('coverage')!='canonical-val-same-table-only' or value.get('missing_locators')!=[]: - return None - fields=value.get('fields') - if (not isinstance(fields,list) or not fields or len(fields)>30 - or type(value.get('returned_count')) is not int or value['returned_count']!=len(fields) - or type(value.get('available_count')) is not int or value['available_count'] None: - if self.max_turns < 1: - raise ValueError("max_turns must be at least 1") - if self.max_identical_calls < 1: - raise ValueError("max_identical_calls must be at least 1") - if ( - self.action_retries < 0 - or self.forced_finalize_retries < 0 - or self.repetition_retries < 0 - ): - raise ValueError("retry limits must be non-negative") - - -@dataclass(frozen=True) -class LoopEvent: - kind: str - turn: int - data: Mapping[str, Any] = field(default_factory=dict) - - def to_dict(self) -> dict[str, Any]: - return {"kind": self.kind, "turn": self.turn, "data": dict(self.data)} - - -@dataclass -class LoopState: - input: dict[str, str] - named_state: dict[str, Any] = field(default_factory=dict) - call_history: list[dict[str, Any]] = field(default_factory=list) - turns: int = 0 - max_turns: int = 8 - - @classmethod - def from_record(cls, record: MetadataRecord, *, max_turns: int) -> "LoopState": - return cls( - input={"domain": record.domain, "field_name": record.field_name}, - max_turns=max_turns, - ) - - @property - def remaining_turns(self) -> int: - return max(self.max_turns - self.turns, 0) - - def to_model_dict(self) -> dict[str, Any]: - return { - "input": dict(self.input), - "named_state": dict(self.named_state), - "call_history": [dict(item) for item in self.call_history], - "turns": self.turns, - "remaining_turns": self.remaining_turns, - } - - -@dataclass(frozen=True) -class PolicyDecision: - call: ToolCall - raw_response: str - messages: tuple[dict[str, str], ...] = () - metadata: Mapping[str, Any] = field(default_factory=dict) - - -@dataclass -class LoopTrace: - input: dict[str, str] - events: list[LoopEvent] = field(default_factory=list) - terminated: bool = False - final_result: dict[str, Any] | None = None - stop_reason: str = "not_started" - turns: int = 0 - state: dict[str, Any] = field(default_factory=dict) - - def to_dict(self) -> dict[str, Any]: - return { - "input": dict(self.input), - "events": [event.to_dict() for event in self.events], - "terminated": self.terminated, - "final_result": dict(self.final_result) if self.final_result is not None else None, - "stop_reason": self.stop_reason, - "turns": self.turns, - "state": dict(self.state), - } - - -class LoopPolicy(Protocol): - def select_action( - self, - record: MetadataRecord, - state: LoopState, - callable_skills: Mapping[str, SkillSpec], - *, - feedback: str | None = None, - forced_finalize: bool = False, - ) -> PolicyDecision: ... - - -class PrefetchFieldMetadataPolicy: - """Spend the first normal turn querying metadata, then delegate unchanged.""" - - def __init__(self, delegate: LoopPolicy) -> None: - self.delegate = delegate - - def select_action( - self, - record: MetadataRecord, - state: LoopState, - callable_skills: Mapping[str, SkillSpec], - *, - feedback: str | None = None, - forced_finalize: bool = False, - ) -> PolicyDecision: - if ( - not forced_finalize - and state.turns == 0 - and not any(item.get("tool") == "GET_FIELD_METADATA" for item in state.call_history) - and "GET_FIELD_METADATA" in callable_skills - ): - call = ToolCall("GET_FIELD_METADATA", {"current_record": "$record"}) - return PolicyDecision( - call=call, - raw_response=json.dumps(call.to_dict(), ensure_ascii=False), - metadata={"fixed_metadata_prefetch": True}, - ) - return self.delegate.select_action( - record, state, callable_skills, - feedback=feedback, forced_finalize=forced_finalize, - ) - - -class PrefetchNeighborFieldsPolicy: - """Fixed one-time neighbor lookup followed by an unchanged dynamic policy.""" - - def __init__(self, delegate: LoopPolicy) -> None: - self.delegate = delegate - - def select_action( - self, - record: MetadataRecord, - state: LoopState, - callable_skills: Mapping[str, SkillSpec], - *, - feedback: str | None = None, - forced_finalize: bool = False, - ) -> PolicyDecision: - previously_called = any( - item.get("tool") == "GET_TABLE_FIELDS" for item in state.call_history - ) - if ( - not forced_finalize - and not previously_called - and "table_fields" not in state.named_state - and "GET_TABLE_FIELDS" in callable_skills - ): - call = ToolCall("GET_TABLE_FIELDS", {"current_record": "$record"}) - return PolicyDecision( - call=call, - raw_response=json.dumps(call.to_dict(), ensure_ascii=False), - metadata={"fixed_neighbor_prefetch": True}, - ) - return self.delegate.select_action( - record, state, callable_skills, - feedback=feedback, forced_finalize=forced_finalize, - ) - - -class SkillExecutor(Protocol): - def execute( - self, - call: ToolCall, - record: MetadataRecord, - state: Mapping[str, Any], - contract: SkillContract, - ) -> Observation: ... - - -def _decode_one_object(text: str) -> Mapping[str, Any]: - if not isinstance(text, str) or not text.strip(): - raise ActionError("policy action must be non-empty JSON") - cleaned = text.strip() - if cleaned.startswith("```"): - lines = cleaned.splitlines()[1:] - if lines and lines[-1].strip() == "```": - lines.pop() - cleaned = "\n".join(lines).strip() - if not cleaned.startswith("{"): - raise ActionError("policy action must be one JSON object") - decoder = json.JSONDecoder() - try: - value, end = decoder.raw_decode(cleaned) - except JSONDecodeError as exc: - raise ActionError(f"policy action is invalid JSON: {exc.msg}") from exc - if cleaned[end:].strip(): - raise ActionError("policy action contains trailing content") - if not isinstance(value, Mapping): - raise ActionError("policy action must be one Tool Call JSON object") - return value - - -def parse_policy_action(text: str) -> ToolCall: - """Parse exactly one Tool Call and reject Programs or plain stop tokens.""" - - if isinstance(text, str) and text.strip().lower().rstrip(".!" ) in { - "stop", - "done", - "finish", - "finished", - "terminate", - }: - raise EarlyStopError("policy stopped without a final result") - payload = _decode_one_object(text) - if set(payload) != {"tool", "arguments"}: - raise ActionError("policy action must be one Tool Call with tool and arguments") - try: - return ToolCall.from_mapping(payload) - except (TypeError, ValueError) as exc: - raise ActionError(f"invalid Tool Call: {exc}") from exc - - -def _has_semantic_state(state: Mapping[str, Any]) -> bool: - return any( - name in state - for name in ( - "field_semantics", - "field_abbreviation_semantics", - "disambiguated_field_semantics", - "domain_semantics", - "field_metadata", - ) - ) - - -_SEMANTIC_EVIDENCE_KEYS = ( - "domain_semantics", - "field_abbreviation_semantics", - "field_semantics", - "disambiguated_field_semantics", - "field_description_semantics", - "table_description_semantics", - "standard_comparison", -) - -_TWO_STAGE_EVIDENCE_KEYS = ( - "domain_semantics", - "field_abbreviation_semantics", - "field_semantics", - "disambiguated_field_semantics", - "field_metadata", - "table_fields", - "field_description_semantics", - "table_semantics", - "table_description_semantics", - "context_field_semantics", - "metadata_semantics", - "standard_comparison", -) - - -def _two_stage_evidence(record: MetadataRecord, state: Mapping[str, Any]) -> dict[str, Any]: - return { - "domain": record.domain, - "field_name": record.field_name, - "observations": {key: state[key] for key in _TWO_STAGE_EVIDENCE_KEYS if key in state}, - } - - -def build_final_evidence_state(state: Mapping[str, Any]) -> dict[str, Any] | None: - """Create the auditable evidence bundle required by the terminal Skill.""" - - category = state.get("category") - level = state.get("grading_level") - aligned = state.get("aligned_standard_entry") - candidates = state.get("standard_candidates") - if ( - not isinstance(category, str) - or not category - or not isinstance(level, str) - or not level - or not isinstance(aligned, Mapping) - or not isinstance(candidates, Sequence) - or isinstance(candidates, (str, bytes)) - or not candidates - ): - return None - semantic_evidence = { - key: state[key] - for key in _SEMANTIC_EVIDENCE_KEYS - if key in state and state[key] not in (None, "") - } - return { - "category": category, - "grading_level": level, - "aligned_standard_entry": dict(aligned), - "standard_candidates": [ - dict(item) if isinstance(item, Mapping) else item for item in candidates - ], - "semantic_evidence": semantic_evidence, - } - - -def _input_available(name: str, record: MetadataRecord, state: Mapping[str, Any]) -> bool: - if name == "current_record": - return True - if name in {"domain", "field_name"}: - return record.available(name) - if name in state: - return state[name] is not None and state[name] != "" - if name == "semantic_query": - return _has_semantic_state(state) - if name in {"semantic_evidence", "current_evidence", "all_available_evidence"}: - return bool(state) - if name == "candidate_standard_categories": - return bool(state.get("standard_candidates")) - if name == "aligned_category": - return bool(state.get("category")) - if name == "final_evidence_state": - return isinstance(state.get("final_evidence_state"), Mapping) - return False - - -def derive_callable_skills( - record: MetadataRecord, - state: LoopState | Mapping[str, Any], - catalog: Mapping[str, SkillSpec] | None = None, -) -> dict[str, SkillSpec]: - """Return Skills whose required semantic inputs currently exist.""" - - named = state.named_state if isinstance(state, LoopState) else state - active = catalog or dynamic_loop_catalog() - return { - name: spec - for name, spec in active.items() - if all(_input_available(required, record, named) for required in spec.required_inputs) - } - - -def _catalog_payload(catalog: Mapping[str, SkillSpec]) -> list[dict[str, Any]]: - return [ - { - "name": spec.name, - "required_inputs": list(spec.required_inputs), - "optional_inputs": list(spec.optional_inputs), - "produces": list(spec.produces), - "terminal": spec.terminal, - } - for spec in catalog.values() - ] - - -def build_policy_messages( - record: MetadataRecord, - state: LoopState, - callable_skills: Mapping[str, SkillSpec], - *, - feedback: str | None = None, - forced_finalize: bool = False, -) -> list[dict[str, str]]: - """Build a model prompt from the minimum visible input and current states.""" - - payload: dict[str, Any] = { - "task": "Choose the next Skill from the callable catalog or finalize when evidence is sufficient.", - "current": state.to_model_dict(), - "callable_skills": _catalog_payload(callable_skills), - "forced_finalize": forced_finalize, - "argument_reference_grammar": [ - "$record", - "$domain", - "$metadata.field_name", - "$state.", - ], - "output_schema": {"tool": "SKILL_NAME", "arguments": {}}, - } - if feedback: - payload["validation_feedback"] = feedback - return [ - {"role": "system", "content": POLICY_SYSTEM_PROMPT}, - {"role": "user", "content": json.dumps(payload, ensure_ascii=False, indent=2)}, - ] - - -class ScriptedLoopPolicy: - """Deterministic policy used to test controller behavior without a model.""" - - def __init__(self, responses: Iterable[str | ToolCall | Mapping[str, Any]]) -> None: - self.responses = deque(responses) - self.seen_states: list[dict[str, Any]] = [] - self.seen_feedback: list[str | None] = [] - self.seen_forced: list[bool] = [] - - def select_action( - self, - record: MetadataRecord, - state: LoopState, - callable_skills: Mapping[str, SkillSpec], - *, - feedback: str | None = None, - forced_finalize: bool = False, - ) -> PolicyDecision: - del record, callable_skills - self.seen_states.append(state.to_model_dict()) - self.seen_feedback.append(feedback) - self.seen_forced.append(forced_finalize) - if not self.responses: - raise ActionError("scripted policy has no response remaining") - response = self.responses.popleft() - if isinstance(response, ToolCall): - call = response - raw = json.dumps(call.to_dict(), ensure_ascii=False) - elif isinstance(response, Mapping): - raw = json.dumps(dict(response), ensure_ascii=False) - call = parse_policy_action(raw) - else: - raw = response - call = parse_policy_action(raw) - return PolicyDecision(call=call, raw_response=raw) - - -class FixedPipelinePolicy: - """Reference policy that follows the same five evidence steps for every row.""" - - def select_action( - self, - record: MetadataRecord, - state: LoopState, - callable_skills: Mapping[str, SkillSpec], - *, - feedback: str | None = None, - forced_finalize: bool = False, - ) -> PolicyDecision: - del record, feedback, forced_finalize - named = state.named_state - if "field_semantics" not in named: - call = ToolCall( - "INTERPRET_FIELD_NAME", - {"field_name": "$metadata.field_name", "domain": "$domain"}, - ) - elif "standard_candidates" not in named: - call = ToolCall("SEARCH_STANDARD", {"semantic_query": "$state.field_semantics"}) - elif "category" not in named: - call = ToolCall( - "INFER_CATEGORY", - { - "candidate_standard_categories": "$state.standard_candidates", - "all_available_evidence": "$state.field_semantics", - }, - ) - elif "grading_level" not in named: - call = ToolCall( - "INFER_GRADING_LEVEL", - { - "aligned_category": "$state.category", - "aligned_standard_entry": "$state.aligned_standard_entry", - }, - ) - else: - call = ToolCall( - "FINALIZE_CLASSIFICATION", - {"final_evidence_state": "$state.final_evidence_state"}, - ) - if call.tool not in callable_skills: - raise ActionError( - f"fixed pipeline requires {call.tool}, but it is not callable from the current state" - ) - raw = json.dumps(call.to_dict(), ensure_ascii=False, separators=(",", ":")) - return PolicyDecision(call=call, raw_response=raw) - - -class ScriptedSkillExecutor: - """Return predefined Observations while recording executed tools.""" - - def __init__(self, outputs: Mapping[str, Sequence[Observation]]) -> None: - self.outputs = {name: deque(values) for name, values in outputs.items()} - self.executed_tools: list[str] = [] - - def execute( - self, - call: ToolCall, - record: MetadataRecord, - state: Mapping[str, Any], - contract: SkillContract, - ) -> Observation: - del record, state, contract - self.executed_tools.append(call.tool) - queue = self.outputs.get(call.tool) - if not queue: - return Observation(call.tool, "error", "no scripted output", {}) - return queue.popleft() - - -def _canonical_call(call: ToolCall) -> str: - return json.dumps(call.to_dict(), ensure_ascii=False, sort_keys=True, separators=(",", ":")) - - -def _validate_call_arguments( - call: ToolCall, - spec: SkillSpec, - record: MetadataRecord, - state: Mapping[str, Any], -) -> str | None: - allowed = set(spec.required_inputs) | set(spec.optional_inputs) - unknown = sorted(set(call.arguments) - allowed) - if unknown: - return f"unknown arguments for {call.tool}: {unknown}" - for name in spec.required_inputs: - if name not in call.arguments: - return f"missing required argument {name!r}" - if (call.tool == "INFER_CATEGORY_FROM_TOPK" - and call.arguments.get("candidate_standard_categories") - != "$state.standard_candidates"): - return ( - "candidate_standard_categories must be the exact reference " - "$state.standard_candidates; do not rewrite prior candidate IDs" - ) - for name, value in call.arguments.items(): - found, _ = resolve_reference(value, record, state) - if not found: - return f"argument {name!r} cannot be resolved" - return None - - -class AgentLoopController: - """Run one validated Skill at a time with controller-owned safeguards.""" - - def __init__( - self, - *, - policy: LoopPolicy, - executor: SkillExecutor, - catalog: Mapping[str, SkillSpec] | None = None, - skill_loader: SkillLoader, - config: LoopConfig | None = None, - registry_categories: Iterable[str] = (), - registry_entries: Mapping[str, Mapping[str, Any]] | None = None, - approved_levels: Iterable[str] = ("L1", "L2", "L3", "L4"), - callable_derivation=None, - state_publication=None, - ) -> None: - self.policy = policy - self.executor = executor - self.catalog = dict(catalog or dynamic_loop_catalog()) - self.skill_loader = skill_loader - self.config = config or LoopConfig() - self.registry_entries = { - str(category): dict(entry) - for category, entry in (registry_entries or {}).items() - } - self.registry_categories = frozenset( - {str(item) for item in registry_categories} | set(self.registry_entries) - ) - self.approved_levels = frozenset(str(item) for item in approved_levels) - self.callable_derivation = callable_derivation or derive_callable_skills - self.state_publication = state_publication - - def _normalize_policy_decision(self, decision, record, state, spec): - """Extension point for controller-owned transport normalization.""" - return decision - - def _rejected_policy_metadata(self, decision, error): - return {} - - def _valid_terminal(self, result: Any, state: Mapping[str, Any]) -> bool: - if not isinstance(result, Mapping): - return False - category = result.get("category") - level = result.get("grading_level") - if not isinstance(category, str) or not category: - return False - if self.registry_categories and category not in self.registry_categories: - return False - if not isinstance(level, str) or level not in self.approved_levels: - return False - - frozen_entry = self.registry_entries.get(category) - if frozen_entry is not None and frozen_entry.get("grading_level") != level: - return False - - aligned = state.get("aligned_standard_entry") - if not isinstance(aligned, Mapping): - return False - aligned_category = aligned.get("category") or aligned.get("category_id") - if aligned_category != category or aligned.get("grading_level") != level: - return False - - candidates = state.get("standard_candidates") - if not isinstance(candidates, Sequence) or isinstance(candidates, (str, bytes)): - return False - if not any( - isinstance(candidate, Mapping) - and (candidate.get("category") or candidate.get("category_id")) == category - for candidate in candidates - ): - return False - - evidence = state.get("final_evidence_state") - return ( - isinstance(evidence, Mapping) - and evidence.get("category") == category - and evidence.get("grading_level") == level - ) - - def _normalize_observation( - self, - call: ToolCall, - observation: Observation, - state: Mapping[str, Any], - ) -> Observation: - """Bind model-selected evidence back to exact frozen controller objects.""" - - if observation.status != "success": - return observation - if call.tool in {"INFER_CATEGORY", "INFER_CATEGORY_FROM_TOPK"}: - category = observation.data.get("category") - candidates = state.get("standard_candidates") - matched = None - if isinstance(category, str) and isinstance(candidates, Sequence): - matched = next( - ( - candidate - for candidate in candidates - if isinstance(candidate, Mapping) - and (candidate.get("category") or candidate.get("category_id")) - == category - ), - None, - ) - if not isinstance(matched, Mapping): - return Observation( - call.tool, - "error", - "model-selected category is not one of the retrieved candidates", - {}, - metadata=dict(observation.metadata), - ) - data = dict(observation.data) - original = data.get("aligned_standard_entry") - if call.tool == "INFER_CATEGORY_FROM_TOPK": - frozen = self.registry_entries.get(category) - if not isinstance(frozen, Mapping): - return Observation(call.tool, "error", "selected category is absent from frozen registry", {}) - data["aligned_standard_entry"] = {"category": category, **dict(frozen)} - else: - data["aligned_standard_entry"] = dict(matched) - metadata = dict(observation.metadata) - metadata["controller_normalized_aligned_entry"] = original != data["aligned_standard_entry"] - return Observation( - observation.skill, - observation.status, - observation.summary, - data, - metadata=metadata, - ) - if call.tool == "INFER_GRADING_LEVEL": - level = observation.data.get("grading_level") - if not isinstance(level, str) or level not in self.approved_levels: - return Observation( - call.tool, - "error", - "model-produced grading level is empty or not approved", - {}, - metadata=dict(observation.metadata), - ) - return observation - - def _ready_finalization(self, state: Mapping[str, Any]) -> bool: - """Require the current bundle to agree with exact frozen registry evidence.""" - evidence = state.get("final_evidence_state") - if not self._valid_terminal(evidence, state): - return False - category = state.get("category") - frozen = self.registry_entries.get(category) if isinstance(category, str) else None - return ( - isinstance(frozen, Mapping) - and evidence.get("category") == category - and evidence.get("grading_level") == state.get("grading_level") - and state.get("aligned_standard_entry") == {"category": category, **dict(frozen)} - and evidence == self._final_evidence_state(None, state) - ) - - def _available_evidence(self, record, state): - return _two_stage_evidence(record, state) - - def _final_evidence_state(self, record, state): - return build_final_evidence_state(state) - - def run(self, record: MetadataRecord) -> LoopTrace: - visible_record = MetadataRecord.from_mapping( - {"domain": record.domain, "field_name": record.field_name, - "source_id": record.source_id} - ) - state = LoopState.from_record(visible_record, max_turns=self.config.max_turns) - trace = LoopTrace(input=dict(state.input), stop_reason="running") - identical_counts: Counter[str] = Counter() - repetition_rejections = 0 - invalid_terminal_count = 0 - feedback: str | None = None - recovery_attempted = False - - while state.turns < self.config.max_turns: - forced = state.remaining_turns == 1 - recovering = False - callable_skills = self.callable_derivation(visible_record, state, self.catalog) - decision: PolicyDecision | None = None - if forced: - if "FINALIZE_CLASSIFICATION" not in callable_skills: - trace.events.append( - LoopEvent( - "controller_intervention", - state.turns + 1, - {"reason": "forced_finalization_missing_evidence"}, - ) - ) - trace.stop_reason = "budget_exhausted_no_result" - break - call = ToolCall( - "FINALIZE_CLASSIFICATION", - {"final_evidence_state": "$state.final_evidence_state"}, - ) - raw = json.dumps(call.to_dict(), ensure_ascii=False, separators=(",", ":")) - decision = PolicyDecision(call=call, raw_response=raw) - callable_skills = { - "FINALIZE_CLASSIFICATION": callable_skills["FINALIZE_CLASSIFICATION"] - } - trace.events.append( - LoopEvent( - "controller_intervention", - state.turns + 1, - {"reason": "forced_finalization", "call": call.to_dict()}, - ) - ) - else: - invalid_reason = "invalid_action" - for attempt in range(self.config.action_retries + 1): - try: - decision = self.policy.select_action( - visible_record, - state, - callable_skills, - feedback=feedback, - forced_finalize=False, - ) - if decision.call.tool not in callable_skills: - invalid_reason = "uncallable_skill" - raise ActionError( - f"{decision.call.tool} is not callable; choices={list(callable_skills)}" - ) - spec = callable_skills[decision.call.tool] - decision = self._normalize_policy_decision( - decision, visible_record, state.named_state, spec - ) - argument_error = _validate_call_arguments( - decision.call, spec, visible_record, state.named_state - ) - if argument_error: - invalid_reason = "invalid_arguments" - raise ActionError(argument_error) - break - except ActionError as exc: - if isinstance(exc, EarlyStopError): - invalid_reason = "stop_without_final_result" - rejected_data: dict[str, Any] = { - "reason": invalid_reason, - "error": str(exc), - "attempt": attempt + 1, - } - if decision is not None: - rejected_data["raw_response"] = decision.raw_response - rejected_data["messages"] = [dict(m) for m in decision.messages] - rejected_data["metadata"] = dict(decision.metadata) - elif isinstance(getattr(exc, "metadata", None), Mapping): - rejected_data["metadata"] = dict(exc.metadata) - rejection_metadata = self._rejected_policy_metadata(decision, exc) - if rejection_metadata: - rejected_data.setdefault("metadata", {}).update(rejection_metadata) - decision = None - feedback = str(exc) - trace.events.append( - LoopEvent( - "retry" if attempt < self.config.action_retries else "rejected_action", - state.turns + 1, - rejected_data, - ) - ) - if attempt == self.config.action_retries: - if ( - self.config.recover_ready_finalization - and not recovery_attempted - and "FINALIZE_CLASSIFICATION" in callable_skills - and self._ready_finalization(state.named_state) - ): - recovery_attempted = True - recovering = True - forced = True - call = ToolCall( - "FINALIZE_CLASSIFICATION", - {"final_evidence_state": "$state.final_evidence_state"}, - ) - decision = PolicyDecision( - call=call, - raw_response=json.dumps(call.to_dict(), ensure_ascii=False), - ) - trace.events.append(LoopEvent( - "controller_intervention", state.turns + 1, - {"reason": "invalid_action_finalization_recovery", "call": call.to_dict()}, - )) - break - if invalid_reason == "stop_without_final_result": - trace.stop_reason = "stop_without_final_result" - else: - trace.stop_reason = "invalid_action" - trace.turns = state.turns - trace.state = dict(state.named_state) - return trace - - assert decision is not None - if forced: - decision = self._normalize_policy_decision( - decision, visible_record, state.named_state, self.catalog[decision.call.tool] - ) - call = decision.call - canonical = _canonical_call(call) - if identical_counts[canonical] >= self.config.max_identical_calls: - repetition_rejections += 1 - recoverable = ( - not recovering - and repetition_rejections <= self.config.repetition_retries - ) - trace.events.append( - LoopEvent( - "controller_intervention", - state.turns + 1, - { - "reason": "repetition_limit", - "call": call.to_dict(), - "recovered": recoverable, - "attempt": repetition_rejections, - "messages": [dict(m) for m in decision.messages], - "raw_response": decision.raw_response, - "metadata": dict(decision.metadata), - }, - ) - ) - if recoverable: - feedback = ( - f"Repeated call {call.tool} was blocked; choose a different callable Skill." - ) - continue - trace.stop_reason = "repetition_limit" - trace.turns = state.turns - trace.state = dict(state.named_state) - return trace - identical_counts[canonical] += 1 - - if decision.metadata.get("fixed_metadata_prefetch"): - trace.events.append( - LoopEvent( - "controller_intervention", state.turns + 1, - {"reason": "metadata_prefetch", "call": call.to_dict()}, - ) - ) - trace.events.append( - LoopEvent( - "policy_action", - state.turns + 1, - { - "call": call.to_dict(), - "raw_response": decision.raw_response, - "messages": [dict(message) for message in decision.messages], - "metadata": dict(decision.metadata), - "forced_finalize": forced, - }, - ) - ) - contract = self.skill_loader.load(call.tool) - try: - observation = self.executor.execute( - call, visible_record, dict(state.named_state), contract - ) - except Exception as exc: - metadata = getattr(exc, "metadata", {}) - observation = Observation( - call.tool, "error", str(exc), {}, - metadata=dict(metadata) if isinstance(metadata, Mapping) else {}, - ) - observation = self._normalize_observation( - call, observation, state.named_state - ) - - state.turns += 1 - state.call_history.append(call.to_dict()) - trace.events.append( - LoopEvent( - "observation", - state.turns, - { - "skill": observation.skill, - "status": observation.status, - "summary": observation.summary, - "data": dict(observation.data), - "metadata": dict(observation.metadata), - }, - ) - ) - feedback = None - - if observation.status != "success": - feedback = f"Skill {call.tool} failed: {observation.summary}" - if recovering: - trace.stop_reason = "recovery_finalization_failed" - break - if forced or state.turns >= self.config.max_turns: - trace.stop_reason = "budget_exhausted_no_result" - break - continue - - state.named_state.update(observation.data) - if self.state_publication is not None: - self.state_publication(visible_record, state.named_state, observation.data, call.tool) - if call.tool == "GET_FIELD_METADATA" and "INTERPRET_FIELD_DESCRIPTION" in self.catalog: - metadata = observation.data.get("field_metadata") - if isinstance(metadata, Mapping): - for key in ("field_description", "table_description"): - value = metadata.get(key) - if isinstance(value, str) and value.strip(): - state.named_state[key] = value - if "INFER_CATEGORY_FROM_TOPK" in self.catalog: - state.named_state["available_evidence"] = self._available_evidence( - visible_record, state.named_state - ) - evidence = self._final_evidence_state(visible_record, state.named_state) - if evidence is None: - state.named_state.pop("final_evidence_state", None) - else: - state.named_state["final_evidence_state"] = evidence - if call.tool != "FINALIZE_CLASSIFICATION": - continue - - result = observation.data.get("final_result") - if self._valid_terminal(result, state.named_state): - trace.terminated = True - trace.final_result = dict(result) - trace.stop_reason = "completed" - break - - invalid_terminal_count += 1 - feedback = "terminal result must contain one registry category and approved grading level" - trace.events.append( - LoopEvent( - "retry", - state.turns, - {"reason": "invalid_terminal", "result": result}, - ) - ) - if recovering: - trace.stop_reason = "invalid_terminal" - break - if invalid_terminal_count > self.config.forced_finalize_retries: - trace.stop_reason = "invalid_terminal" - break - if forced: - trace.stop_reason = "budget_exhausted_no_result" - break - - if trace.stop_reason == "running": - trace.stop_reason = "budget_exhausted_no_result" - trace.turns = state.turns - trace.state = dict(state.named_state) - return trace - - -__all__ = [ - "ActionError", - "AgentLoopController", - "EarlyStopError", - "FixedPipelinePolicy", - "LoopConfig", - "LoopEvent", - "LoopPolicy", - "LoopState", - "PrefetchNeighborFieldsPolicy", - "PrefetchFieldMetadataPolicy", - "LoopTrace", - "POLICY_SYSTEM_PROMPT", - "PolicyDecision", - "ScriptedLoopPolicy", - "ScriptedSkillExecutor", - "SkillExecutor", - "build_final_evidence_state", - "build_policy_messages", - "derive_callable_skills", - "parse_policy_action", -] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/artifact_projection.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/artifact_projection.py deleted file mode 100644 index e2b1250..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/artifact_projection.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Project in-memory Agent Loop traces into label-isolated run artifacts.""" - -from __future__ import annotations - -from typing import Any, Mapping - - -def project_trace(row: Mapping[str, Any]) -> dict[str, Any]: - """Split one scored row into observation, model-log, trajectory, and evaluation views.""" - - source_id = row.get("source_id") - trace = row.get("trace") or {} - observations: list[dict[str, Any]] = [] - model_calls: list[dict[str, Any]] = [] - actions: list[dict[str, Any]] = [] - for event in trace.get("events", []): - if not isinstance(event, Mapping): - continue - kind = event.get("kind") - turn = event.get("turn") - data = event.get("data") or {} - if not isinstance(data, Mapping): - continue - if kind == "policy_action": - call = data.get("call") - if isinstance(call, Mapping): - actions.append({"turn": turn, "tool": call.get("tool"), - "arguments": dict(call.get("arguments") or {})}) - model_calls.append({ - "source_id": source_id, "turn": turn, "kind": "policy_action", - "skill": (call or {}).get("tool") if isinstance(call, Mapping) else None, - "messages": data.get("messages"), "raw_response": data.get("raw_response"), - "metadata": data.get("metadata") or {}, - }) - elif kind == "observation": - observations.append({ - "source_id": source_id, "turn": turn, "skill": data.get("skill"), - "status": data.get("status"), "summary": data.get("summary"), - "data": dict(data.get("data") or {}), - }) - metadata = data.get("metadata") or {} - if metadata: - model_calls.append({ - "source_id": source_id, "turn": turn, "kind": "skill_execution", - "skill": data.get("skill"), "metadata": dict(metadata), - }) - trajectory = { - "source_id": source_id, - "input": dict(trace.get("input") or {}), - "actions": actions, - "observations": [{key: value for key, value in item.items() if key != "source_id"} - for item in observations], - "final_result": trace.get("final_result"), - "stop_reason": trace.get("stop_reason"), - } - evaluation = { - "source_id": source_id, - "ground_truth": row.get("ground_truth"), - "ground_truth_level": row.get("ground_truth_level"), - "predicted_category": row.get("predicted_category"), - "predicted_level": row.get("predicted_level"), - "category_correct": row.get("category_correct"), - "level_correct": row.get("level_correct"), - "joint_correct": row.get("joint_correct"), - } - return {"observations": observations, "model_calls": model_calls, - "trajectory": trajectory, "evaluation": evaluation} diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/catalog.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/catalog.py deleted file mode 100644 index da77ce4..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/catalog.py +++ /dev/null @@ -1,105 +0,0 @@ -"""First-version Skill catalog used by the local planner/validator.""" - -from __future__ import annotations - -from dataclasses import dataclass -from typing import Mapping - - -@dataclass(frozen=True) -class SkillSpec: - name: str - role: str - required_inputs: tuple[str, ...] - optional_inputs: tuple[str, ...] = () - produces: tuple[str, ...] = () - max_calls: int = 1 - terminal: bool = False - - -def default_catalog() -> dict[str, SkillSpec]: - """Return a fresh ordered catalog for the first local experiment.""" - - specs = ( - SkillSpec("CHECK_METADATA_AVAILABILITY", "metadata_acquisition", ("current_record",), produces=("metadata_availability",)), - SkillSpec("GET_TABLE_FIELDS", "metadata_acquisition", ("table_name",), produces=("table_fields",)), - SkillSpec("SELECT_CONTEXT_FIELDS", "metadata_acquisition", ("target_field", "table_fields"), optional_inputs=("current_semantic_state",), produces=("selected_context_fields",)), - SkillSpec("INTERPRET_DOMAIN", "semantic_interpretation", ("domain",), produces=("domain_semantics",)), - SkillSpec("EXPAND_FIELD_ABBREVIATION", "semantic_interpretation", ("field_name",), optional_inputs=("domain",), produces=("field_abbreviation_semantics",)), - SkillSpec("INTERPRET_FIELD_NAME", "semantic_interpretation", ("field_name",), optional_inputs=("domain", "field_abbreviation_semantics"), produces=("field_semantics",)), - SkillSpec("DISAMBIGUATE_FIELD_SEMANTICS", "semantic_interpretation", ("field_semantics",), optional_inputs=("domain", "standard_candidates"), produces=("disambiguated_field_semantics",)), - SkillSpec("INTERPRET_FIELD_DESCRIPTION", "semantic_interpretation", ("field_description",), optional_inputs=("field_name", "domain"), produces=("field_description_semantics",)), - SkillSpec("INTERPRET_TABLE_NAME", "semantic_interpretation", ("table_name",), optional_inputs=("domain", "table_description"), produces=("table_semantics",)), - SkillSpec("INTERPRET_TABLE_DESCRIPTION", "semantic_interpretation", ("table_description",), optional_inputs=("table_name", "domain"), produces=("table_description_semantics",)), - SkillSpec("INTERPRET_CONTEXT_FIELDS", "semantic_interpretation", ("context_fields",), optional_inputs=("domain", "table_name"), produces=("context_field_semantics",)), - SkillSpec("SYNTHESIZE_METADATA_SEMANTICS", "semantic_interpretation", ("field_semantics",), optional_inputs=("domain_semantics", "table_semantics", "context_field_semantics", "field_description_semantics"), produces=("metadata_semantics",)), - SkillSpec("SEARCH_STANDARD", "standard_alignment", ("semantic_query",), produces=("standard_candidates",)), - SkillSpec("ALIGN_FIELD_TO_STANDARD", "standard_alignment", ("field_semantics", "standard_candidates"), produces=("field_standard_alignment",)), - SkillSpec("COMPARE_STANDARD_CANDIDATES", "standard_alignment", ("standard_candidates", "semantic_evidence"), produces=("standard_comparison", "aligned_standard_entry")), - SkillSpec("CHECK_EVIDENCE_SUFFICIENCY", "evidence_reasoning", ("current_evidence",), produces=("evidence_sufficiency",)), - SkillSpec("INFER_CATEGORY", "evidence_reasoning", ("candidate_standard_categories", "all_available_evidence"), produces=("category", "aligned_standard_entry")), - SkillSpec("INFER_GRADING_LEVEL", "evidence_reasoning", ("aligned_category", "aligned_standard_entry"), produces=("grading_level",)), - SkillSpec("FINALIZE_CLASSIFICATION", "evidence_reasoning", ("final_evidence_state",), produces=("final_result",), terminal=True), - ) - return {spec.name: spec for spec in specs} - - -DYNAMIC_LOOP_SKILLS = ( - "CHECK_METADATA_AVAILABILITY", - "INTERPRET_DOMAIN", - "EXPAND_FIELD_ABBREVIATION", - "INTERPRET_FIELD_NAME", - "DISAMBIGUATE_FIELD_SEMANTICS", - "SEARCH_STANDARD", - "COMPARE_STANDARD_CANDIDATES", - "CHECK_EVIDENCE_SUFFICIENCY", - "INFER_CATEGORY", - "INFER_GRADING_LEVEL", - "FINALIZE_CLASSIFICATION", -) - - -def dynamic_loop_catalog( - *, include_field_metadata: bool = False, - include_table_fields: bool = False, - include_description_skills: bool = False, - two_stage: bool = False, -) -> dict[str, SkillSpec]: - """Return the approved ordered Skill subset for the dynamic pilot.""" - - catalog = default_catalog() - names = tuple( - "SELECT_CATEGORY_TOPK" if name == "SEARCH_STANDARD" else - "INFER_CATEGORY_FROM_TOPK" if name == "INFER_CATEGORY" else name - for name in DYNAMIC_LOOP_SKILLS - ) if two_stage else DYNAMIC_LOOP_SKILLS - if two_stage: - catalog.update({ - "SELECT_CATEGORY_TOPK": SkillSpec( - "SELECT_CATEGORY_TOPK", "standard_alignment", ("semantic_query",), - produces=("standard_candidates",), - ), - "INFER_CATEGORY_FROM_TOPK": SkillSpec( - "INFER_CATEGORY_FROM_TOPK", "evidence_reasoning", - ("candidate_standard_categories", "all_available_evidence"), - produces=("category", "aligned_standard_entry"), - ), - }) - selected = {name: catalog[name] for name in names} - if include_field_metadata: - selected["GET_FIELD_METADATA"] = SkillSpec( - "GET_FIELD_METADATA", "metadata_acquisition", ("current_record",), - produces=("field_metadata",), - ) - if include_table_fields: - selected["GET_TABLE_FIELDS"] = SkillSpec( - "GET_TABLE_FIELDS", "metadata_acquisition", ("current_record",), - produces=("table_fields",), - ) - if include_description_skills: - for name in ("INTERPRET_FIELD_DESCRIPTION", "INTERPRET_TABLE_DESCRIPTION"): - selected[name] = catalog[name] - return selected - - -__all__ = ["DYNAMIC_LOOP_SKILLS", "SkillSpec", "default_catalog", "dynamic_loop_catalog"] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/category_catalog.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/category_catalog.py deleted file mode 100644 index 9696dd4..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/category_catalog.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Frozen Registry views with a strict label-only Top-K information boundary.""" - -from __future__ import annotations - -from typing import Any, Mapping, Sequence - - -class CategoryCatalog: - """Expose labels first and descriptions only for validated candidate IDs.""" - - def __init__(self, registry_entries: Mapping[str, Mapping[str, Any]]) -> None: - self._entries = {str(key): dict(value) for key, value in registry_entries.items()} - if not self._entries: - raise ValueError("category registry is empty") - width = max(3, len(str(len(self._entries)))) - self._option_to_category = { - f"C{index:0{width}d}": category - for index, category in enumerate(sorted(self._entries), start=1) - } - self._category_to_option = { - category: option_id for option_id, category in self._option_to_category.items() - } - - def selection_options(self) -> list[dict[str, str]]: - """Return stable short choices and full paths, without canonical IDs or details.""" - - labels = {entry["category"]: entry["label"] for entry in self.labels()} - return [ - {"option_id": option_id, "label": labels[category]} - for option_id, category in self._option_to_category.items() - ] - - def resolve_option_ids(self, option_ids: Sequence[str], k: int) -> tuple[str, ...]: - """Validate ranked model choices before translating to frozen category IDs.""" - - if k < 1 or k > len(self._entries): - raise ValueError("top_k must be between 1 and registry size") - if not isinstance(option_ids, (list, tuple)) or len(option_ids) != k: - raise ValueError(f"top_k result must contain exactly {k} option IDs") - if any(not isinstance(item, str) or item not in self._option_to_category - for item in option_ids): - raise ValueError("top_k result contains an unknown option ID") - if len(set(option_ids)) != len(option_ids): - raise ValueError("top_k result contains duplicate option IDs") - return tuple(self._option_to_category[item] for item in option_ids) - - def option_details(self, ids: Sequence[str]) -> list[dict[str, str]]: - """Expose descriptions only for selected choices, still without long IDs.""" - - return [ - { - "option_id": self._category_to_option[item["category"]], - "label": item["label"], - "description": item["description"], - } - for item in self.details(ids) - ] - - def labels(self) -> list[dict[str, str]]: - result: list[dict[str, str]] = [] - for category, entry in self._entries.items(): - path = entry.get("path") - if isinstance(path, (list, tuple)) and path: - label = " > ".join(str(part) for part in path) - else: - label = str(entry.get("label") or category.partition(":")[2] or entry.get("name") or category) - result.append({"category": category, "label": label}) - return result - - def validate_top_k(self, ids: Sequence[str], k: int) -> tuple[str, ...]: - if k < 1 or k > len(self._entries): - raise ValueError("top_k must be between 1 and registry size") - if not isinstance(ids, (list, tuple)) or len(ids) != k: - raise ValueError(f"top_k result must contain exactly {k} IDs") - if any(not isinstance(item, str) or item not in self._entries for item in ids): - raise ValueError("top_k result contains an unknown category ID") - if len(set(ids)) != len(ids): - raise ValueError("top_k result contains duplicate category IDs") - return tuple(ids) - - def details(self, ids: Sequence[str]) -> list[dict[str, str]]: - if not isinstance(ids, (list, tuple)) or not ids or len(set(ids)) != len(ids): - raise ValueError("candidate IDs must be a nonempty distinct list") - labels = {entry["category"]: entry["label"] for entry in self.labels()} - result: list[dict[str, str]] = [] - for category in ids: - if category not in self._entries: - raise ValueError(f"unknown category ID: {category}") - entry = self._entries[category] - result.append({ - "category": category, - "label": labels[category], - "description": str(entry.get("description") or entry.get("definition") or ""), - }) - return result - - def frozen_entry(self, category: str) -> dict[str, Any]: - if category not in self._entries: - raise ValueError(f"unknown category ID: {category}") - return {"category": category, **self._entries[category]} diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/contracts.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/contracts.py deleted file mode 100644 index d7634ae..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/contracts.py +++ /dev/null @@ -1,120 +0,0 @@ -"""JSON-compatible contracts for the DSL orchestration layer.""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any, Mapping - - -OPTIONAL_METADATA_FIELDS = ( - "database_name", - "database_description", - "table_name", - "table_description", - "field_description", - "field_type", - "value", -) - - -def _text(value: Any) -> str: - return "" if value is None else str(value).strip() - - -@dataclass(frozen=True) -class MetadataRecord: - """One classification instance with required and optional metadata.""" - - domain: str - field_name: str - metadata: Mapping[str, Any] = field(default_factory=dict) - source_id: str | None = None - - @classmethod - def from_mapping(cls, raw: Mapping[str, Any]) -> "MetadataRecord": - nested = raw.get("metadata") - nested_metadata = dict(nested) if isinstance(nested, Mapping) else {} - merged = dict(nested_metadata) - for key in ("field_name", *OPTIONAL_METADATA_FIELDS): - if key in raw and raw[key] is not None: - merged[key] = raw[key] - - domain = _text(raw.get("domain", merged.pop("domain", None))) - field_name = _text(merged.get("field_name")) - if not domain: - raise ValueError("domain is required and must be non-empty") - if not field_name: - raise ValueError("field_name is required and must be non-empty") - merged["field_name"] = field_name - return cls( - domain=domain, - field_name=field_name, - metadata=merged, - source_id=_text(raw.get("source_id")) or None, - ) - - def get(self, name: str, default: Any = None) -> Any: - if name == "domain": - return self.domain - if name == "field_name": - return self.field_name - return self.metadata.get(name, default) - - def available(self, name: str) -> bool: - value = self.get(name) - return bool(_text(value)) - - def to_dict(self) -> dict[str, Any]: - result: dict[str, Any] = {"domain": self.domain, "metadata": dict(self.metadata)} - if self.source_id: - result["source_id"] = self.source_id - return result - - -@dataclass(frozen=True) -class ToolCall: - tool: str - arguments: Mapping[str, Any] = field(default_factory=dict) - - @classmethod - def from_mapping(cls, raw: Mapping[str, Any]) -> "ToolCall": - tool = _text(raw.get("tool")) - if not tool: - raise ValueError("tool is required and must be non-empty") - arguments = raw.get("arguments", {}) - if not isinstance(arguments, Mapping): - raise ValueError("arguments must be an object") - return cls(tool=tool, arguments=dict(arguments)) - - def to_dict(self) -> dict[str, Any]: - return {"tool": self.tool, "arguments": dict(self.arguments)} - - -@dataclass(frozen=True) -class Program: - steps: tuple[ToolCall, ...] - - @classmethod - def from_mapping(cls, raw: Mapping[str, Any]) -> "Program": - steps = raw.get("program") - if not isinstance(steps, list): - raise ValueError("program must be a list") - return cls(steps=tuple(ToolCall.from_mapping(item) for item in steps)) - - def to_dict(self) -> dict[str, Any]: - return {"program": [step.to_dict() for step in self.steps]} - - -@dataclass(frozen=True) -class StandardEntry: - category: str - description: str - grading_level: str - - def to_dict(self) -> dict[str, str]: - return { - "category": self.category, - "description": self.description, - "grading_level": self.grading_level, - } - diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metadata_lookup.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metadata_lookup.py deleted file mode 100644 index 7de1ab4..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metadata_lookup.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Label-isolated lookup of real field metadata for an explicit DSL call.""" - -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any, Mapping - -from .contracts import MetadataRecord - - -RETRIEVABLE_FIELDS = ( - "database_name", "table_name", "field_description", "table_description" -) - - -class FieldMetadataLookup: - def __init__(self, rows: Mapping[str, Mapping[str, Any]]) -> None: - self._rows = {key: dict(value) for key, value in rows.items()} - - @classmethod - def from_canonical(cls, source: str | Path) -> "FieldMetadataLookup": - raw = json.loads(Path(source).read_text(encoding="utf-8")) - if not isinstance(raw, list): - raise ValueError("canonical source must be a list") - projected: dict[str, dict[str, Any]] = {} - for row in raw: - if not isinstance(row, Mapping): - raise ValueError("canonical row must be an object") - source_id = row.get("id") - if not isinstance(source_id, str) or not source_id: - raise ValueError("canonical row must have id") - if source_id in projected: - raise ValueError(f"duplicate source id: {source_id}") - metadata = row.get("metadata") - if not isinstance(metadata, Mapping): - raise ValueError(f"canonical metadata missing for {source_id}") - projected[source_id] = { - "domain": row.get("domain"), - "field_name": metadata.get("field_name"), - "fields": { - key: str(metadata[key]).strip() - for key in RETRIEVABLE_FIELDS - if metadata.get(key) not in (None, "") - and str(metadata[key]).strip().casefold() not in ('', 'none', 'null', 'n/a') - }, - } - return cls(projected) - - def get(self, record: MetadataRecord) -> dict[str, str]: - if not record.source_id or record.source_id not in self._rows: - raise ValueError("source id is absent from metadata lookup") - entry = self._rows[record.source_id] - if entry["domain"] != record.domain or entry["field_name"] != record.field_name: - raise ValueError("lookup source does not match domain and field_name") - return dict(entry["fields"]) diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metrics.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metrics.py deleted file mode 100644 index d3ba05b..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/metrics.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Auditable metrics for local Program execution traces.""" - -from __future__ import annotations - -from collections import Counter -from typing import Any, Iterable - -from .runtime import ExecutionTrace, Observation - - -def _value(item: Observation | dict[str, Any], key: str, default: Any = None) -> Any: - if isinstance(item, Observation): - return getattr(item, key, default) - return item.get(key, default) - - -def summarize_trace(trace: ExecutionTrace) -> dict[str, Any]: - names = [_value(item, "skill", "") for item in trace.observations] - statuses = [_value(item, "status", "error") for item in trace.observations] - counts = Counter(names) - return { - "tool_calls": len(names), - "successful_tool_calls": sum(status == "success" for status in statuses), - "failed_tool_calls": sum(status != "success" for status in statuses), - "tool_call_success_rate": (sum(status == "success" for status in statuses) / len(statuses)) if statuses else 1.0, - "program_length": len(names), - "duplicate_calls": sum(max(count - 1, 0) for count in counts.values()), - "terminated": bool(trace.terminated), - "final_result_valid": isinstance(trace.final_result, dict) and bool(trace.final_result), - } - - -def summarize_traces(traces: Iterable[ExecutionTrace]) -> dict[str, Any]: - rows = [summarize_trace(trace) for trace in traces] - count = len(rows) - calls = sum(row["tool_calls"] for row in rows) - successful = sum(row["successful_tool_calls"] for row in rows) - return { - "traces": count, - "termination_rate": (sum(row["terminated"] for row in rows) / count) if count else 0.0, - "average_program_length": (sum(row["program_length"] for row in rows) / count) if count else 0.0, - "tool_call_success_rate": (successful / calls) if calls else 1.0, - "average_duplicate_calls": (sum(row["duplicate_calls"] for row in rows) / count) if count else 0.0, - } - - -__all__ = ["summarize_trace", "summarize_traces"] - diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/model_skill_executor.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/model_skill_executor.py deleted file mode 100644 index 8df1c1d..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/model_skill_executor.py +++ /dev/null @@ -1,828 +0,0 @@ -"""Model-independent adapters for policy generation and semantic Skill execution.""" - -from __future__ import annotations - -import json -from dataclasses import replace -from json import JSONDecodeError -from pathlib import Path -from typing import Any, Callable, Mapping, Sequence - -from .agent_loop import ( - ActionError, - LoopState, - PolicyDecision, - _two_stage_evidence, - build_policy_messages, - parse_policy_action, -) -from .catalog import SkillSpec -from .contracts import OPTIONAL_METADATA_FIELDS, MetadataRecord, ToolCall -from .metadata_lookup import FieldMetadataLookup -from .table_field_lookup import TableFieldLookup -from .category_catalog import CategoryCatalog -from .runtime import KnowledgeBase, Observation -from .skill_loader import SkillContract, SkillLoader -from .validator import resolve_reference -from .topk_selection import SELECTION_POLICY, aggregate_rankings, balanced_options, ranking_scores - - -TextGenerator = Callable[[list[dict[str, str]]], str] -DeterministicHandler = Callable[[ToolCall, MetadataRecord, Mapping[str, Any]], Observation] - - -def _generation_metadata(generate: TextGenerator) -> dict[str, Any]: - metadata = getattr(generate, "last_generation_metadata", None) - return dict(metadata) if isinstance(metadata, Mapping) else {} - - -def _attempt_metadata(attempts: Sequence[Mapping[str, Any]]) -> dict[str, Any]: - """Keep every Skill generation while preserving the existing aggregate fields.""" - - last = attempts[-1] - metadata: dict[str, Any] = { - "attempts": [dict(item) for item in attempts], - "model_call_count": len(attempts), - "messages": last["messages"], - "raw_response": last.get("raw_response"), - } - generations = [item.get("generation", {}) for item in attempts] - usages = [item.get("token_usage") for item in generations if isinstance(item, Mapping)] - if any(isinstance(item, Mapping) for item in usages): - metadata["token_usage"] = { - key: sum(int(item.get(key) or 0) for item in usages if isinstance(item, Mapping)) - for key in ("prompt_tokens", "completion_tokens", "total_tokens") - } - elapsed = [item.get("elapsed_seconds") for item in generations if isinstance(item, Mapping)] - if any(isinstance(item, (int, float)) for item in elapsed): - metadata["elapsed_seconds"] = sum( - float(item) for item in elapsed if isinstance(item, (int, float)) - ) - return metadata - - -class SkillExecutionError(ValueError): - """Raised when a Skill cannot produce one valid Observation.""" - - def __init__(self, message: str, *, metadata: Mapping[str, Any] | None = None) -> None: - super().__init__(message) - self.metadata = dict(metadata or {}) - - -def metadata_availability_handler( - call: ToolCall, - record: MetadataRecord, - resolved: Mapping[str, Any], -) -> Observation: - """Report availability from the projected, model-visible record only.""" - - del resolved - available = [name for name in ("domain", "field_name") if record.available(name)] - missing = [name for name in OPTIONAL_METADATA_FIELDS if not record.available(name)] - return Observation( - call.tool, - "success", - f"Available metadata: {', '.join(available)}; missing: {', '.join(missing)}", - {"metadata_availability": {"available": available, "missing": missing}}, - ) - - -def make_standard_search_handler( - knowledge_base: KnowledgeBase, - *, - top_k: int = 5, -) -> DeterministicHandler: - """Create a frozen-registry Top-K retrieval handler.""" - - if top_k < 1: - raise ValueError("top_k must be positive") - - def handler( - call: ToolCall, - record: MetadataRecord, - resolved: Mapping[str, Any], - ) -> Observation: - del record - query = resolved.get("semantic_query") - candidates = knowledge_base.search_standard(query, top_k=top_k) - return Observation( - call.tool, - "success", - f"Retrieved {len(candidates)} standard candidates", - {"standard_candidates": candidates}, - ) - - return handler - - -def make_field_metadata_handler(lookup: FieldMetadataLookup) -> DeterministicHandler: - """Expose only allowlisted source metadata when the Agent invokes this Skill.""" - - def handler( - call: ToolCall, - record: MetadataRecord, - resolved: Mapping[str, Any], - ) -> Observation: - del resolved - fields = lookup.get(record) - return Observation( - call.tool, - "success", - f"Retrieved {len(fields)} approved metadata fields", - {"field_metadata": fields}, - ) - - return handler - - -def make_table_fields_handler(lookup: TableFieldLookup) -> DeterministicHandler: - """Expose bounded, label-free same-table fields only on an explicit call.""" - - def handler( - call: ToolCall, - record: MetadataRecord, - resolved: Mapping[str, Any], - ) -> Observation: - del resolved - fields = lookup.get(record) - return Observation( - call.tool, - "success", - f"Retrieved {len(fields['fields'])} of {fields['available_count']} neighboring fields", - {"table_fields": fields}, - ) - - return handler - - -def _decode_observation_object(text: str) -> Mapping[str, Any]: - if not isinstance(text, str) or not text.strip(): - raise SkillExecutionError("Skill response must be non-empty JSON") - cleaned = text.strip() - if cleaned.startswith("```"): - lines = cleaned.splitlines()[1:] - if lines and lines[-1].strip() == "```": - lines.pop() - cleaned = "\n".join(lines).strip() - if not cleaned.startswith("{"): - raise SkillExecutionError("Skill response must be one JSON object") - decoder = json.JSONDecoder() - try: - value, end = decoder.raw_decode(cleaned) - except JSONDecodeError as exc: - raise SkillExecutionError(f"Skill response is invalid JSON: {exc.msg}") from exc - if cleaned[end:].strip(): - raise SkillExecutionError("Skill response contains trailing content") - if not isinstance(value, Mapping): - raise SkillExecutionError("Skill response must be a JSON object") - return value - - -def parse_skill_observation(text: str, spec: SkillSpec) -> Observation: - """Parse one strict success Observation for the selected Skill.""" - - payload = _decode_observation_object(text) - if set(payload) != {"summary", "data"}: - raise SkillExecutionError("Skill response must contain exactly summary and data") - summary = payload.get("summary") - data = payload.get("data") - if not isinstance(summary, str) or not summary.strip(): - raise SkillExecutionError("Skill summary must be a non-empty string") - if not isinstance(data, Mapping): - raise SkillExecutionError("Skill data must be an object") - expected = set(spec.produces) - actual = set(data) - missing = sorted(expected - actual) - if missing: - raise SkillExecutionError(f"missing produced keys: {missing}") - extra = sorted(actual - expected) - if extra: - raise SkillExecutionError(f"unexpected produced keys: {extra}") - empty = sorted( - key - for key in expected - if data.get(key) is None or data.get(key) == "" - ) - if empty: - raise SkillExecutionError(f"produced keys must be non-empty: {empty}") - return Observation(spec.name, "success", summary.strip(), dict(data)) - - -def load_few_shot_messages(path: str | Path) -> tuple[dict[str, str], ...]: - """Load synthetic policy examples while rejecting evaluation-label leakage.""" - - source = Path(path) - payload = json.loads(source.read_text(encoding="utf-8")) - if not isinstance(payload, list) or not payload: - raise ValueError("few-shot file must contain a non-empty JSON list") - messages: list[dict[str, str]] = [] - forbidden = ("ground_truth", "ground truth", "source_id", "source id") - for index, item in enumerate(payload): - if not isinstance(item, Mapping) or set(item) != {"role", "content"}: - raise ValueError(f"few-shot message {index} must contain exactly role and content") - role = item.get("role") - content = item.get("content") - if role not in {"user", "assistant"} or not isinstance(content, str) or not content: - raise ValueError(f"few-shot message {index} has an invalid role or content") - lowered = content.lower() - if any(marker in lowered for marker in forbidden): - raise ValueError("few-shot examples must not contain ground-truth or source identifiers") - messages.append({"role": role, "content": content}) - return tuple(messages) - - -class ModelLoopPolicy: - """Adapt a text generator to the one-action dynamic policy contract.""" - - def __init__( - self, - generate: TextGenerator, - *, - few_shot_messages: Sequence[Mapping[str, str]] = (), - metadata_guidance: bool = False, - two_stage: bool = False, - description_skills: bool = False, - ) -> None: - self.generate = generate - self.few_shot_messages = tuple(dict(message) for message in few_shot_messages) - self.metadata_guidance = metadata_guidance - self.two_stage = two_stage - self.description_skills = description_skills - - def select_action( - self, - record: MetadataRecord, - state: LoopState, - callable_skills: Mapping[str, SkillSpec], - *, - feedback: str | None = None, - forced_finalize: bool = False, - ) -> PolicyDecision: - messages = build_policy_messages( - record, - state, - callable_skills, - feedback=feedback, - forced_finalize=forced_finalize, - ) - if self.two_stage: - messages[0]["content"] += ( - "\nUse only a Skill listed in callable_skills for this turn; " - "never call SELECT_CATEGORY_TOPK before it is callable. " - "If semantic evidence is absent, first call INTERPRET_FIELD_NAME " - "with field_name=$metadata.field_name or another callable semantic Skill. " - "When SELECT_CATEGORY_TOPK becomes callable, provide semantic_query=" - "$state.field_semantics if present, otherwise a different existing " - "$state.; never omit required arguments. " - "Then call INFER_CATEGORY_FROM_TOPK with candidate_standard_categories=" - "$state.standard_candidates and all_available_evidence=" - "$state.available_evidence; bare $state is invalid. " - "Only grade after selecting one category." - ) - if self.metadata_guidance: - messages[0]["content"] += ( - " If GET_FIELD_METADATA is callable and field_metadata is absent, " - "call it before category selection." - ) - if "table_fields" not in state.named_state: - if self.description_skills: - messages[0]["content"] += ( - " Once real field_metadata is available, if " - "INTERPRET_FIELD_DESCRIPTION is callable and " - "field_description_semantics is absent, call " - "INTERPRET_FIELD_DESCRIPTION before SELECT_CATEGORY_TOPK " - "with field_description=$state.field_description. " - "If no field description exists but " - "INTERPRET_TABLE_DESCRIPTION is callable, use its real " - "table_description instead. After interpretation, pass " - "semantic_query=$state.available_evidence to " - "SELECT_CATEGORY_TOPK and pass " - "all_available_evidence=$state.available_evidence to Top-1. " - "If neither description is available, use " - "semantic_query=$state.field_metadata." - ) - else: - messages[0]["content"] += ( - " Once field_metadata is available, pass semantic_query=" - "$state.field_metadata to SELECT_CATEGORY_TOPK and pass " - "$state.field_metadata to INFER_CATEGORY_FROM_TOPK." - ) - if "GET_TABLE_FIELDS" in callable_skills and "table_fields" not in state.named_state: - messages[0]["content"] += ( - " If the current field and table metadata leave the business " - "category ambiguous, you may call GET_TABLE_FIELDS with " - "current_record=$record before category selection; this is optional." - ) - if "table_fields" in state.named_state: - messages[0]["content"] += ( - " Neighboring table_fields are available. To use both target " - "metadata and neighbors in category selection, pass semantic_query=" - "$state.available_evidence to SELECT_CATEGORY_TOPK and " - "all_available_evidence=$state.available_evidence to " - "INFER_CATEGORY_FROM_TOPK." - ) - if self.metadata_guidance: - messages[0]["content"] += ( - " Finish grading and finalization without repeating diagnostic Skills." - ) - if self.description_skills and "field_metadata" in state.named_state: - messages[0]["content"] += ( - " Real descriptions in field_metadata may be interpreted through " - "INTERPRET_FIELD_DESCRIPTION or INTERPRET_TABLE_DESCRIPTION only " - "when these Skills appear in callable_skills. They are optional: " - "do not call a missing-description Skill or repeat one. " - "If description semantics were produced, use " - "semantic_query=$state.available_evidence for SELECT_CATEGORY_TOPK " - "and all_available_evidence=$state.available_evidence for Top-1." - ) - elif self.metadata_guidance: - messages[0]["content"] += ( - "\nIf GET_FIELD_METADATA is callable and field_metadata is absent, " - "call GET_FIELD_METADATA before semantic interpretation or retrieval. " - "When real field_metadata has been obtained and standard_candidates " - "are absent, call SEARCH_STANDARD with " - "{\"semantic_query\":\"$state.field_metadata\"}; do not search only " - "the guessed field_semantics. Once candidates are available, " - "proceed toward category, level, and finalization without " - "repeating diagnostic Skills." - ) - if self.few_shot_messages: - messages[1:1] = [dict(message) for message in self.few_shot_messages] - try: - raw = self.generate(messages) - except Exception as exc: # pragma: no cover - backend-specific - error = ActionError(f"policy generator failed: {exc}") - error.metadata = {"messages": messages, "raw_response": None, - "error": str(exc), "generation": _generation_metadata(self.generate)} - raise error from exc - if not isinstance(raw, str): - raise ActionError("policy generator must return a string") - try: - parsed = parse_policy_action(raw) - except ActionError as exc: - exc.metadata = {"messages": messages, "raw_response": raw, - "generation": _generation_metadata(self.generate)} - raise - return PolicyDecision( - call=parsed, - raw_response=raw, - messages=tuple(messages), - metadata=_generation_metadata(self.generate), - ) - - -class ModelSkillExecutor: - """Execute deterministic tools or one selected Markdown Skill via a generator.""" - - def __init__( - self, - generate: TextGenerator, - loader: SkillLoader, - *, - deterministic_handlers: Mapping[str, DeterministicHandler] | None = None, - category_catalog: CategoryCatalog | None = None, - top_k: int = 5, - guard_two_stage_evidence: bool = False, - topk_evidence_mode: str = "augmented", - topk_selection_mode: str = "single", - topk_selection_seed: int = 20260930, - top1_evidence_mode: str = "all", - top1_selection_mode: str = "model", - evidence_assembly=None, - ) -> None: - if top1_evidence_mode not in {"all", "raw"}: - raise ValueError("top1_evidence_mode must be all or raw") - if top1_selection_mode not in {"model", "first"}: - raise ValueError("top1_selection_mode must be model or first") - self.top1_evidence_mode = top1_evidence_mode - self.top1_selection_mode = top1_selection_mode - if topk_evidence_mode not in {"augmented", "raw", "raw-flat"}: - raise ValueError("topk_evidence_mode must be augmented, raw or raw-flat") - if topk_selection_mode not in {"single", "balanced-vote"}: - raise ValueError("topk_selection_mode must be single or balanced-vote") - if topk_selection_mode == "balanced-vote" and category_catalog is None: - raise ValueError("balanced-vote requires a two-stage category catalog") - self.generate = generate - self.loader = loader - self.category_catalog = category_catalog - self.top_k = top_k - self.guard_two_stage_evidence = guard_two_stage_evidence - self.evidence_assembly = evidence_assembly - self.topk_evidence_mode = topk_evidence_mode - self.topk_selection_mode = topk_selection_mode - self.topk_selection_seed = topk_selection_seed - self.deterministic_handlers = { - "CHECK_METADATA_AVAILABILITY": metadata_availability_handler, - **dict(deterministic_handlers or {}), - } - - @staticmethod - def _resolved_arguments( - call: ToolCall, - record: MetadataRecord, - state: Mapping[str, Any], - ) -> dict[str, Any]: - resolved: dict[str, Any] = {} - for name, value in call.arguments.items(): - found, result = resolve_reference(value, record, state) - if not found: - raise SkillExecutionError(f"argument {name!r} cannot be resolved") - resolved[name] = result - return resolved - - @staticmethod - def _messages(contract: SkillContract, resolved: Mapping[str, Any]) -> list[dict[str, str]]: - system = ( - f"Execute only the selected Skill {contract.name}.\n" - f"DSL: {contract.dsl}\n" - f"Contract:\n{contract.body}\n" - "Use only the resolved inputs. Return exactly one JSON object with summary and data." - ) - payload = { - "skill": contract.name, - "resolved_inputs": dict(resolved), - "output_schema": { - "summary": "non-empty natural-language observation", - "data": {name: "required output" for name in contract.produces}, - }, - } - return [ - {"role": "system", "content": system}, - {"role": "user", "content": json.dumps(payload, ensure_ascii=False, indent=2)}, - ] - - @staticmethod - def _validate_deterministic(observation: Observation, spec: SkillSpec) -> Observation: - if observation.skill != spec.name: - raise SkillExecutionError( - f"deterministic handler returned Skill {observation.skill!r}, expected {spec.name!r}" - ) - if observation.status != "success": - return observation - actual = set(observation.data) - expected = set(spec.produces) - if actual != expected: - raise SkillExecutionError( - f"deterministic handler output keys {sorted(actual)} do not match {sorted(expected)}" - ) - return observation - - def execute( - self, - call: ToolCall, - record: MetadataRecord, - state: Mapping[str, Any], - contract: SkillContract, - ) -> Observation: - loaded = self.loader.load(call.tool) - if loaded != contract: - raise SkillExecutionError(f"contract mismatch for {call.tool}") - spec = self.loader.catalog[call.tool] - resolved = self._resolved_arguments(call, record, state) - if call.tool in {"SELECT_CATEGORY_TOPK", "INFER_CATEGORY_FROM_TOPK"}: - try: - return self._execute_two_stage(call, record, resolved, state, contract) - except SkillExecutionError as exc: - if call.tool == "INFER_CATEGORY_FROM_TOPK": - exc.metadata.update(top1_selection_mode=self.top1_selection_mode, - top1_evidence_mode=self.top1_evidence_mode) - raise - if call.tool == "FINALIZE_CLASSIFICATION" and self.guard_two_stage_evidence: - return self._finalize_guarded_two_stage(call, resolved, state) - handler = self.deterministic_handlers.get(call.tool) - if handler is not None: - return self._validate_deterministic(handler(call, record, resolved), spec) - - messages = self._messages(contract, resolved) - try: - raw = self.generate(messages) - except Exception as exc: # pragma: no cover - backend-specific - raise SkillExecutionError(f"Skill generator failed: {exc}", metadata={ - "messages": messages, "raw_response": None, "error": str(exc), - "generation": _generation_metadata(self.generate)}) from exc - if not isinstance(raw, str): - raise SkillExecutionError("Skill generator must return a string") - try: - observation = parse_skill_observation(raw, spec) - except SkillExecutionError as exc: - exc.metadata = {"messages": messages, "raw_response": raw, - "generation": _generation_metadata(self.generate)} - raise - return replace( - observation, - metadata={ - "messages": messages, - "raw_response": raw, - **_generation_metadata(self.generate), - }, - ) - - def _finalize_guarded_two_stage( - self, - call: ToolCall, - resolved: Mapping[str, Any], - state: Mapping[str, Any], - ) -> Observation: - if self.category_catalog is None: - raise SkillExecutionError("two-stage category catalog is not configured") - evidence = resolved.get("final_evidence_state") - if not isinstance(evidence, Mapping) or evidence != state.get("final_evidence_state"): - raise SkillExecutionError("finalizer must consume the frozen final evidence state") - category = evidence.get("category") - level = evidence.get("grading_level") - aligned = evidence.get("aligned_standard_entry") - candidates = evidence.get("standard_candidates") - if not isinstance(category, str) or not isinstance(level, str): - raise SkillExecutionError("final evidence is missing category or grading level") - if category != state.get("category") or level != state.get("grading_level"): - raise SkillExecutionError("final evidence differs from the selected category or level") - if ( - not isinstance(aligned, Mapping) - or (aligned.get("category") or aligned.get("category_id")) != category - or aligned.get("grading_level") != level - ): - raise SkillExecutionError("final evidence disagrees with the aligned entry") - if not isinstance(candidates, list) or not any( - isinstance(item, Mapping) - and (item.get("category") or item.get("category_id")) == category - for item in candidates - ): - raise SkillExecutionError("selected category is absent from frozen Top-K") - try: - registry_entry = self.category_catalog.frozen_entry(category) - except ValueError as exc: - raise SkillExecutionError(str(exc)) from exc - if registry_entry.get("grading_level") != level: - raise SkillExecutionError("selected level disagrees with frozen Registry") - return Observation( - call.tool, - "success", - "Bound final result to the selected category and frozen grading level", - {"final_result": {"category": category, "grading_level": level}}, - metadata={"controller_bound_terminal": True}, - ) - - def _execute_two_stage( - self, - call: ToolCall, - record: MetadataRecord, - resolved: Mapping[str, Any], - state: Mapping[str, Any], - contract: SkillContract, - ) -> Observation: - if self.category_catalog is None: - raise SkillExecutionError("two-stage category catalog is not configured") - evidence_assembled = ( - self.guard_two_stage_evidence - and call.tool == "SELECT_CATEGORY_TOPK" - and isinstance(state.get("field_metadata"), Mapping) - ) - if call.tool == "SELECT_CATEGORY_TOPK": - if evidence_assembled and self.evidence_assembly is None: - semantic_query = _two_stage_evidence(record, state) - if self.topk_evidence_mode == "raw": - semantic_query["observations"] = { - "field_metadata": state["field_metadata"], - } - elif self.topk_evidence_mode == "raw-flat": - semantic_query = { - **state["field_metadata"], - "domain": record.domain, "field_name": record.field_name, - } - else: - semantic_query = resolved["semantic_query"] - prompt_input = { - "record_input": {"domain": record.domain, "field_name": record.field_name}, - "semantic_query": semantic_query, - "top_k": self.top_k, - "category_options": self.category_catalog.selection_options(), - } - if self.evidence_assembly is not None: - # Opt-in pool callers preserve the selected native query and share the - # same validated publication/final evidence boundary. - prompt_input["available_evidence"] = self.evidence_assembly(record, state) - output_rule = ( - 'Return exactly one JSON object: {"option_ids":["C001",...],' - f'"summary":"reason"}}. The list MUST contain exactly {self.top_k} distinct ' - f'option IDs from category_options, ranked best first. If fewer than {self.top_k} ' - 'are strong matches, include weaker but plausible supplied options to fill every slot. ' - 'Copy the short option_id exactly. Do not output long category paths, canonical ' - 'category IDs, duplicates, invented option IDs, or a different top-N. ' - 'Limit summary to one short phrase (at most 20 characters); do not put ' - 'quotation marks, line breaks, or a long explanation inside summary. ' - 'Close the summary string and the JSON object.' - ) - else: - prior = state.get("standard_candidates") - supplied = resolved.get("candidate_standard_categories") - if not isinstance(prior, list) or supplied != prior: - raise SkillExecutionError("Top-1 must consume the actual prior Top-K observation") - if len(prior) != self.top_k or any(not isinstance(item, Mapping) for item in prior): - raise SkillExecutionError("Top-1 requires exactly top_k candidate objects") - ids = [item.get("category") for item in prior if isinstance(item, Mapping)] - try: - self.category_catalog.validate_top_k(ids, self.top_k) - details = self.category_catalog.option_details(ids) - except ValueError as exc: - raise SkillExecutionError(str(exc)) from exc - if self.top1_selection_mode == "first": - category = ids[0] - return Observation(call.tool, "success", "Selected actual first frozen candidate", - {"category": category, "aligned_standard_entry": self.category_catalog.frozen_entry(category)}, - metadata={"top1_selection_mode": "first", "top1_evidence_mode": self.top1_evidence_mode, - "controller_bound_selection": True, "model_call_count": 0, "attempts": []}) - evidence = resolved["all_available_evidence"] - if self.top1_evidence_mode == "raw": - evidence = {"domain": record.domain, "field_name": record.field_name, - "observations": {"field_metadata": dict(state["field_metadata"])} - if isinstance(state.get("field_metadata"), Mapping) else {}} - prompt_input = { - "all_available_evidence": evidence, - "candidate_details": details, - } - if self.evidence_assembly is not None: - prompt_input["available_evidence"] = self.evidence_assembly(record, state) - output_rule = ( - 'Return exactly one JSON object: {"option_id":"one supplied short option ID",' - '"summary":"reason"}. Do not choose outside candidate_details. ' - 'Limit summary to one short phrase (at most 20 characters); do not put ' - 'quotation marks, line breaks, or a long explanation inside summary. ' - 'Close the summary string and the JSON object.' - ) - messages = [ - {"role": "system", "content": f"Execute only the selected Skill {contract.name}.\n{contract.body}\n{output_rule}"}, - {"role": "user", "content": json.dumps(prompt_input, ensure_ascii=False, indent=2)}, - ] - if call.tool == "SELECT_CATEGORY_TOPK" and self.topk_selection_mode == "balanced-vote": - return self._execute_balanced_topk(record, prompt_input, messages[0], evidence_assembled) - attempts: list[dict[str, Any]] = [] - max_attempts = 2 - for attempt_index in range(max_attempts): - try: - raw = self.generate(messages) - except Exception as exc: - attempts.append({"messages": messages, "raw_response": None, "error": str(exc), - "generation": _generation_metadata(self.generate)}) - raise SkillExecutionError( - f"two-stage Skill generator failed: {exc}", - metadata=_attempt_metadata(attempts), - ) from exc - generation = _generation_metadata(self.generate) - try: - payload = _decode_observation_object(raw) - summary = payload.get("summary") - if not isinstance(summary, str) or not summary.strip(): - raise SkillExecutionError("two-stage Skill requires a nonempty summary") - if call.tool == "SELECT_CATEGORY_TOPK": - if set(payload) != {"option_ids", "summary"}: - raise SkillExecutionError("Top-K response must contain option_ids and summary only") - canonical_ids = self.category_catalog.resolve_option_ids( - payload["option_ids"], self.top_k - ) - label_map = {item["category"]: item for item in self.category_catalog.labels()} - data = {"standard_candidates": [label_map[item] for item in canonical_ids]} - else: - if set(payload) != {"option_id", "summary"}: - raise SkillExecutionError("Top-1 response must contain option_id and summary only") - category = self.category_catalog.resolve_option_ids([payload["option_id"]], 1)[0] - if category not in ids: - raise SkillExecutionError("Top-1 category is outside prior Top-K") - data = {"category": category, "aligned_standard_entry": self.category_catalog.frozen_entry(category)} - except (SkillExecutionError, ValueError, TypeError, KeyError) as exc: - error = str(exc) - attempts.append({"messages": messages, "raw_response": raw, - "error": error, "generation": generation}) - if attempt_index + 1 < max_attempts: - if call.tool == "SELECT_CATEGORY_TOPK": - feedback = ( - f"Your Top-K response failed validation: {error}. " - f"Return a complete new JSON object with exactly {self.top_k} " - "distinct option IDs copied from category_options. " - "Use option_ids and summary only; never use canonical paths or IDs. " - "Keep summary to one short phrase and close the JSON object." - ) - else: - feedback = ( - f"Your Top-1 response failed validation: {error}. " - "Return one complete JSON object with option_id copied from " - "candidate_details and a brief summary. Close the object with " - "a closing brace }. Keep summary to one short phrase. " - "Do not use any option outside candidate_details." - ) - messages = [ - *messages, - {"role": "assistant", "content": raw if isinstance(raw, str) else ""}, - {"role": "user", "content": feedback}, - ] - continue - raise SkillExecutionError( - f"invalid two-stage Skill response: {error}", - metadata=_attempt_metadata(attempts), - ) from exc - attempts.append({"messages": messages, "raw_response": raw, - "generation": generation}) - metadata = _attempt_metadata(attempts) - if call.tool == "INFER_CATEGORY_FROM_TOPK": - metadata.update({"top1_evidence_mode": self.top1_evidence_mode, - "top1_selection_mode": self.top1_selection_mode}) - if evidence_assembled: - metadata["controller_evidence_assembled"] = True - metadata["topk_evidence_mode"] = self.topk_evidence_mode - return Observation(call.tool, "success", summary.strip(), data, - metadata=metadata) - raise AssertionError("unreachable") - - def _execute_balanced_topk( - self, record: MetadataRecord, prompt_input: Mapping[str, Any], - system_message: Mapping[str, str], evidence_assembled: bool, - ) -> Observation: - """Make exactly three independent calls, retaining failures without retry.""" - assert self.category_catalog is not None - attempts: list[dict[str, Any]] = [] - rankings: list[list[str]] = [] - options = prompt_input["category_options"] - allowed = [item["option_id"] for item in options] - for index, presented in enumerate(balanced_options( - options, record.domain, record.field_name, self.topk_selection_seed - ), start=1): - messages = [dict(system_message), { - "role": "user", "content": json.dumps( - {**prompt_input, "category_options": presented}, ensure_ascii=False, indent=2 - ), - }] - attempt: dict[str, Any] = { - "round": index, "presented_option_ids": [item["option_id"] for item in presented], - "valid": False, "error": None, "raw_response": None, - "messages": messages, "generation": {}, - } - # Most generators keep a last-call attribute. Clear it before this call - # so a failing backend cannot be charged for the previous completion. - metadata_cleared = False - try: - if hasattr(self.generate, "last_generation_metadata"): - self.generate.last_generation_metadata = {} - metadata_cleared = True - except (AttributeError, TypeError): - pass - try: - raw = self.generate(messages) - except Exception as exc: - attempt["error"] = f"generator failed: {exc}" - if metadata_cleared: - attempt["generation"] = _generation_metadata(self.generate) - attempts.append(attempt) - continue - attempt["raw_response"] = raw - attempt["generation"] = _generation_metadata(self.generate) - try: - payload = _decode_observation_object(raw) - if set(payload) != {"option_ids", "summary"}: - raise SkillExecutionError("Top-K response must contain option_ids and summary only") - if not isinstance(payload["summary"], str) or not payload["summary"].strip(): - raise SkillExecutionError("two-stage Skill requires a nonempty summary") - self.category_catalog.resolve_option_ids(payload["option_ids"], self.top_k) - ranking = list(payload["option_ids"]) - rankings.append(ranking) - attempt.update({"valid": True, "option_ids": ranking, "votes": [ - {"option_id": item, "vote": 1, "reciprocal_rank_score": f"1/{rank}"} - for rank, item in enumerate(ranking, start=1) - ]}) - except (SkillExecutionError, ValueError, TypeError, KeyError) as exc: - attempt["error"] = str(exc) - attempts.append(attempt) - metadata = _attempt_metadata(attempts) - metadata["format_retry_count"] = 0 - selection = { - "mode": "balanced-vote", "policy": SELECTION_POLICY, - "seed": self.topk_selection_seed, "rounds": 3, "quorum": 2, - "valid_rounds": len(rankings), "selected_option_ids": [], "scores": [], - } - metadata["topk_selection"] = selection - if evidence_assembled: - metadata.update({"controller_evidence_assembled": True, "topk_evidence_mode": self.topk_evidence_mode}) - if len(rankings) < 2: - raise SkillExecutionError("balanced-vote requires at least two valid rankings", metadata=metadata) - selected = aggregate_rankings(rankings, allowed, record.domain, record.field_name, - self.topk_selection_seed, self.top_k) - selection["selected_option_ids"] = selected - selection["scores"] = ranking_scores(rankings, allowed, record.domain, record.field_name, - self.topk_selection_seed, self.top_k) - canonical = self.category_catalog.resolve_option_ids(selected, self.top_k) - labels = {item["category"]: item for item in self.category_catalog.labels()} - return Observation("SELECT_CATEGORY_TOPK", "success", "Balanced Top-K vote", - {"standard_candidates": [labels[item] for item in canonical]}, metadata=metadata) - - -__all__ = [ - "DeterministicHandler", - "ModelLoopPolicy", - "ModelSkillExecutor", - "SkillExecutionError", - "TextGenerator", - "make_standard_search_handler", - "make_field_metadata_handler", - "make_table_fields_handler", - "metadata_availability_handler", - "load_few_shot_messages", - "parse_skill_observation", -] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/planner.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/planner.py deleted file mode 100644 index 9987d1d..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/planner.py +++ /dev/null @@ -1,405 +0,0 @@ -"""Prompt construction and model-independent Program planning adapters.""" - -from __future__ import annotations - -import json -from dataclasses import dataclass -from json import JSONDecodeError -from pathlib import Path -from time import perf_counter -from typing import Any, Callable, Mapping, Sequence - -from .catalog import SkillSpec, default_catalog -from .contracts import MetadataRecord, Program -from .validator import DEFAULT_MAX_STEPS, ValidationIssue, validate_program - - -PLANNER_SYSTEM_PROMPT = """你是数据库字段分类分级任务的 DSL Program Planner。 -你的职责是根据当前字段元数据、已有状态和可用 Skill Catalog,生成一个可执行的 Program。 -只允许使用 Catalog 中出现的 Skill;只能引用当前真实存在的元数据或前一步已经产生的状态。 -引用语法必须严格遵守:`$record` 表示完整记录,`$domain` 表示域名,`$metadata.` 表示元数据字段,`$state.` 表示前一步产生的状态。 -禁止使用 `$metadata`、`$record.metadata.`、`$record.domain` 或其他未列出的路径;这些写法即使看起来等价,也不是合法 DSL 引用。 -不要补造缺失的表名、描述或样例值。Program 必须以 FINALIZE_CLASSIFICATION 结束。 -对于前一步 Skill 产生的结果,后续参数必须使用对应的 `$state.` 引用,不能把空数组、空对象或模型臆造的结果直接填入必需参数。 -Program 最多 10 步;如果已有信息足够,可以采用下面这个合法的最小骨架: -{"program":[ - {"tool":"INTERPRET_FIELD_NAME","arguments":{"field_name":"$metadata.field_name"}}, - {"tool":"SEARCH_STANDARD","arguments":{"semantic_query":"$state.field_semantics"}}, - {"tool":"INFER_CATEGORY","arguments":{"candidate_standard_categories":"$state.standard_candidates","all_available_evidence":"$state.field_semantics"}}, - {"tool":"INFER_GRADING_LEVEL","arguments":{"aligned_category":"$state.category","aligned_standard_entry":"$state.aligned_standard_entry"}}, - {"tool":"FINALIZE_CLASSIFICATION","arguments":{"final_evidence_state":"$state.final_evidence_state"}} -]} -只输出一个完整 JSON 对象,不要输出 Markdown、解释或额外文字,不能省略括号。""" - - -TWO_STAGE_PLANNER_SYSTEM_PROMPT = """你是数据库字段分类分级任务的 DSL Program Planner。 -每个 Program 步骤只包含一次 Tool Call;只能调用本轮 Skill Catalog 中的工具。 -仅使用可见的 domain 与 field_name,缺少其他元数据时通过可用的元数据 Skill 查询,不能编造。 -引用语法只允许 `$record`、`$domain`、`$metadata.`、`$state.`。 -先调用 SELECT_CATEGORY_TOPK 从完整类别路径目录选候选 ID,再调用 INFER_CATEGORY_FROM_TOPK 从这些候选中选一个类别。 -第二步的 candidate_standard_categories 必须引用 `$state.standard_candidates`,不能自己填写候选。 -只有 Top-1 类别确定后才调用 INFER_GRADING_LEVEL,最后必须调用 FINALIZE_CLASSIFICATION。 -合法的最小骨架: -{"program":[ - {"tool":"INTERPRET_FIELD_NAME","arguments":{"field_name":"$metadata.field_name"}}, - {"tool":"SELECT_CATEGORY_TOPK","arguments":{"semantic_query":"$state.field_semantics"}}, - {"tool":"INFER_CATEGORY_FROM_TOPK","arguments":{"candidate_standard_categories":"$state.standard_candidates","all_available_evidence":"$state.field_semantics"}}, - {"tool":"INFER_GRADING_LEVEL","arguments":{"aligned_category":"$state.category","aligned_standard_entry":"$state.aligned_standard_entry"}}, - {"tool":"FINALIZE_CLASSIFICATION","arguments":{"final_evidence_state":"$state.grading_level"}} -]} -只输出一个完整 JSON 对象,不输出解释或 Markdown。""" - - -class PlannerError(ValueError): - """Raised when generation, JSON parsing, or Program validation fails.""" - - def __init__( - self, - message: str, - *, - raw_response: str | None = None, - issues: Sequence[ValidationIssue] = (), - ) -> None: - super().__init__(message) - self.raw_response = raw_response - self.issues = tuple(issues) - - -@dataclass(frozen=True) -class PlannerResult: - """A validated Program together with the exact prompt and model response.""" - - program: Program - messages: tuple[dict[str, str], ...] - raw_response: str - - -def _catalog_payload(catalog: Mapping[str, SkillSpec]) -> list[dict[str, Any]]: - return [ - { - "name": spec.name, - "role": spec.role, - "required_inputs": list(spec.required_inputs), - "optional_inputs": list(spec.optional_inputs), - "produces": list(spec.produces), - "max_calls": spec.max_calls, - "terminal": spec.terminal, - } - for spec in catalog.values() - ] - - -def build_planner_messages( - record: MetadataRecord, - catalog: Mapping[str, SkillSpec] | None = None, - *, - state: Mapping[str, Any] | None = None, - max_steps: int = DEFAULT_MAX_STEPS, - two_stage: bool = False, -) -> list[dict[str, str]]: - """Build deterministic chat messages for a model that generates a Program.""" - - active_catalog = catalog or default_catalog() - available_metadata = [ - name - for name in ("domain", *record.metadata.keys()) - if record.available(name) - ] - payload = { - "task": "为当前数据库字段选择必要的元数据、语义、标准对齐和证据推理 Skill,并生成完整 Program。", - "record": ( - {"domain": record.domain, "metadata": dict(record.metadata)} - if two_stage else record.to_dict() - ), - "available_metadata": available_metadata, - "state": dict(state or {}), - "skill_catalog": _catalog_payload(active_catalog), - "constraints": { - "max_steps": max_steps, - "final_skill": "FINALIZE_CLASSIFICATION", - "output_schema": {"program": [{"tool": "SKILL_NAME", "arguments": {}}]}, - }, - } - return [ - {"role": "system", "content": ( - TWO_STAGE_PLANNER_SYSTEM_PROMPT if two_stage else PLANNER_SYSTEM_PROMPT - )}, - { - "role": "user", - "content": json.dumps(payload, ensure_ascii=False, indent=2), - }, - ] - - -def _decode_single_json_object(text: str) -> Mapping[str, Any]: - cleaned = text.strip() - if cleaned.startswith("```"): - lines = cleaned.splitlines() - if lines and lines[0].lstrip().startswith("```"): - lines = lines[1:] - if lines and lines[-1].strip() == "```": - lines = lines[:-1] - cleaned = "\n".join(lines).strip() - - start = cleaned.find("{") - if start < 0: - raise PlannerError("model response does not contain a JSON object", raw_response=text) - - decoder = json.JSONDecoder() - try: - value, end = decoder.raw_decode(cleaned[start:]) - except JSONDecodeError as exc: - raise PlannerError(f"invalid JSON response: {exc.msg}", raw_response=text) from exc - - trailing = cleaned[start + end :].strip() - if trailing: - if trailing.startswith("{"): - message = "model response contains multiple JSON objects" - else: - message = "model response contains trailing non-JSON content" - raise PlannerError(message, raw_response=text) - if not isinstance(value, Mapping): - raise PlannerError("model response JSON must be an object", raw_response=text) - return value - - -def parse_program_response(text: str) -> Program: - """Parse one model response into a Program without silently repairing it.""" - - if not isinstance(text, str) or not text.strip(): - raise PlannerError("model response must be a non-empty string", raw_response=text if isinstance(text, str) else None) - payload = _decode_single_json_object(text) - try: - return Program.from_mapping(payload) - except (TypeError, ValueError) as exc: - raise PlannerError(f"invalid Program schema: {exc}", raw_response=text) from exc - - -class PromptPlanner: - """Adapt any text generator to the validated DSL Program contract.""" - - def __init__( - self, - generate: Callable[[list[dict[str, str]]], str], - *, - catalog: Mapping[str, SkillSpec] | None = None, - max_steps: int = DEFAULT_MAX_STEPS, - max_retries: int = 1, - two_stage: bool = False, - ) -> None: - if max_retries < 0: - raise ValueError("max_retries must be non-negative") - self.generate = generate - self.catalog = dict(catalog or default_catalog()) - self.max_steps = max_steps - self.max_retries = max_retries - self.two_stage = two_stage - - @staticmethod - def _validation_feedback(issues: Sequence[ValidationIssue]) -> str: - rendered = "\n".join(f"- {issue}" for issue in issues) - return ( - "上一版 Program 未通过 DSL 校验,请修正后重新输出完整 JSON 对象。\n" - "校验错误:\n" - f"{rendered}\n" - "只允许使用 `$record`、`$domain`、`$metadata.` 和 `$state.`;" - "禁止使用 `$metadata` 或 `$record.metadata.`。" - "不要解释,不要输出 Markdown,只输出修正后的 JSON。" - ) - - def plan( - self, - record: MetadataRecord, - *, - state: Mapping[str, Any] | None = None, - ) -> PlannerResult: - messages = build_planner_messages( - record, - self.catalog, - state=state, - max_steps=self.max_steps, - two_stage=self.two_stage, - ) - attempt_messages = list(messages) - for attempt in range(self.max_retries + 1): - try: - raw_response = self.generate(attempt_messages) - except Exception as exc: # pragma: no cover - depends on external generator - raise PlannerError(f"planner generator failed: {exc}") from exc - if not isinstance(raw_response, str): - raise PlannerError("planner generator must return a string", raw_response=None) - - program = parse_program_response(raw_response) - issues = validate_program( - record, - program, - self.catalog, - initial_state=state, - max_steps=self.max_steps, - ) - if not issues: - return PlannerResult( - program=program, - messages=tuple(attempt_messages), - raw_response=raw_response, - ) - - if attempt == self.max_retries: - rendered = "; ".join(str(issue) for issue in issues) - raise PlannerError( - f"generated Program failed validation: {rendered}", - raw_response=raw_response, - issues=issues, - ) - - attempt_messages.extend( - [ - {"role": "assistant", "content": raw_response}, - {"role": "user", "content": self._validation_feedback(issues)}, - ] - ) - - raise AssertionError("unreachable") - - -class TransformersTextGenerator: - """Optional local Transformers backend; imports model dependencies lazily.""" - - def __init__( - self, - model_path: str | Path, - *, - max_new_tokens: int = 512, - local_files_only: bool = True, - device_map: str = "auto", - torch_dtype: str = "auto", - trust_remote_code: bool = False, - enable_thinking: bool = False, - ) -> None: - self.model_path = str(Path(model_path).expanduser()) - self.max_new_tokens = max_new_tokens - self.local_files_only = local_files_only - self.device_map = device_map - self.torch_dtype = torch_dtype - self.trust_remote_code = trust_remote_code - self.enable_thinking = enable_thinking - self._tokenizer = None - self._model = None - self._torch = None - self.last_generation_metadata: dict[str, Any] = {} - - def _load(self) -> None: - if self._model is not None: - return - try: - import torch - from transformers import ( - AutoConfig, - AutoModelForCausalLM, - AutoModelForImageTextToText, - AutoTokenizer, - ) - except ImportError as exc: # pragma: no cover - optional dependency - raise PlannerError( - "TransformersTextGenerator requires torch and transformers; " - "install them in the remote environment first" - ) from exc - self._torch = torch - - dtype: Any = self.torch_dtype - if dtype != "auto": - dtype = getattr(torch, dtype) - self._tokenizer = AutoTokenizer.from_pretrained( - self.model_path, - local_files_only=self.local_files_only, - trust_remote_code=self.trust_remote_code, - ) - model_config = AutoConfig.from_pretrained( - self.model_path, - local_files_only=self.local_files_only, - trust_remote_code=self.trust_remote_code, - ) - auto_model = ( - AutoModelForImageTextToText - if select_transformers_auto_model(model_config.to_dict()) == "image-text-to-text" - else AutoModelForCausalLM - ) - self._model = auto_model.from_pretrained( - self.model_path, - local_files_only=self.local_files_only, - device_map=self.device_map, - dtype=dtype, - trust_remote_code=self.trust_remote_code, - ) - self._model.eval() - - def __call__(self, messages: list[dict[str, str]]) -> str: - self._load() - assert self._tokenizer is not None - assert self._model is not None - tokenizer = self._tokenizer - model = self._model - if not hasattr(tokenizer, "apply_chat_template"): - raise PlannerError("tokenizer does not provide apply_chat_template") - try: - prompt = tokenizer.apply_chat_template( - messages, - tokenize=False, - add_generation_prompt=True, - enable_thinking=self.enable_thinking, - ) - except TypeError: - # Generic chat templates may not expose Qwen's thinking switch. - prompt = tokenizer.apply_chat_template( - messages, - tokenize=False, - add_generation_prompt=True, - ) - inputs = tokenizer(prompt, return_tensors="pt") - device = next(model.parameters()).device - inputs = {name: value.to(device) for name, value in inputs.items()} - prompt_length = inputs["input_ids"].shape[-1] - assert self._torch is not None - started = perf_counter() - with self._torch.no_grad(): - generated = model.generate( - **inputs, - max_new_tokens=self.max_new_tokens, - do_sample=False, - ) - new_tokens = generated[0][prompt_length:] - completion_tokens = int(new_tokens.shape[-1]) - self.last_generation_metadata = { - "token_usage": { - "prompt_tokens": int(prompt_length), - "completion_tokens": completion_tokens, - "total_tokens": int(prompt_length) + completion_tokens, - }, - "elapsed_seconds": perf_counter() - started, - } - return tokenizer.decode(new_tokens, skip_special_tokens=True).strip() - - -def select_transformers_auto_model(config: Mapping[str, Any]) -> str: - """Choose the compatible Transformers auto class from lightweight config data.""" - - architectures = config.get("architectures") - names = architectures if isinstance(architectures, list) else [] - model_type = str(config.get("model_type") or "") - if model_type == "qwen3_5" or any( - str(name).endswith("ForConditionalGeneration") for name in names - ): - return "image-text-to-text" - return "causal-lm" - - -__all__ = [ - "PLANNER_SYSTEM_PROMPT", - "PlannerError", - "PlannerResult", - "PromptPlanner", - "TransformersTextGenerator", - "build_planner_messages", - "parse_program_response", - "select_transformers_auto_model", -] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/retrieval.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/retrieval.py deleted file mode 100644 index df3e678..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/retrieval.py +++ /dev/null @@ -1,335 +0,0 @@ -"""Auditable Top-K retrieval backends for frozen standard registries.""" - -from __future__ import annotations - -from dataclasses import dataclass, field -import json -from json import JSONDecodeError -import math -from pathlib import Path -from time import perf_counter -from typing import Any, Callable, Mapping, Sequence - -from .runtime import KnowledgeBase - - -class RetrievalError(ValueError): - """Raised when a retriever cannot return one valid frozen-registry ranking.""" - - -@dataclass(frozen=True) -class RetrievalResult: - candidates: tuple[dict[str, Any], ...] - metadata: Mapping[str, Any] = field(default_factory=dict) - - -_QUERY_FIELD_ORDER = ( - "domain", - "field_name", - "field_abbreviation_semantics", - "field_semantics", -) - - -def format_retrieval_query(query: Any) -> str: - """Render allowed retrieval evidence deterministically for text encoders.""" - - if isinstance(query, Mapping): - parts = [ - f"{name}: {query[name]}" - for name in _QUERY_FIELD_ORDER - if name in query and query[name] not in (None, "") - ] - return "\n".join(parts) - return str(query) - - -def _canonical_registry(registry: Mapping[str, Mapping[str, Any]]) -> dict[str, dict[str, Any]]: - canonical: dict[str, dict[str, Any]] = {} - for key, raw in registry.items(): - category = str(raw.get("category") or raw.get("category_id") or key) - if category in canonical: - raise RetrievalError(f"duplicate Registry category: {category}") - entry = dict(raw) - entry["category"] = category - canonical[category] = entry - return canonical - - -def validate_ranked_candidates( - candidates: Sequence[Mapping[str, Any]], - registry: Mapping[str, Mapping[str, Any]], - *, - top_k: int, -) -> tuple[dict[str, Any], ...]: - """Return authoritative Registry entries for one exact, distinct ranking.""" - - if top_k < 1: - raise RetrievalError("top_k must be positive") - if len(candidates) != top_k: - raise RetrievalError(f"ranking must contain exactly {top_k} candidates") - frozen = _canonical_registry(registry) - ranked: list[dict[str, Any]] = [] - seen: set[str] = set() - for index, candidate in enumerate(candidates): - category = candidate.get("category") or candidate.get("category_id") - if not isinstance(category, str) or not category: - raise RetrievalError(f"candidate {index} must contain a non-empty category") - if category in seen: - raise RetrievalError(f"duplicate category in ranking: {category}") - if category not in frozen: - raise RetrievalError(f"unknown Registry category: {category}") - seen.add(category) - ranked.append(dict(frozen[category])) - return tuple(ranked) - - -class LexicalRetriever: - def __init__( - self, - knowledge_base: KnowledgeBase, - registry: Mapping[str, Mapping[str, Any]], - ) -> None: - self.knowledge_base = knowledge_base - self.registry = _canonical_registry(registry) - - def retrieve(self, query: Any, top_k: int = 5) -> RetrievalResult: - candidates = self.knowledge_base.search_standard(query, top_k=top_k) - return RetrievalResult( - validate_ranked_candidates(candidates, self.registry, top_k=top_k), - {"backend": "lexical"}, - ) - - -def _single_json_object(text: str) -> Mapping[str, Any]: - if not isinstance(text, str) or not text.strip(): - raise RetrievalError("model response must be non-empty JSON") - cleaned = text.strip() - if not cleaned.startswith("{"): - raise RetrievalError("model response must be one JSON object") - try: - value, end = json.JSONDecoder().raw_decode(cleaned) - except JSONDecodeError as exc: - raise RetrievalError(f"model response is invalid JSON: {exc.msg}") from exc - if cleaned[end:].strip() or not isinstance(value, Mapping): - raise RetrievalError("model response must be exactly one JSON object") - return value - - -def _last_generation_metadata(generate: Callable[..., Any]) -> dict[str, Any]: - metadata = getattr(generate, "last_generation_metadata", None) - return dict(metadata) if isinstance(metadata, Mapping) else {} - - -class CatalogModelRetriever: - """Ask a text generator to rank IDs from the complete frozen Registry.""" - - def __init__( - self, - generate: Callable[[list[dict[str, str]]], str], - registry: Mapping[str, Mapping[str, Any]], - ) -> None: - self.generate = generate - self.registry = _canonical_registry(registry) - - def _messages(self, query: Any, top_k: int) -> list[dict[str, str]]: - catalog = [ - { - "category_id": category, - "description": str(entry.get("description") or entry.get("definition") or category), - } - for category, entry in self.registry.items() - ] - payload = { - "semantic_query": query, - "top_k": top_k, - "category_catalog": catalog, - "output_schema": {"category_ids": ["exact Registry category ID"]}, - } - return [ - { - "role": "system", - "content": ( - "Rank the database-field categories supported by the semantic query. " - "Choose only exact category_id values from the supplied complete catalog. " - f"Return exactly {top_k} distinct IDs in descending relevance. " - "Return one JSON object only, with exactly the key category_ids." - ), - }, - {"role": "user", "content": json.dumps(payload, ensure_ascii=False)}, - ] - - def retrieve(self, query: Any, top_k: int = 5) -> RetrievalResult: - messages = self._messages(query, top_k) - raw = self.generate(messages) - payload = _single_json_object(raw) - if set(payload) != {"category_ids"}: - raise RetrievalError("model response must contain exactly category_ids") - ids = payload.get("category_ids") - if not isinstance(ids, list): - raise RetrievalError("category_ids must be a list") - candidates = [{"category": value} for value in ids] - ranked = validate_ranked_candidates(candidates, self.registry, top_k=top_k) - return RetrievalResult( - ranked, - { - "backend": "model-catalog", - "messages": messages, - "raw_response": raw, - **_last_generation_metadata(self.generate), - }, - ) - - -EmbeddingFunction = Callable[..., Sequence[Sequence[float]]] - - -def _normalized(vector: Sequence[float]) -> tuple[float, ...]: - values = tuple(float(value) for value in vector) - norm = math.sqrt(sum(value * value for value in values)) - if not values or norm == 0.0: - raise RetrievalError("embedding vector must be non-empty and non-zero") - return tuple(value / norm for value in values) - - -class EmbeddingRetriever: - """Rank a frozen Registry with cached normalized catalog embeddings.""" - - def __init__( - self, - encode: EmbeddingFunction, - registry: Mapping[str, Mapping[str, Any]], - ) -> None: - self.encode = encode - self.registry = _canonical_registry(registry) - self._categories = tuple(self.registry) - self._catalog_vectors: tuple[tuple[float, ...], ...] | None = None - - def _catalog_texts(self) -> list[str]: - return [ - "passage: " - + category - + " " - + str(entry.get("description") or entry.get("definition") or category) - for category, entry in self.registry.items() - ] - - def _ensure_catalog(self) -> tuple[tuple[float, ...], ...]: - if self._catalog_vectors is None: - encoded = self.encode(self._catalog_texts(), kind="passage") - if len(encoded) != len(self._categories): - raise RetrievalError("catalog embedding count does not match Registry") - self._catalog_vectors = tuple(_normalized(vector) for vector in encoded) - dimensions = {len(vector) for vector in self._catalog_vectors} - if len(dimensions) != 1: - raise RetrievalError("catalog embedding dimension mismatch") - return self._catalog_vectors - - def retrieve(self, query: Any, top_k: int = 5) -> RetrievalResult: - if top_k > len(self.registry): - raise RetrievalError("top_k exceeds Registry size") - started = perf_counter() - catalog_vectors = self._ensure_catalog() - query_rows = self.encode([f"query: {format_retrieval_query(query)}"], kind="query") - if len(query_rows) != 1: - raise RetrievalError("query encoder must return exactly one vector") - query_vector = _normalized(query_rows[0]) - if len(query_vector) != len(catalog_vectors[0]): - raise RetrievalError("query/catalog embedding dimension mismatch") - scored = [ - (sum(left * right for left, right in zip(query_vector, vector)), category) - for category, vector in zip(self._categories, catalog_vectors) - ] - scored.sort(key=lambda item: (-item[0], item[1])) - ranked = validate_ranked_candidates( - [{"category": category} for _, category in scored[:top_k]], - self.registry, - top_k=top_k, - ) - return RetrievalResult( - ranked, - { - "backend": "embedding", - "elapsed_seconds": perf_counter() - started, - "scores": [score for score, _ in scored[:top_k]], - }, - ) - - -class TransformersE5Encoder: - """Lazy Hugging Face E5 encoder with masked mean pooling.""" - - def __init__( - self, - model_path: str | Path, - *, - local_files_only: bool = True, - device_map: str = "auto", - batch_size: int = 32, - ) -> None: - self.model_path = str(Path(model_path).expanduser()) - self.local_files_only = local_files_only - self.device_map = device_map - self.batch_size = batch_size - self._tokenizer = None - self._model = None - self._torch = None - - def _load(self) -> None: - if self._model is not None: - return - try: - import torch - from transformers import AutoModel, AutoTokenizer - except ImportError as exc: # pragma: no cover - optional remote dependency - raise RetrievalError("TransformersE5Encoder requires torch and transformers") from exc - self._torch = torch - self._tokenizer = AutoTokenizer.from_pretrained( - self.model_path, local_files_only=self.local_files_only - ) - self._model = AutoModel.from_pretrained( - self.model_path, - local_files_only=self.local_files_only, - device_map=self.device_map, - dtype="auto", - ) - self._model.eval() - - def __call__(self, texts: Sequence[str], *, kind: str) -> list[list[float]]: - if kind not in {"query", "passage"}: - raise RetrievalError("embedding kind must be query or passage") - self._load() - assert self._tokenizer is not None - assert self._model is not None - assert self._torch is not None - rows: list[list[float]] = [] - device = next(self._model.parameters()).device - for start in range(0, len(texts), self.batch_size): - batch = list(texts[start : start + self.batch_size]) - inputs = self._tokenizer( - batch, - max_length=512, - padding=True, - truncation=True, - return_tensors="pt", - ) - inputs = {name: value.to(device) for name, value in inputs.items()} - with self._torch.no_grad(): - hidden = self._model(**inputs).last_hidden_state - mask = inputs["attention_mask"].unsqueeze(-1).to(hidden.dtype) - pooled = (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1) - pooled = self._torch.nn.functional.normalize(pooled, p=2, dim=1) - rows.extend(pooled.detach().cpu().tolist()) - return rows - - -__all__ = [ - "CatalogModelRetriever", - "EmbeddingRetriever", - "LexicalRetriever", - "RetrievalError", - "RetrievalResult", - "TransformersE5Encoder", - "format_retrieval_query", - "validate_ranked_candidates", -] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/runtime.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/runtime.py deleted file mode 100644 index e90f120..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/runtime.py +++ /dev/null @@ -1,173 +0,0 @@ -"""CPU-only deterministic indexes and a mock Skill executor.""" - -from __future__ import annotations - -from collections import defaultdict -from dataclasses import dataclass, field -import re -from typing import Any, Mapping, Sequence - -from .catalog import SkillSpec, default_catalog -from .contracts import MetadataRecord, Program, StandardEntry, ToolCall -from .validator import assert_valid_program, resolve_reference - - -@dataclass -class KnowledgeBase: - records: tuple[MetadataRecord, ...] - standards: tuple[StandardEntry, ...] - _table_index: dict[tuple[str | None, str], list[MetadataRecord]] = field(default_factory=dict) - - @classmethod - def from_mappings(cls, records: Sequence[Mapping[str, Any]], standards: Sequence[StandardEntry]) -> "KnowledgeBase": - normalized = tuple(MetadataRecord.from_mapping(record) for record in records) - index: dict[tuple[str | None, str], list[MetadataRecord]] = defaultdict(list) - for record in normalized: - table = record.get("table_name") - if table: - index[(record.get("database_name"), str(table))].append(record) - return cls(normalized, tuple(standards), dict(index)) - - def table_fields(self, table_name: str, database_name: str | None = None) -> list[str]: - rows = self._table_index.get((database_name, table_name), []) - if not rows and database_name is not None: - rows = [record for (db, table), values in self._table_index.items() if table == table_name for record in values] - return list(dict.fromkeys(record.field_name for record in rows)) - - def search_standard(self, query: Any, top_k: int = 5) -> list[dict[str, str]]: - tokens = _search_tokens(query) - scored = [] - for entry in self.standards: - haystack_tokens = _search_tokens(f"{entry.category} {entry.description}") - score = len(tokens.intersection(haystack_tokens)) - scored.append((score, entry)) - scored.sort(key=lambda item: (-item[0], item[1].category)) - return [entry.to_dict() for _, entry in scored[:top_k]] - - def level_for(self, category: str) -> str | None: - for entry in self.standards: - if entry.category == category: - return entry.grading_level - return None - - -def _flatten_text(value: Any) -> list[str]: - if isinstance(value, Mapping): - parts: list[str] = [] - for key, nested in value.items(): - parts.extend(_flatten_text(key)) - parts.extend(_flatten_text(nested)) - return parts - if isinstance(value, (list, tuple, set)): - parts = [] - for nested in value: - parts.extend(_flatten_text(nested)) - return parts - return [str(value)] if value is not None else [] - - -def _search_tokens(value: Any) -> set[str]: - """Extract identifier tokens and CJK n-grams from nested Skill inputs.""" - - text = " ".join(_flatten_text(value)).lower() - tokens = set(re.findall(r"[a-z0-9]+", text)) - for chunk in re.findall(r"[\u4e00-\u9fff]+", text): - if len(chunk) <= 3: - tokens.add(chunk) - tokens.update(chunk[index : index + 2] for index in range(len(chunk) - 1)) - tokens.update(chunk[index : index + 3] for index in range(len(chunk) - 2)) - return {token for token in tokens if token} - - -@dataclass(frozen=True) -class Observation: - skill: str - status: str - summary: str - data: Mapping[str, Any] = field(default_factory=dict) - metadata: Mapping[str, Any] = field(default_factory=dict) - - -@dataclass -class ExecutionTrace: - observations: list[Observation | Mapping[str, Any]] = field(default_factory=list) - terminated: bool = False - final_result: dict[str, Any] | None = None - state: dict[str, Any] = field(default_factory=dict) - - -class MockSkillExecutor: - """Run deterministic and placeholder semantic Skills without an LLM.""" - - def __init__(self, knowledge_base: KnowledgeBase, catalog: Mapping[str, SkillSpec] | None = None): - self.knowledge_base = knowledge_base - self.catalog = dict(catalog or default_catalog()) - - def execute(self, call: ToolCall, record: MetadataRecord, state: Mapping[str, Any]) -> Observation: - spec = self.catalog[call.tool] - resolved = { - key: resolve_reference(value, record, state)[1] - for key, value in call.arguments.items() - } - - if call.tool == "CHECK_METADATA_AVAILABILITY": - available = ["domain", "field_name"] + [name for name in record.metadata if record.available(name) and name != "field_name"] - missing = [name for name in ("database_name", "database_description", "table_name", "table_description", "field_description", "field_type", "value") if not record.available(name)] - data = {"metadata_availability": {"available": available, "missing": missing}} - elif call.tool == "GET_TABLE_FIELDS": - table_name = str(resolved["table_name"]) - data = {"table_fields": self.knowledge_base.table_fields(table_name, record.get("database_name"))} - elif call.tool == "SELECT_CONTEXT_FIELDS": - fields = list(resolved["table_fields"] or []) - target = str(resolved["target_field"]) - data = {"selected_context_fields": [field for field in fields if field != target][:3]} - elif call.tool == "SEARCH_STANDARD": - data = {"standard_candidates": self.knowledge_base.search_standard(resolved["semantic_query"])} - elif call.tool == "INFER_CATEGORY": - candidates = resolved["candidate_standard_categories"] - if isinstance(candidates, Mapping): - candidates = [candidates] - candidates = list(candidates or []) - first = dict(candidates[0]) if candidates else {} - category = first.get("category") or first.get("category_id") or first.get("name") - data = {"category": category, "aligned_standard_entry": first} - elif call.tool == "INFER_GRADING_LEVEL": - entry = resolved["aligned_standard_entry"] - if isinstance(entry, Mapping): - level = entry.get("grading_level") - else: - level = self.knowledge_base.level_for(str(resolved["aligned_category"])) - data = {"grading_level": level} - elif call.tool == "FINALIZE_CLASSIFICATION": - data = {"final_result": {"category": state.get("category"), "grading_level": state.get("grading_level")}} - else: - produced = spec.produces[0] if spec.produces else "observation" - data = {produced: {"input": resolved, "source_skill": call.tool}} - - return Observation(call.tool, "success", f"Mock observation from {call.tool}", data) - - -def execute_program( - record: MetadataRecord, - program: Program, - executor: MockSkillExecutor, - *, - initial_state: Mapping[str, Any] | None = None, -) -> ExecutionTrace: - assert_valid_program(record, program, executor.catalog, initial_state=initial_state) - state = dict(initial_state or {}) - trace = ExecutionTrace(state=state) - for call in program.steps: - observation = executor.execute(call, record, state) - trace.observations.append(observation) - if observation.status != "success": - break - state.update(observation.data) - if call.tool == "FINALIZE_CLASSIFICATION": - trace.terminated = True - trace.final_result = dict(observation.data["final_result"]) - break - return trace - - -__all__ = ["ExecutionTrace", "KnowledgeBase", "MockSkillExecutor", "Observation", "execute_program"] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/skill_loader.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/skill_loader.py deleted file mode 100644 index cb43a6a..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/skill_loader.py +++ /dev/null @@ -1,159 +0,0 @@ -"""Strict loader for one Markdown contract per orchestration Skill.""" - -from __future__ import annotations - -from dataclasses import dataclass -from pathlib import Path -from typing import Mapping - -from .catalog import SkillSpec - - -class SkillContractError(ValueError): - """Raised when Skill files are missing, duplicated, or inconsistent.""" - - -@dataclass(frozen=True) -class SkillContract: - name: str - dsl: str - required_inputs: tuple[str, ...] - optional_inputs: tuple[str, ...] - produces: tuple[str, ...] - terminal: bool - body: str - path: Path - - -def _parse_list(value: str, *, key: str, path: Path) -> tuple[str, ...]: - value = value.strip() - if not value.startswith("[") or not value.endswith("]"): - raise SkillContractError(f"{path}: {key} must use [a, b] syntax") - inner = value[1:-1].strip() - if not inner: - return () - items = tuple(item.strip() for item in inner.split(",")) - if any(not item for item in items): - raise SkillContractError(f"{path}: {key} contains an empty value") - return items - - -def _parse_contract(path: Path) -> SkillContract: - text = path.read_text(encoding="utf-8") - lines = text.splitlines() - if len(lines) < 3 or lines[0].strip() != "---": - raise SkillContractError(f"{path}: missing opening front matter marker") - try: - end = next(index for index, line in enumerate(lines[1:], start=1) if line.strip() == "---") - except StopIteration as exc: - raise SkillContractError(f"{path}: missing closing front matter marker") from exc - - header: dict[str, str] = {} - for line in lines[1:end]: - if ":" not in line: - raise SkillContractError(f"{path}: invalid front matter line {line!r}") - key, value = line.split(":", 1) - key = key.strip() - if key in header: - raise SkillContractError(f"{path}: duplicate front matter key {key!r}") - header[key] = value.strip() - - required = {"name", "dsl", "required_inputs", "optional_inputs", "produces", "terminal"} - if set(header) != required: - missing = sorted(required - set(header)) - extra = sorted(set(header) - required) - raise SkillContractError(f"{path}: front matter keys mismatch; missing={missing}, extra={extra}") - terminal_text = header["terminal"].lower() - if terminal_text not in {"true", "false"}: - raise SkillContractError(f"{path}: terminal must be true or false") - body = "\n".join(lines[end + 1 :]).strip() - if not body: - raise SkillContractError(f"{path}: Skill contract body is empty") - return SkillContract( - name=header["name"], - dsl=header["dsl"], - required_inputs=_parse_list(header["required_inputs"], key="required_inputs", path=path), - optional_inputs=_parse_list(header["optional_inputs"], key="optional_inputs", path=path), - produces=_parse_list(header["produces"], key="produces", path=path), - terminal=terminal_text == "true", - body=body, - path=path, - ) - - -class SkillLoader: - """Discover and validate Markdown Skill contracts against a catalog.""" - - def __init__( - self, - root: str | Path, - catalog: Mapping[str, SkillSpec], - *, - extra_roots: tuple[str | Path, ...] = (), - strict_catalog: bool = True, - ) -> None: - self.root = Path(root) - self.extra_roots = tuple(Path(path) for path in extra_roots) - self.strict_catalog = strict_catalog - self.catalog = dict(catalog) - self._contracts: dict[str, SkillContract] | None = None - - def validate_all(self) -> dict[str, SkillContract]: - discovered: dict[str, list[SkillContract]] = {} - for root in (self.root, *self.extra_roots): - if root.is_dir(): - for path in sorted(root.glob("*.md")): - contract = _parse_contract(path) - discovered.setdefault(contract.name, []).append(contract) - - validated: dict[str, SkillContract] = {} - for name, spec in self.catalog.items(): - matches = discovered.get(name, []) - if not matches: - raise SkillContractError(f"missing Skill contract for {name}") - if len(matches) > 1: - paths = ", ".join(str(item.path) for item in matches) - raise SkillContractError(f"duplicate Skill contracts for {name}: {paths}") - contract = matches[0] - expected_filename = f"{spec.role}_{spec.name}.md" - if contract.path.name != expected_filename: - raise SkillContractError( - f"{contract.path}: filename must be {expected_filename!r}" - ) - expected = { - "dsl": spec.role, - "required_inputs": spec.required_inputs, - "optional_inputs": spec.optional_inputs, - "produces": spec.produces, - "terminal": spec.terminal, - } - actual = { - "dsl": contract.dsl, - "required_inputs": contract.required_inputs, - "optional_inputs": contract.optional_inputs, - "produces": contract.produces, - "terminal": contract.terminal, - } - for key, value in expected.items(): - if actual[key] != value: - raise SkillContractError( - f"{contract.path}: {key}={actual[key]!r} does not match catalog {value!r}" - ) - validated[name] = contract - - unexpected = sorted(set(discovered) - set(self.catalog)) - if unexpected and self.strict_catalog: - raise SkillContractError(f"unexpected Skill contracts: {unexpected}") - self._contracts = validated - return dict(validated) - - def load(self, name: str) -> SkillContract: - if name not in self.catalog: - raise SkillContractError(f"unknown Skill {name!r}") - if self._contracts is None: - self.validate_all() - assert self._contracts is not None - return self._contracts[name] - - -__all__ = ["SkillContract", "SkillContractError", "SkillLoader"] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/table_field_lookup.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/table_field_lookup.py deleted file mode 100644 index 2935086..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/table_field_lookup.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Label-isolated, bounded lookup of neighboring fields in one real table.""" - -from __future__ import annotations - -from collections import defaultdict -import json -from pathlib import Path -from typing import Any, Mapping - -from .contracts import MetadataRecord - - -TableKey = tuple[str, str, str] - - -class TableFieldLookup: - def __init__( - self, - identities: Mapping[str, tuple[str, str, TableKey]], - tables: Mapping[TableKey, list[tuple[str, str]]], - *, - max_fields: int = 30, - ) -> None: - if max_fields < 1: - raise ValueError("max_fields must be positive") - self.max_fields = max_fields - self._identities = dict(identities) - self._tables = {key: tuple(values) for key, values in tables.items()} - - @classmethod - def from_canonical(cls, source: str | Path, *, max_fields: int = 30) -> "TableFieldLookup": - raw = json.loads(Path(source).read_text(encoding="utf-8")) - if not isinstance(raw, list): - raise ValueError("canonical source must be a list") - identities: dict[str, tuple[str, str, TableKey]] = {} - tables: dict[TableKey, list[tuple[str, str]]] = defaultdict(list) - for row in raw: - if not isinstance(row, Mapping): - raise ValueError("canonical row must be an object") - source_id = row.get("id") - if not isinstance(source_id, str) or not source_id.strip(): - raise ValueError("canonical row must have source id") - if source_id in identities: - raise ValueError(f"duplicate source id: {source_id}") - metadata = row.get("metadata") - if not isinstance(metadata, Mapping): - raise ValueError(f"canonical metadata missing for {source_id}") - domain = str(row.get("domain") or "").strip() - database = str(metadata.get("database_name") or "").strip() - table = str(metadata.get("table_name") or "").strip() - field_name = str(metadata.get("field_name") or "").strip() - if not domain or not database or not table or not field_name: - raise ValueError(f"table identity is incomplete for {source_id}") - key = (domain, database, table) - identities[source_id] = (domain, field_name, key) - description = str(metadata.get("field_description") or "").strip() - tables[key].append((field_name, description)) - return cls(identities, tables, max_fields=max_fields) - - def get(self, record: MetadataRecord) -> dict[str, Any]: - if not record.source_id or record.source_id not in self._identities: - raise ValueError("source id is absent from table field lookup") - domain, field_name, key = self._identities[record.source_id] - if domain != record.domain or field_name != record.field_name: - raise ValueError("lookup source does not match domain and field_name") - selected: dict[str, str] = {} - for name, description in self._tables[key]: - if name == record.field_name: - continue - previous = selected.get(name, "") - if description and (not previous or description < previous): - selected[name] = description - else: - selected.setdefault(name, previous) - names = sorted(selected, key=lambda value: (value.casefold(), value)) - fields: list[dict[str, str]] = [] - for name in names[: self.max_fields]: - item = {"field_name": name} - if selected[name]: - item["field_description"] = selected[name] - fields.append(item) - return { - "fields": fields, - "available_count": len(names), - "truncated": len(names) > self.max_fields, - } - - -__all__ = ["TableFieldLookup"] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/topk_selection.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/topk_selection.py deleted file mode 100644 index 0a98919..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/topk_selection.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Label-free, deterministic balanced presentation and exact vote aggregation.""" - -from __future__ import annotations - -import hashlib -import json -import random -from fractions import Fraction - - -SELECTION_POLICY = "canonical-sha256-shuffle-cyclic3-votes-rrf-hash-v1" - - -def _digest(seed: int, domain: str, field_name: str, option_id: str | None = None) -> str: - values = [seed, domain, field_name] - if option_id is not None: - values.append(option_id) - return hashlib.sha256(json.dumps(values, ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest() - - -def balanced_options(options: list[dict], domain: str, field_name: str, seed: int) -> list[list[dict]]: - """Shuffle canonical IDs once, then present floor(i*N/3) cyclic offsets.""" - ids = [item.get("option_id") for item in options] - if not ids or any(not isinstance(item, str) or not item for item in ids) or len(set(ids)) != len(ids): - raise ValueError("options require distinct nonempty option IDs") - canonical = [dict(item) for item in sorted(options, key=lambda item: item["option_id"])] - random.Random(int(_digest(seed, domain, field_name), 16)).shuffle(canonical) - rounds = [] - for index in range(3): - offset = index * len(canonical) // 3 - rounds.append([dict(item) for item in canonical[offset:] + canonical[:offset]]) - return rounds - - -def ranking_scores(rankings: list[list[str]], allowed: list[str], domain: str, - field_name: str, seed: int, top_k: int = 5) -> list[dict]: - """Return exact score records in the fixed aggregation order for audit traces.""" - if top_k < 1 or top_k > len(allowed) or len(set(allowed)) != len(allowed): - raise ValueError("top_k must fit a distinct allowed catalog") - if len(rankings) < 2: - raise ValueError("balanced-vote requires at least two valid rankings") - for ranking in rankings: - if (not isinstance(ranking, list) or len(ranking) != top_k - or any(not isinstance(item, str) or item not in allowed for item in ranking) - or len(set(ranking)) != top_k): - raise ValueError("each ranking requires exactly top_k distinct in-catalog IDs") - scores = [] - for option_id in sorted(allowed): - ranks = [ranking.index(option_id) + 1 for ranking in rankings if option_id in ranking] - if ranks: - score = sum((Fraction(1, rank) for rank in ranks), Fraction()) - scores.append((option_id, len(ranks), score, _digest(seed, domain, field_name, option_id))) - scores.sort(key=lambda item: (-item[1], -item[2], item[3])) - return [{"option_id": option_id, "votes": votes, "reciprocal_rank_score": str(score), "tie_hash": tie_hash} - for option_id, votes, score, tie_hash in scores] - - -def aggregate_rankings(rankings: list[list[str]], allowed: list[str], domain: str, - field_name: str, seed: int, top_k: int = 5) -> list[str]: - """Require quorum, validate all rankings and select by votes, exact RRF, hash.""" - return [item["option_id"] for item in ranking_scores(rankings, allowed, domain, field_name, seed, top_k)[:top_k]] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/validator.py b/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/validator.py deleted file mode 100644 index 8c30690..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/agent/orchestration/validator.py +++ /dev/null @@ -1,131 +0,0 @@ -"""Static validation for planner-produced Programs.""" - -from __future__ import annotations - -from dataclasses import dataclass -from typing import Any, Mapping - -from .catalog import SkillSpec -from .contracts import MetadataRecord, Program - - -DEFAULT_MAX_STEPS = 10 - - -@dataclass(frozen=True) -class ValidationIssue: - code: str - message: str - step_index: int | None = None - - def __str__(self) -> str: - location = "" if self.step_index is None else f" at step {self.step_index}" - return f"{self.code}{location}: {self.message}" - - -def resolve_reference(value: Any, record: MetadataRecord, state: Mapping[str, Any]) -> tuple[bool, Any]: - if not isinstance(value, str) or not value.startswith("$"): - return bool(value is not None and value != ""), value - if value == "$record": - # The controller may retain source_id privately for deterministic lookups. - # It is never included in resolved arguments sent to model-backed Skills. - return True, {"domain": record.domain, "metadata": dict(record.metadata)} - if value == "$domain": - return True, record.domain - if value.startswith("$metadata."): - name = value[len("$metadata.") :] - resolved = record.get(name) - return record.available(name), resolved - if value.startswith("$state."): - name = value[len("$state.") :] - return name in state, state.get(name) - return False, None - - -def validate_program( - record: MetadataRecord, - program: Program, - catalog: Mapping[str, SkillSpec], - *, - initial_state: Mapping[str, Any] | None = None, - max_steps: int = DEFAULT_MAX_STEPS, -) -> list[ValidationIssue]: - issues: list[ValidationIssue] = [] - state = dict(initial_state or {}) - seen: dict[str, int] = {} - finalized = False - - if len(program.steps) > max_steps: - issues.append(ValidationIssue("max_steps_exceeded", f"program has {len(program.steps)} steps; max is {max_steps}")) - - for index, call in enumerate(program.steps): - spec = catalog.get(call.tool) - if spec is None: - issues.append(ValidationIssue("unknown_skill", f"unknown Skill {call.tool!r}", index)) - continue - if call.tool == "INFER_CATEGORY_FROM_TOPK": - if not seen.get("SELECT_CATEGORY_TOPK") and "standard_candidates" not in (initial_state or {}): - issues.append(ValidationIssue( - "missing_topk_dependency", - "INFER_CATEGORY_FROM_TOPK requires a preceding SELECT_CATEGORY_TOPK", - index, - )) - if call.arguments.get("candidate_standard_categories") != "$state.standard_candidates": - issues.append(ValidationIssue( - "invalid_topk_reference", - "candidate_standard_categories must reference $state.standard_candidates", - index, - )) - if finalized: - issues.append(ValidationIssue("calls_after_finalizer", "no calls are allowed after FINALIZE_CLASSIFICATION", index)) - - seen[call.tool] = seen.get(call.tool, 0) + 1 - if seen[call.tool] > spec.max_calls: - issues.append(ValidationIssue("duplicate_skill", f"{call.tool} exceeds max_calls={spec.max_calls}", index)) - - for name in spec.required_inputs: - if name not in call.arguments: - issues.append(ValidationIssue("missing_required_argument", f"{call.tool} requires argument {name!r}", index)) - continue - found, _ = resolve_reference(call.arguments[name], record, state) - if not found: - value = call.arguments[name] - if isinstance(value, str) and value.startswith("$metadata."): - code = "unavailable_metadata" - elif isinstance(value, str) and value.startswith("$state."): - code = "unresolved_reference" - else: - code = "empty_required_argument" - issues.append(ValidationIssue(code, f"required argument {name!r} cannot be resolved", index)) - - for name in spec.optional_inputs: - if name in call.arguments: - resolve_reference(call.arguments[name], record, state) - - if spec.terminal: - finalized = True - if index != len(program.steps) - 1: - issues.append(ValidationIssue("finalizer_not_last", "FINALIZE_CLASSIFICATION must be the last step", index)) - - for produced in spec.produces: - state.setdefault(produced, {"source_skill": call.tool}) - - if not finalized: - issues.append(ValidationIssue("missing_finalizer", "program must end with FINALIZE_CLASSIFICATION")) - return issues - - -def assert_valid_program( - record: MetadataRecord, - program: Program, - catalog: Mapping[str, SkillSpec], - *, - initial_state: Mapping[str, Any] | None = None, - max_steps: int = DEFAULT_MAX_STEPS, -) -> None: - issues = validate_program(record, program, catalog, initial_state=initial_state, max_steps=max_steps) - if issues: - raise ValueError("; ".join(str(issue) for issue in issues)) - - -__all__ = ["DEFAULT_MAX_STEPS", "ValidationIssue", "assert_valid_program", "resolve_reference", "validate_program"] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/__init__.py b/research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/__init__.py deleted file mode 100644 index 09f258a..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -"""CPU-only helpers for exercising orchestration contracts locally.""" - diff --git a/research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/run_agent_loop_batch.py b/research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/run_agent_loop_batch.py deleted file mode 100644 index c8c6963..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/code/script/orchestration/run_agent_loop_batch.py +++ /dev/null @@ -1,1223 +0,0 @@ -"""Run and evaluate CPU-scripted dynamic Agent Loops without loading a model.""" - -from __future__ import annotations - -import argparse -from dataclasses import dataclass -import hashlib -import json -import os -from pathlib import Path -import random -import subprocess -import tempfile -from typing import Any, Callable, Iterable, Mapping, Sequence - -from agent.orchestration.agent_loop import ( - AgentLoopController, - FixedPipelinePolicy, - LoopConfig, - LoopEvent, - LoopTrace, - PrefetchNeighborFieldsPolicy, - PrefetchFieldMetadataPolicy, - ScriptedLoopPolicy, - ScriptedSkillExecutor, -) -from agent.orchestration.catalog import dynamic_loop_catalog -from agent.orchestration.contracts import MetadataRecord, StandardEntry -from agent.orchestration.model_skill_executor import ( - ModelLoopPolicy, - ModelSkillExecutor, - TextGenerator, - load_few_shot_messages, - make_standard_search_handler, - make_field_metadata_handler, - make_table_fields_handler, -) -from agent.orchestration.metadata_lookup import FieldMetadataLookup -from agent.orchestration.table_field_lookup import TableFieldLookup -from agent.orchestration.category_catalog import CategoryCatalog -from agent.orchestration.artifact_projection import project_trace -from agent.orchestration.runtime import KnowledgeBase -from agent.orchestration.runtime import Observation -from agent.orchestration.skill_loader import SkillLoader - - -ControllerFactory = Callable[[Mapping[str, Any]], AgentLoopController] - - -@dataclass(frozen=True) -class ArtifactPaths: - manifest: Path - traces: Path - summary: Path - observations: Path | None = None - model_calls: Path | None = None - trajectory: Path | None = None - evaluation: Path | None = None - - -def _read_json(path: Path) -> Any: - with path.open("r", encoding="utf-8") as handle: - return json.load(handle) - - -def _read_rows(path: Path) -> list[dict[str, Any]]: - if path.suffix.lower() == ".jsonl": - rows = [] - with path.open("r", encoding="utf-8") as handle: - for line_number, line in enumerate(handle, start=1): - if not line.strip(): - continue - value = json.loads(line) - if not isinstance(value, Mapping): - raise ValueError(f"row {line_number} in {path} must be an object") - rows.append(dict(value)) - return rows - value = _read_json(path) - if not isinstance(value, list) or any(not isinstance(row, Mapping) for row in value): - raise ValueError(f"{path} must contain a JSON list of objects") - return [dict(row) for row in value] - - -def _sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1024 * 1024), b""): - digest.update(chunk) - return digest.hexdigest() - - -def _file_entry(path: Path) -> dict[str, Any]: - return { - "path": str(path.resolve()), - "sha256": _sha256(path), - "bytes": path.stat().st_size, - } - - -def _registry_categories(value: Any) -> list[str]: - if isinstance(value, Mapping): - entries = value.get("categories") - else: - entries = value - if not isinstance(entries, list): - raise ValueError("registry must be a list or contain a categories list") - names: list[str] = [] - for entry in entries: - if isinstance(entry, str): - name = entry - elif isinstance(entry, Mapping): - name = str( - entry.get("category_id") - or entry.get("category") - or entry.get("name") - or entry.get("level_4") - or "" - ) - else: - name = "" - if name: - names.append(name) - return list(dict.fromkeys(names)) - - -def _registry_entry_map(value: Any) -> dict[str, dict[str, Any]]: - entries = value.get("categories") if isinstance(value, Mapping) else value - if not isinstance(entries, list): - raise ValueError("registry must be a list or contain a categories list") - result: dict[str, dict[str, Any]] = {} - for entry in entries: - if isinstance(entry, str): - normalized = {"category": entry, "description": entry, "grading_level": ""} - category = entry - elif isinstance(entry, Mapping): - category = str( - entry.get("category_id") - or entry.get("category") - or entry.get("name") - or entry.get("level_4") - or "" - ) - normalized = dict(entry) - normalized["category"] = category - else: - continue - if category: - if category in result: - raise ValueError(f"duplicate registry category {category!r}") - result[category] = normalized - return result - - -def select_pilot_rows( - rows: Iterable[Mapping[str, Any]], - *, - count: int, - seed: int, -) -> list[dict[str, Any]]: - """Select a stable pilot independent of input ordering and predictions.""" - - if count < 1: - raise ValueError("count must be positive") - normalized = [dict(row) for row in rows] - if any(not row.get("source_id") for row in normalized): - raise ValueError("every pilot row must have source_id") - normalized.sort(key=lambda row: str(row["source_id"])) - source_ids = [str(row["source_id"]) for row in normalized] - if len(set(source_ids)) != len(source_ids): - raise ValueError("pilot source_id values must be unique") - if count > len(normalized): - raise ValueError(f"requested {count} pilot rows from only {len(normalized)} rows") - rng = random.Random(seed) - rng.shuffle(normalized) - return normalized[:count] - - -def pending_rows_for_resume( - rows: Iterable[Mapping[str, Any]], - traces_path: str | Path, -) -> list[dict[str, Any]]: - """Return only rows whose source IDs are absent from an existing trace file.""" - - path = Path(traces_path) - completed: set[str] = set() - if path.is_file(): - for row in _read_rows(path): - source_id = row.get("source_id") - if source_id is not None: - completed.add(str(source_id)) - return [ - dict(row) - for row in rows - if str(row.get("source_id")) not in completed - ] - - -def _trace_from_dict(value: Mapping[str, Any]) -> LoopTrace: - return LoopTrace( - input=dict(value.get("input") or {}), - events=[ - LoopEvent( - kind=str(event.get("kind")), - turn=int(event.get("turn") or 0), - data=dict(event.get("data") or {}), - ) - for event in value.get("events", []) - if isinstance(event, Mapping) - ], - terminated=bool(value.get("terminated")), - final_result=( - dict(value["final_result"]) - if isinstance(value.get("final_result"), Mapping) - else None - ), - stop_reason=str(value.get("stop_reason") or "unknown"), - turns=int(value.get("turns") or 0), - state=dict(value.get("state") or {}), - ) - - -def _recalculate_saved_rows(rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]: - """Recompute a resumed summary from preserved traces without model calls.""" - - replay_rows: list[dict[str, Any]] = [] - traces: dict[str, LoopTrace] = {} - for index, raw in enumerate(rows): - trace_value = raw.get("trace") - if not isinstance(trace_value, Mapping): - raise ValueError("saved row is missing its trace object") - source_id = str(raw.get("source_id") or f"saved-{index}") - trace = _trace_from_dict(trace_value) - traces[source_id] = trace - replay_rows.append( - { - "source_id": source_id, - "domain": trace.input.get("domain"), - "field_name": trace.input.get("field_name"), - "ground_truth": raw.get("ground_truth"), - "ground_truth_level": raw.get("ground_truth_level"), - } - ) - - class ReplayController: - def __init__(self, trace: LoopTrace) -> None: - self.trace = trace - - def run(self, _record: MetadataRecord) -> LoopTrace: - return self.trace - - return evaluate_agent_rows( - replay_rows, - lambda row: ReplayController(traces[str(row["source_id"])]), - ) - - -def load_experiment_variants(path: str | Path) -> list[dict[str, Any]]: - """Expand and validate the checked-in A/B/C experiment contract.""" - - payload = _read_json(Path(path)) - if not isinstance(payload, Mapping): - raise ValueError("experiment config must be an object") - common = payload.get("common") - raw_variants = payload.get("variants") - if not isinstance(common, Mapping) or not isinstance(raw_variants, list): - raise ValueError("experiment config requires common and variants") - variants: list[dict[str, Any]] = [] - for raw in raw_variants: - if not isinstance(raw, Mapping): - raise ValueError("each experiment variant must be an object") - variant = dict(common) - variant.update(dict(raw)) - variants.append(variant) - if [item.get("id") for item in variants] != ["A", "B", "C"]: - raise ValueError("variants must be ordered A, B, C") - if variants[0].get("policy") != "fixed" or any( - variants[index].get("policy") != "dynamic" for index in (1, 2) - ): - raise ValueError("A must be fixed and B/C must be dynamic") - if variants[1].get("few_shot") is not None or not variants[2].get("few_shot"): - raise ValueError("B must omit few-shot and C must enable it") - return variants - - -def build_model_controller( - *, - generate: TextGenerator, - policy_mode: str, - skill_root: str | Path, - registry_entries: Mapping[str, Mapping[str, Any]], - config: LoopConfig | None = None, - few_shot_messages: Sequence[Mapping[str, str]] = (), - top_k: int = 5, - metadata_lookup: FieldMetadataLookup | None = None, - table_field_lookup: TableFieldLookup | None = None, - neighbor_prefetch: bool = False, - metadata_prefetch: bool = False, - include_description_skills: bool = False, - topk_evidence_mode: str = "augmented", - topk_selection_mode: str = "single", - topk_selection_seed: int = 20260930, - top1_evidence_mode: str = "all", - top1_selection_mode: str = "model", - classification_mode: str = "legacy", -) -> AgentLoopController: - """Assemble one model-backed controller without importing Transformers.""" - - if classification_mode not in {"legacy", "two-stage"}: - raise ValueError("classification_mode must be legacy or two-stage") - if classification_mode == "two-stage" and policy_mode == "fixed": - raise ValueError("two-stage mode currently requires the dynamic policy") - if neighbor_prefetch and table_field_lookup is None: - raise ValueError("neighbor_prefetch requires table_field_lookup") - if neighbor_prefetch and policy_mode != "dynamic": - raise ValueError("neighbor_prefetch requires the dynamic policy") - if metadata_prefetch and ( - policy_mode != "dynamic" or classification_mode != "two-stage" - or metadata_lookup is None or not include_description_skills - ): - raise ValueError("metadata_prefetch requires dynamic two-stage classification, metadata_lookup and description Skills") - if include_description_skills and metadata_lookup is None: - raise ValueError("description Skills require metadata_lookup") - if include_description_skills and (classification_mode != "two-stage" or policy_mode != "dynamic"): - raise ValueError("description Skills require dynamic two-stage classification") - if topk_selection_mode not in {"single", "balanced-vote"}: - raise ValueError("topk_selection_mode must be single or balanced-vote") - if topk_selection_mode == "balanced-vote" and (classification_mode != "two-stage" or policy_mode != "dynamic"): - raise ValueError("balanced-vote requires dynamic two-stage classification") - if topk_evidence_mode not in {"augmented", "raw", "raw-flat"}: - raise ValueError("topk_evidence_mode must be augmented, raw or raw-flat") - if topk_evidence_mode in {"raw", "raw-flat"} and not include_description_skills: - raise ValueError("raw Top-K evidence mode requires description Skills") - two_stage = classification_mode == "two-stage" - catalog = dynamic_loop_catalog( - include_field_metadata=metadata_lookup is not None, - include_table_fields=table_field_lookup is not None, - include_description_skills=include_description_skills, - two_stage=two_stage, - ) - loader = SkillLoader( - skill_root, catalog, - extra_roots=( - *((Path(skill_root) / "metadata_extra",) if metadata_lookup is not None else ()), - *((Path(skill_root) / "neighbor_extra",) if table_field_lookup is not None else ()), - *((Path(skill_root) / "semantic_extra",) if include_description_skills else ()), - *((Path(skill_root) / "two_stage",) if two_stage else ()), - ), - strict_catalog=not two_stage, - ) - standards = tuple( - StandardEntry( - category=str(category), - description=str(entry.get("description") or entry.get("definition") or category), - grading_level=str(entry.get("grading_level") or ""), - ) - for category, entry in registry_entries.items() - ) - knowledge_base = KnowledgeBase.from_mappings([], standards) - handlers = {"SEARCH_STANDARD": make_standard_search_handler(knowledge_base, top_k=top_k)} - if metadata_lookup is not None: - handlers["GET_FIELD_METADATA"] = make_field_metadata_handler(metadata_lookup) - if table_field_lookup is not None: - handlers["GET_TABLE_FIELDS"] = make_table_fields_handler(table_field_lookup) - executor = ModelSkillExecutor( - generate, - loader, - deterministic_handlers=handlers, - category_catalog=CategoryCatalog(registry_entries) if two_stage else None, - top_k=top_k, - guard_two_stage_evidence=include_description_skills, - topk_evidence_mode=topk_evidence_mode, - topk_selection_mode=topk_selection_mode, - topk_selection_seed=topk_selection_seed, - top1_evidence_mode=top1_evidence_mode, - top1_selection_mode=top1_selection_mode, - ) - if policy_mode == "fixed": - policy = FixedPipelinePolicy() - elif policy_mode == "dynamic": - policy = ModelLoopPolicy( - generate, - few_shot_messages=few_shot_messages, - metadata_guidance=metadata_lookup is not None, - two_stage=two_stage, - description_skills=include_description_skills, - ) - if neighbor_prefetch: - policy = PrefetchNeighborFieldsPolicy(policy) - if metadata_prefetch: - policy = PrefetchFieldMetadataPolicy(policy) - else: - raise ValueError("policy_mode must be fixed or dynamic") - return AgentLoopController( - policy=policy, - executor=executor, - catalog=catalog, - skill_loader=loader, - config=config or LoopConfig(), - registry_entries=registry_entries, - ) - - -def build_run_manifest( - *, - dataset_id: str, - input_path: str | Path, - registry_path: str | Path, - corpus_path: str | Path | None, - code_revision: str, - sample_count: int, - seed: int, - behavior_files: Mapping[str, str | Path] | None = None, - model: Mapping[str, Any] | None = None, - loop_config: Mapping[str, Any] | None = None, - working_tree_dirty: bool | None = None, -) -> dict[str, Any]: - """Build an auditable CPU-run manifest from exact files.""" - - input_file = Path(input_path) - registry_file = Path(registry_path) - corpus_file = Path(corpus_path) if corpus_path is not None else None - categories = _registry_categories(_read_json(registry_file)) - files = { - "input": _file_entry(input_file), - "registry": _file_entry(registry_file), - } - if corpus_file is not None: - files["corpus"] = _file_entry(corpus_file) - for name, path in (behavior_files or {}).items(): - files[str(name)] = _file_entry(Path(path)) - default_loop_config = { - "max_turns": 8, - "max_identical_calls": 2, - "action_retries": 1, - "forced_finalize_retries": 1, - "repetition_retries": 1, - } - default_loop_config.update(dict(loop_config or {})) - return { - "dataset_id": dataset_id, - "sample_count": sample_count, - "seed": seed, - "input_fields": ["domain", "field_name"], - "category_count": len(categories), - "approved_levels": ["L1", "L2", "L3", "L4"], - "code_revision": code_revision, - "files": files, - "model": dict(model or {"loaded": False, "backend": "scripted-cpu"}), - "loop_config": default_loop_config, - "working_tree_dirty": working_tree_dirty, - } - - -def _record_from_row(row: Mapping[str, Any]) -> MetadataRecord: - raw = row.get("record") - source = dict(raw) if isinstance(raw, Mapping) else dict(row) - return MetadataRecord.from_mapping( - { - "domain": source.get("domain"), - "field_name": source.get("field_name") - or (source.get("metadata") or {}).get("field_name"), - "source_id": row.get("source_id"), - } - ) - - -def _trace_tool_stats(trace: LoopTrace) -> tuple[int, int]: - observations = [event for event in trace.events if event.kind == "observation"] - successes = sum(event.data.get("status") == "success" for event in observations) - return len(observations), successes - - -def _macro_f1(scored: Sequence[Mapping[str, Any]]) -> float: - labels = sorted( - { - str(value) - for row in scored - for value in (row.get("ground_truth"), row.get("predicted_category")) - if value is not None - } - ) - if not labels: - return 0.0 - scores: list[float] = [] - for label in labels: - true_positive = sum( - row.get("ground_truth") == label and row.get("predicted_category") == label - for row in scored - ) - false_positive = sum( - row.get("ground_truth") != label and row.get("predicted_category") == label - for row in scored - ) - false_negative = sum( - row.get("ground_truth") == label and row.get("predicted_category") != label - for row in scored - ) - denominator = (2 * true_positive) + false_positive + false_negative - scores.append((2 * true_positive) / denominator if denominator else 0.0) - return sum(scores) / len(scores) - - -def evaluate_agent_rows( - rows: Iterable[Mapping[str, Any]], - controller_factory: ControllerFactory, -) -> dict[str, Any]: - """Run loops while keeping evaluation labels outside controller state.""" - - scored: list[dict[str, Any]] = [] - total_calls = 0 - successful_calls = 0 - for index, raw in enumerate(rows): - row = dict(raw) - record = _record_from_row(row) - trace = controller_factory(row).run(record) - calls, successes = _trace_tool_stats(trace) - total_calls += calls - successful_calls += successes - final = trace.final_result or {} - predicted_category = final.get("category") - predicted_level = final.get("grading_level") - expected_category = row.get("ground_truth") - expected_level = row.get("ground_truth_level") - category_correct = bool(trace.terminated and predicted_category == expected_category) - level_correct = bool(trace.terminated and predicted_level == expected_level) - scored.append( - { - "index": index, - "source_id": row.get("source_id"), - "ground_truth": expected_category, - "ground_truth_level": expected_level, - "predicted_category": predicted_category, - "predicted_level": predicted_level, - "category_correct": category_correct, - "level_correct": level_correct, - "joint_correct": category_correct and level_correct, - "stop_reason": trace.stop_reason, - "trace": trace.to_dict(), - } - ) - - total = len(scored) - terminal = sum(bool(row["trace"]["terminated"]) for row in scored) - category_correct = sum(bool(row["category_correct"]) for row in scored) - level_correct = sum(bool(row["level_correct"]) for row in scored) - joint_correct = sum(bool(row["joint_correct"]) for row in scored) - retry_count = sum( - event["kind"] == "retry" - for row in scored - for event in row["trace"]["events"] - ) - repetition_interventions = sum( - event["kind"] == "controller_intervention" - and event["data"].get("reason") == "repetition_limit" - for row in scored - for event in row["trace"]["events"] - ) - format_failures = sum( - event["kind"] in {"retry", "rejected_action"} - and event["data"].get("reason") == "invalid_action" - for row in scored - for event in row["trace"]["events"] - ) - legal_action_failures = sum( - event["kind"] in {"retry", "rejected_action"} - and event["data"].get("reason") in {"uncallable_skill", "invalid_arguments"} - for row in scored - for event in row["trace"]["events"] - ) - early_stop_attempts = sum( - event["kind"] in {"retry", "rejected_action"} - and event["data"].get("reason") == "stop_without_final_result" - for row in scored - for event in row["trace"]["events"] - ) - accepted_action_turns = sum( - event["kind"] == "policy_action" - or ( - event["kind"] == "controller_intervention" - and event["data"].get("reason") == "repetition_limit" - ) - for row in scored - for event in row["trace"]["events"] - ) - rejected_action_turns = sum( - event["kind"] == "rejected_action" - for row in scored - for event in row["trace"]["events"] - ) - action_turns = accepted_action_turns + rejected_action_turns - policy_actions = sum( - event["kind"] == "policy_action" - for row in scored - for event in row["trace"]["events"] - ) - parsed_but_rejected = legal_action_failures + repetition_interventions - policy_response_attempts = ( - policy_actions - + parsed_but_rejected - + format_failures - + early_stop_attempts - ) - parsed_policy_responses = policy_actions + parsed_but_rejected - terminal_validation_failures = sum( - event["kind"] == "retry" and event["data"].get("reason") == "invalid_terminal" - for row in scored - for event in row["trace"]["events"] - ) - forced_finalizations = sum( - event["kind"] == "policy_action" and bool(event["data"].get("forced_finalize")) - for row in scored - for event in row["trace"]["events"] - ) - forced_finalization_missing_evidence = sum( - event["kind"] == "controller_intervention" - and event["data"].get("reason") == "forced_finalization_missing_evidence" - for row in scored - for event in row["trace"]["events"] - ) - forced_terminations = 0 - normal_terminations = 0 - retrieval_hits = 0 - retrieval_rows = 0 - neighbor_field_call_rows = 0 - neighbor_field_calls = 0 - description_skill_call_rows = 0 - description_skill_calls = 0 - required_input_violations = 0 - total_tokens = 0 - measured_elapsed_seconds = 0.0 - measured_model_calls = 0 - skill_correction_attempts = 0 - for row in scored: - events = row["trace"]["events"] - row_neighbor_calls = sum( - event["kind"] == "observation" - and event["data"].get("skill") == "GET_TABLE_FIELDS" - for event in events - ) - neighbor_field_calls += row_neighbor_calls - neighbor_field_call_rows += row_neighbor_calls > 0 - row_description_calls = sum( - event["kind"] == "observation" - and event["data"].get("skill") in { - "INTERPRET_FIELD_DESCRIPTION", "INTERPRET_TABLE_DESCRIPTION" - } - for event in events - ) - description_skill_calls += row_description_calls - description_skill_call_rows += row_description_calls > 0 - if row["trace"]["terminated"]: - final_actions = [ - event - for event in events - if event["kind"] == "policy_action" - and event["data"].get("call", {}).get("tool") == "FINALIZE_CLASSIFICATION" - ] - if final_actions and final_actions[-1]["data"].get("forced_finalize"): - forced_terminations += 1 - else: - normal_terminations += 1 - retrieval = [ - event for event in events - if event["kind"] == "observation" - and event["data"].get("skill") in {"SEARCH_STANDARD", "SELECT_CATEGORY_TOPK"} - and event["data"].get("status") == "success" - ] - if retrieval: - retrieval_rows += 1 - candidates = retrieval[-1]["data"].get("data", {}).get("standard_candidates", []) - expected = row.get("ground_truth") - if any( - isinstance(candidate, Mapping) - and (candidate.get("category") or candidate.get("category_id")) == expected - for candidate in candidates - ): - retrieval_hits += 1 - for event in events: - metadata = event["data"].get("metadata", {}) - if event["kind"] == "observation" and metadata.get("required_input_violation"): - required_input_violations += 1 - if event["kind"] == "observation": - skill_correction_attempts += max( - int(metadata.get("format_retry_count", int(metadata.get("model_call_count") or 1) - 1)), 0 - ) - token_usage = metadata.get("token_usage") - if isinstance(token_usage, Mapping): - total_tokens += int(token_usage.get("total_tokens") or 0) - elapsed = metadata.get("elapsed_seconds") - if isinstance(elapsed, (int, float)): - measured_elapsed_seconds += float(elapsed) - measured_model_calls += int(metadata.get("model_call_count") or 1) - return { - "total": total, - "terminal_results": terminal, - "termination_rate": terminal / total if total else 0.0, - "tool_calls": total_calls, - "successful_tool_calls": successful_calls, - "tool_execution_success_rate": successful_calls / total_calls if total_calls else 1.0, - "category_correct": category_correct, - "level_correct": level_correct, - "joint_correct": joint_correct, - "category_accuracy": category_correct / total if total else 0.0, - "level_accuracy": level_correct / total if total else 0.0, - "joint_accuracy": joint_correct / total if total else 0.0, - "category_macro_f1": _macro_f1(scored), - "average_tool_calls": total_calls / total if total else 0.0, - "neighbor_field_calls": neighbor_field_calls, - "neighbor_field_call_rows": neighbor_field_call_rows, - "neighbor_field_call_rate": neighbor_field_call_rows / total if total else 0.0, - "description_skill_calls": description_skill_calls, - "description_skill_call_rows": description_skill_call_rows, - "description_skill_call_rate": description_skill_call_rows / total if total else 0.0, - "action_turns": action_turns, - "accepted_action_turns": accepted_action_turns, - "action_parse_rate_after_retry": ( - accepted_action_turns / action_turns if action_turns else 0.0 - ), - "policy_response_attempts": policy_response_attempts, - "json_object_parse_rate": ( - parsed_policy_responses / policy_response_attempts - if policy_response_attempts - else 0.0 - ), - "legal_action_rate_given_parsed": ( - policy_actions / parsed_policy_responses if parsed_policy_responses else 0.0 - ), - "retry_count": retry_count, - "format_failures": format_failures, - "legal_action_failures": legal_action_failures, - "early_stop_attempts": early_stop_attempts, - "terminal_validation_failures": terminal_validation_failures, - "early_stop_recoveries": sum( - bool(row["trace"]["terminated"]) - and any( - event["data"].get("reason") == "stop_without_final_result" - for event in row["trace"]["events"] - if event["kind"] == "retry" - ) - for row in scored - ), - "repetition_interventions": repetition_interventions, - "repetition_recoveries": sum( - bool(row["trace"]["terminated"]) - and any( - event["kind"] == "controller_intervention" - and event["data"].get("reason") == "repetition_limit" - and bool(event["data"].get("recovered")) - for event in row["trace"]["events"] - ) - for row in scored - ), - "forced_finalizations": forced_finalizations, - "forced_finalization_missing_evidence": forced_finalization_missing_evidence, - "normal_terminations": normal_terminations, - "forced_terminations": forced_terminations, - "retrieval_recall_at_5": retrieval_hits / retrieval_rows if retrieval_rows else 0.0, - "retrieval_evaluated_rows": retrieval_rows, - "required_input_violations_reaching_execution": required_input_violations, - "total_tokens": total_tokens if measured_model_calls else None, - "measured_model_calls": measured_model_calls, - "skill_correction_attempts": skill_correction_attempts, - "measured_elapsed_seconds": ( - measured_elapsed_seconds if measured_model_calls else None - ), - "stop_reasons": { - reason: sum(row["stop_reason"] == reason for row in scored) - for reason in sorted({str(row["stop_reason"]) for row in scored}) - }, - "rows": scored, - } - - -def write_run_artifacts( - output_dir: str | Path, - manifest: Mapping[str, Any], - report: Mapping[str, Any], - *, - classification_mode: str = "legacy", -) -> ArtifactPaths: - """Write manifest, one trace row per sample, and aggregate summary.""" - - root = Path(output_dir) - root.mkdir(parents=True, exist_ok=True) - paths = ArtifactPaths( - manifest=root / "manifest.json", - traces=root / "traces.jsonl", - summary=root / "summary.json", - observations=root / "observations.jsonl" if classification_mode == "two-stage" else None, - model_calls=root / "model_calls.jsonl" if classification_mode == "two-stage" else None, - trajectory=root / "trajectory.jsonl" if classification_mode == "two-stage" else None, - evaluation=root / "evaluation.jsonl" if classification_mode == "two-stage" else None, - ) - rows = report.get("rows", []) - projected = [project_trace(row) for row in rows] if classification_mode == "two-stage" else [] - _atomic_write_text( - paths.manifest, json.dumps(dict(manifest), ensure_ascii=False, indent=2) + "\n" - ) - _atomic_write_text(paths.traces, _jsonl_text(rows)) - if classification_mode == "two-stage": - for name, target in ( - ("observations", paths.observations), - ("model_calls", paths.model_calls), - ("trajectory", paths.trajectory), - ("evaluation", paths.evaluation), - ): - assert target is not None - records = [] - for item in projected: - payload = item[name] - records.extend(payload if isinstance(payload, list) else [payload]) - _atomic_write_text(target, _jsonl_text(records)) - summary = {key: value for key, value in report.items() if key != "rows"} - _atomic_write_text(paths.summary, json.dumps(summary, ensure_ascii=False, indent=2) + "\n") - return paths - - -def _jsonl_text(rows: Iterable[Mapping[str, Any]]) -> str: - return "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows) - - -def _atomic_write_text(path: Path, content: str) -> None: - """Replace one completed artifact atomically within its output directory.""" - - with tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", dir=path.parent, - prefix=f".{path.name}.", suffix=".tmp", delete=False, - ) as handle: - temp_path = Path(handle.name) - try: - handle.write(content) - except BaseException: - temp_path.unlink(missing_ok=True) - raise - try: - os.replace(temp_path, path) - finally: - temp_path.unlink(missing_ok=True) - - -def _git_revision() -> str: - try: - return subprocess.check_output( - ["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL - ).strip() - except (OSError, subprocess.CalledProcessError): - return "unknown" - - -def _git_dirty() -> bool | None: - try: - output = subprocess.check_output( - ["git", "status", "--porcelain"], text=True, stderr=subprocess.DEVNULL - ) - return bool(output.strip()) - except (OSError, subprocess.CalledProcessError): - return None - - -def _skill_behavior_files( - skill_root: Path, *, classification_mode: str = "legacy", - include_metadata_extra: bool = False, - include_table_fields: bool = False, - include_description_skills: bool = False, -) -> dict[str, Path]: - files = { - f"skill:{path.name}": path - for path in sorted(skill_root.glob("*.md")) - if path.is_file() - } - if classification_mode == "two-stage": - files.update({ - f"skill:two_stage/{path.name}": path - for path in sorted((skill_root / "two_stage").glob("*.md")) - if path.is_file() - }) - if include_metadata_extra: - files.update({ - f"skill:metadata_extra/{path.name}": path - for path in (skill_root / "metadata_extra" / "metadata_acquisition_GET_FIELD_METADATA.md",) - if path.is_file() - }) - if include_table_fields: - path = skill_root / "neighbor_extra" / "metadata_acquisition_GET_TABLE_FIELDS.md" - if path.is_file(): - files[f"skill:neighbor_extra/{path.name}"] = path - if include_description_skills: - for path in sorted((skill_root / "semantic_extra").glob("*.md")): - files[f"skill:semantic_extra/{path.name}"] = path - return files - - -def _observation(raw: Mapping[str, Any], tool: str) -> Observation: - return Observation( - skill=str(raw.get("skill") or tool), - status=str(raw.get("status") or "success"), - summary=str(raw.get("summary") or tool), - data=dict(raw.get("data") or {}), - ) - - -def _scripted_factory( - scripts: Mapping[str, Any], - skill_root: Path, - registry_categories: Sequence[str], -) -> ControllerFactory: - catalog = dynamic_loop_catalog() - - def factory(row: Mapping[str, Any]) -> AgentLoopController: - source_id = str(row.get("source_id")) - sample = scripts.get(source_id) - if not isinstance(sample, Mapping): - raise ValueError(f"missing scripted responses for source_id={source_id!r}") - raw_outputs = sample.get("observations", {}) - if not isinstance(raw_outputs, Mapping): - raise ValueError(f"observations for {source_id!r} must be an object") - outputs = { - str(tool): [_observation(item, str(tool)) for item in values] - for tool, values in raw_outputs.items() - } - config_raw = sample.get("config", {}) - return AgentLoopController( - policy=ScriptedLoopPolicy(sample.get("actions", [])), - executor=ScriptedSkillExecutor(outputs), - catalog=catalog, - skill_loader=SkillLoader(skill_root, catalog), - config=LoopConfig(**dict(config_raw)), - registry_categories=registry_categories, - ) - - return factory - - -def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--input", required=True, type=Path) - parser.add_argument("--backend", choices=("scripted", "transformers"), default="scripted") - parser.add_argument("--responses", type=Path) - parser.add_argument("--policy", choices=("fixed", "dynamic"), default="dynamic") - parser.add_argument("--classification-mode", choices=("legacy", "two-stage"), default="legacy") - parser.add_argument("--model", type=Path) - parser.add_argument("--few-shot", type=Path) - parser.add_argument("--max-new-tokens", type=int, default=512) - parser.add_argument("--enable-thinking", action="store_true") - parser.add_argument("--allow-remote-model-files", action="store_true") - parser.add_argument("--top-k", type=int, default=5) - parser.add_argument("--max-turns", type=int, default=8) - parser.add_argument("--max-identical-calls", type=int, default=2) - parser.add_argument("--action-retries", type=int, default=1) - parser.add_argument("--forced-finalize-retries", type=int, default=1) - parser.add_argument("--repetition-retries", type=int, default=1) - parser.add_argument("--resume", action="store_true") - parser.add_argument("--registry", required=True, type=Path) - parser.add_argument("--corpus", type=Path) - parser.add_argument("--metadata-source", type=Path) - parser.add_argument("--neighbor-fields", action="store_true") - parser.add_argument("--neighbor-prefetch", action="store_true") - parser.add_argument("--description-skills", action="store_true") - parser.add_argument("--topk-evidence-mode", choices=("augmented", "raw", "raw-flat"), default="augmented") - parser.add_argument("--topk-selection-mode", choices=("single", "balanced-vote"), default="single") - parser.add_argument("--topk-selection-seed", type=int, default=20260930) - parser.add_argument("--skill-root", type=Path, default=Path("skills")) - parser.add_argument("--output", required=True, type=Path) - parser.add_argument("--dataset-id", required=True) - parser.add_argument("--seed", type=int, default=20260921) - parser.add_argument("--pilot-count", type=int) - return parser - - -def main(argv: Sequence[str] | None = None) -> int: - args = _parser().parse_args(argv) - if args.topk_selection_mode == "balanced-vote" and ( - args.classification_mode != "two-stage" or args.policy != "dynamic" or args.backend != "transformers" - ): - raise ValueError("balanced-vote requires transformers and dynamic two-stage classification") - if args.topk_evidence_mode in {"raw", "raw-flat"} and not args.description_skills: - raise ValueError("raw Top-K evidence mode requires --description-skills") - if args.neighbor_prefetch and not args.neighbor_fields: - raise ValueError("--neighbor-prefetch requires --neighbor-fields") - if args.neighbor_fields and args.metadata_source is None: - raise ValueError("--neighbor-fields requires --metadata-source") - if args.neighbor_fields and args.backend != "transformers": - raise ValueError("--neighbor-fields requires the transformers backend") - if args.neighbor_fields and args.policy != "dynamic": - raise ValueError("--neighbor-fields currently requires --policy dynamic") - if args.description_skills and ( - args.metadata_source is None or args.backend != "transformers" - or args.policy != "dynamic" or args.classification_mode != "two-stage" - ): - raise ValueError("--description-skills requires transformers, dynamic two-stage, and --metadata-source") - if args.classification_mode == "two-stage" and args.backend != "transformers": - raise ValueError("two-stage requires the transformers backend") - if args.classification_mode == "two-stage" and args.policy != "dynamic": - raise ValueError("two-stage currently supports only the dynamic policy") - prior_manifest = args.output / "manifest.json" - if args.resume and not prior_manifest.is_file() and args.output.is_dir(): - prior_results = ( - "traces.jsonl", "summary.json", "observations.jsonl", "model_calls.jsonl", - "trajectory.jsonl", "evaluation.jsonl", - ) - if any((args.output / name).is_file() and (args.output / name).stat().st_size > 0 - for name in prior_results): - raise ValueError("cannot resume existing results without manifest.json") - if args.resume and prior_manifest.is_file(): - previous = _read_json(prior_manifest) - model = previous.get("model", {}) if isinstance(previous, Mapping) else {} - prior_selection = model.get("topk_selection_mode", "single") if isinstance(model, Mapping) else "single" - prior_seed = model.get("topk_selection_seed", 20260930) if isinstance(model, Mapping) else 20260930 - if prior_selection != args.topk_selection_mode: - raise ValueError("cannot resume artifacts from a different Top-K selection mode") - if prior_seed != args.topk_selection_seed: - raise ValueError("cannot resume artifacts from a different Top-K selection seed") - prior_mode = model.get("classification_mode", "legacy") if isinstance(model, Mapping) else "legacy" - if prior_mode != args.classification_mode: - raise ValueError("cannot resume artifacts from a different classification mode") - prior_neighbors = bool(model.get("neighbor_fields_dsl_enabled", False)) if isinstance(model, Mapping) else False - if prior_neighbors != args.neighbor_fields: - raise ValueError("cannot resume artifacts from a different neighbor-fields mode") - prior_prefetch = model.get("neighbor_fields_mode") == "prefetch" if isinstance(model, Mapping) else False - if prior_prefetch != args.neighbor_prefetch: - raise ValueError("cannot resume artifacts from a different neighbor prefetch mode") - prior_descriptions = bool(model.get("description_skills_enabled", False)) if isinstance(model, Mapping) else False - if prior_descriptions != args.description_skills: - raise ValueError("cannot resume artifacts from a different description-Skill mode") - prior_topk_mode = model.get("topk_evidence_mode", "augmented") if isinstance(model, Mapping) else "augmented" - if prior_topk_mode != args.topk_evidence_mode: - raise ValueError("cannot resume artifacts from a different Top-K evidence mode") - files = previous.get("files", {}) if isinstance(previous, Mapping) else {} - prior_has_source = isinstance(files, Mapping) and "metadata_source" in files - current_has_source = args.metadata_source is not None - if prior_has_source != current_has_source: - raise ValueError("cannot resume artifacts from a different metadata source configuration") - if current_has_source: - source_entry = files.get("metadata_source", {}) if isinstance(files, Mapping) else {} - prior_hash = source_entry.get("sha256") if isinstance(source_entry, Mapping) else None - if not isinstance(prior_hash, str) or prior_hash != _sha256(args.metadata_source): - source_kind = "neighbor metadata" if args.neighbor_fields else "metadata" - raise ValueError(f"cannot resume artifacts from a different {source_kind} source") - rows = _read_rows(args.input) - if args.pilot_count is not None: - rows = select_pilot_rows(rows, count=args.pilot_count, seed=args.seed) - intended_sample_count = len(rows) - traces_path = args.output / "traces.jsonl" - if args.output.exists() and any(args.output.iterdir()) and not args.resume: - raise FileExistsError(f"output directory is not empty: {args.output}; use --resume") - existing_scored = _read_rows(traces_path) if args.resume and traces_path.is_file() else [] - if args.resume: - rows = pending_rows_for_resume(rows, traces_path) - registry_value = _read_json(args.registry) - registry_categories = _registry_categories(registry_value) - registry_entries = _registry_entry_map(registry_value) - loop_config = LoopConfig( - max_turns=args.max_turns, - max_identical_calls=args.max_identical_calls, - action_retries=args.action_retries, - forced_finalize_retries=args.forced_finalize_retries, - repetition_retries=args.repetition_retries, - ) - behavior_files = _skill_behavior_files( - args.skill_root, classification_mode=args.classification_mode, - include_metadata_extra=args.backend == "transformers" and args.metadata_source is not None, - include_table_fields=args.neighbor_fields, - include_description_skills=args.description_skills, - ) - if args.backend == "scripted": - if args.responses is None: - raise ValueError("--responses is required for the scripted backend") - response_payload = _read_json(args.responses) - if not isinstance(response_payload, Mapping) or not isinstance( - response_payload.get("samples"), Mapping - ): - raise ValueError("responses must contain a samples object") - behavior_files["scripted_responses"] = args.responses - factory = _scripted_factory( - response_payload["samples"], - args.skill_root, - registry_categories, - ) - model_manifest: dict[str, Any] = { - "loaded": False, - "backend": "scripted-cpu", - "sample_config_overrides": { - str(source_id): dict(sample.get("config") or {}) - for source_id, sample in response_payload["samples"].items() - if isinstance(sample, Mapping) and sample.get("config") - }, - } - else: - if args.model is None: - raise ValueError("--model is required for the transformers backend") - from agent.orchestration.planner import TransformersTextGenerator - - generate = TransformersTextGenerator( - args.model, - max_new_tokens=args.max_new_tokens, - local_files_only=not args.allow_remote_model_files, - enable_thinking=args.enable_thinking, - ) - few_shot_messages = load_few_shot_messages(args.few_shot) if args.few_shot else () - metadata_lookup = ( - FieldMetadataLookup.from_canonical(args.metadata_source) - if args.metadata_source else None - ) - table_field_lookup = ( - TableFieldLookup.from_canonical(args.metadata_source) - if args.neighbor_fields else None - ) - if args.metadata_source: - behavior_files["metadata_source"] = args.metadata_source - if args.few_shot: - behavior_files["few_shot"] = args.few_shot - - def factory(_row: Mapping[str, Any]) -> AgentLoopController: - return build_model_controller( - generate=generate, - policy_mode=args.policy, - skill_root=args.skill_root, - registry_entries=registry_entries, - config=loop_config, - few_shot_messages=few_shot_messages, - top_k=args.top_k, - metadata_lookup=metadata_lookup, - table_field_lookup=table_field_lookup, - neighbor_prefetch=args.neighbor_prefetch, - include_description_skills=args.description_skills, - topk_evidence_mode=args.topk_evidence_mode, - topk_selection_mode=args.topk_selection_mode, - topk_selection_seed=args.topk_selection_seed, - classification_mode=args.classification_mode, - ) - - model_manifest = { - "loaded": True, - "backend": "transformers", - "name_or_path": str(args.model), - "local_files_only": not args.allow_remote_model_files, - "enable_thinking": args.enable_thinking, - "max_new_tokens": args.max_new_tokens, - "do_sample": False, - "policy": args.policy, - "few_shot": bool(args.few_shot), - "retrieval": { - "backend": ( - "model-full-catalog-short-options" if args.classification_mode == "two-stage" - else "deterministic-lexical" - ), - "top_k": args.top_k, - "selection_id_scheme": ( - "sorted-canonical-c001-v1" - if args.classification_mode == "two-stage" else None - ), - }, - "classification_mode": args.classification_mode, - "metadata_dsl_enabled": metadata_lookup is not None, - "neighbor_fields_dsl_enabled": table_field_lookup is not None, - "description_skills_enabled": args.description_skills, - "topk_evidence_mode": args.topk_evidence_mode, - "neighbor_fields_mode": ( - "prefetch" if args.neighbor_prefetch else - "optional" if table_field_lookup else "off" - ), - "neighbor_fields_limit": table_field_lookup.max_fields if table_field_lookup else None, - "neighbor_fields_source_policy": ( - "cross-split-unlabeled-table-metadata" if table_field_lookup else None - ), - } - from agent.orchestration.topk_selection import SELECTION_POLICY - - model_manifest.update({ - "topk_selection_mode": args.topk_selection_mode, - "topk_selection_seed": args.topk_selection_seed, - "topk_selection_algorithm": SELECTION_POLICY if args.topk_selection_mode == "balanced-vote" else "single-with-one-format-retry", - "topk_selection_rounds": 3 if args.topk_selection_mode == "balanced-vote" else 1, - "topk_selection_quorum": 2 if args.topk_selection_mode == "balanced-vote" else 1, - }) - report = evaluate_agent_rows(rows, factory) - if existing_scored: - report = _recalculate_saved_rows([*existing_scored, *report["rows"]]) - manifest = build_run_manifest( - dataset_id=args.dataset_id, - input_path=args.input, - registry_path=args.registry, - corpus_path=args.corpus, - code_revision=_git_revision(), - sample_count=intended_sample_count, - seed=args.seed, - behavior_files=behavior_files, - model=model_manifest, - loop_config=loop_config.__dict__, - working_tree_dirty=_git_dirty(), - ) - paths = write_run_artifacts(args.output, manifest, report, - classification_mode=args.classification_mode) - print( - json.dumps( - { - "manifest": str(paths.manifest), - "traces": str(paths.traces), - "summary": str(paths.summary), - **{key: value for key, value in report.items() if key != "rows"}, - }, - ensure_ascii=False, - indent=2, - ) - ) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) - - -__all__ = [ - "ArtifactPaths", - "build_model_controller", - "build_run_manifest", - "evaluate_agent_rows", - "load_experiment_variants", - "main", - "pending_rows_for_resume", - "select_pilot_rows", - "write_run_artifacts", -] diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_ASSESS_CATEGORY_SUPPORT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_ASSESS_CATEGORY_SUPPORT.md deleted file mode 100644 index 0624414..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_ASSESS_CATEGORY_SUPPORT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ASSESS_CATEGORY_SUPPORT -dsl: evidence_reasoning -required_inputs: [candidate_category, evidence] -optional_inputs: [] -produces: [category_support] -terminal: false ---- -# ASSESS_CATEGORY_SUPPORT - -Purpose: Assesses how strongly the current evidence supports a candidate category. - -Observation: 输出自然语言支持评估:支持证据、反对证据、薄弱点和总体判断。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["category_support"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_CHECK_EVIDENCE_SUFFICIENCY.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_CHECK_EVIDENCE_SUFFICIENCY.md deleted file mode 100644 index cb91800..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_CHECK_EVIDENCE_SUFFICIENCY.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: CHECK_EVIDENCE_SUFFICIENCY -dsl: evidence_reasoning -required_inputs: [current_evidence] -optional_inputs: [] -produces: [evidence_sufficiency] -terminal: false ---- -# Role -Judge whether the current evidence supports category and grading decisions. - -# Evidence boundaries -Use only the supplied evidence state. Missing evidence must remain missing; do not infer ground truth. - -# Output -Return JSON with `summary` and `data.evidence_sufficiency`, including a boolean `sufficient` and concise rationale. - -# Failure -Return an explicit error when no evidence is available. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_COMPARE_CATEGORY_HYPOTHESES.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_COMPARE_CATEGORY_HYPOTHESES.md deleted file mode 100644 index b69eaaf..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_COMPARE_CATEGORY_HYPOTHESES.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: COMPARE_CATEGORY_HYPOTHESES -dsl: evidence_reasoning -required_inputs: [candidate_categories, evidence] -optional_inputs: [] -produces: [category_comparison] -terminal: false ---- -# COMPARE_CATEGORY_HYPOTHESES - -Purpose: Compares competing standard-category hypotheses. - -Observation: 输出候选类别的自然语言排序与关键区分依据。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["category_comparison"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_DECIDE_NEXT_EVIDENCE_SOURCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_DECIDE_NEXT_EVIDENCE_SOURCE.md deleted file mode 100644 index 92d385f..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_DECIDE_NEXT_EVIDENCE_SOURCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: DECIDE_NEXT_EVIDENCE_SOURCE -dsl: evidence_reasoning -required_inputs: [current_evidence_state, available_metadata] -optional_inputs: [] -produces: [next_evidence_source] -terminal: false ---- -# DECIDE_NEXT_EVIDENCE_SOURCE - -Purpose: Determines which available evidence source should be explored next. - -Observation: 输出自然语言下一步建议,例如解释字段、获取同表字段、解释表/库、查询/重查标准或停止;不得调用超出可用信息范围的数据源。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["next_evidence_source"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FINALIZE_CLASSIFICATION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FINALIZE_CLASSIFICATION.md deleted file mode 100644 index 5e49b98..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FINALIZE_CLASSIFICATION.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: FINALIZE_CLASSIFICATION -dsl: evidence_reasoning -required_inputs: [final_evidence_state] -optional_inputs: [] -produces: [final_result] -terminal: true ---- -# Role -Return the final category and grading level supported by the current evidence state. - -# Evidence boundaries -Use existing evidence only. The category must exist in the frozen registry and the level must be approved. Never use ground truth. - -# Output -Return exactly one JSON object with `summary` and `data.final_result`, where the result contains both `category` and `grading_level`. - -# Failure -Return an explicit error when a valid complete result cannot be produced. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_CONTEXT_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_CONTEXT_EVIDENCE.md deleted file mode 100644 index bd49f03..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_CONTEXT_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: FUSE_CONTEXT_EVIDENCE -dsl: evidence_reasoning -required_inputs: [context_field_evidence] -optional_inputs: [] -produces: [context_evidence] -terminal: false ---- -# FUSE_CONTEXT_EVIDENCE - -Purpose: Integrates semantic evidence from selected contextual fields. - -Observation: 输出自然语言总结上下文字段共同指向的业务场景及其对目标字段的支持。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["context_evidence"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_DATABASE_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_DATABASE_EVIDENCE.md deleted file mode 100644 index 9546a0b..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_DATABASE_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: FUSE_DATABASE_EVIDENCE -dsl: evidence_reasoning -required_inputs: [available_database_evidence] -optional_inputs: [] -produces: [database_evidence] -terminal: false ---- -# FUSE_DATABASE_EVIDENCE - -Purpose: Integrates database-level semantic evidence. - -Observation: 输出数据库级自然语言背景及其对目标字段的高层约束。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["database_evidence"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_FIELD_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_FIELD_EVIDENCE.md deleted file mode 100644 index 97908d1..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_FIELD_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: FUSE_FIELD_EVIDENCE -dsl: evidence_reasoning -required_inputs: [available_field_evidence] -optional_inputs: [] -produces: [field_evidence] -terminal: false ---- -# FUSE_FIELD_EVIDENCE - -Purpose: Integrates all available evidence directly associated with the target field. - -Observation: 输出字段级统一自然语言证据状态,区分直接证据、辅助证据和歧义。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["field_evidence"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_METADATA_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_METADATA_EVIDENCE.md deleted file mode 100644 index f17c548..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_METADATA_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: FUSE_METADATA_EVIDENCE -dsl: evidence_reasoning -required_inputs: [available_metadata_evidence] -optional_inputs: [] -produces: [metadata_evidence] -terminal: false ---- -# FUSE_METADATA_EVIDENCE - -Purpose: Integrates multi-granularity metadata evidence into a unified semantic state. - -Observation: 输出统一 metadata evidence state,并指出不同粒度证据的一致与冲突。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["metadata_evidence"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_STANDARD_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_STANDARD_EVIDENCE.md deleted file mode 100644 index 4f74a10..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_STANDARD_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: FUSE_STANDARD_EVIDENCE -dsl: evidence_reasoning -required_inputs: [standard_alignment_evidence] -optional_inputs: [] -produces: [standard_evidence] -terminal: false ---- -# FUSE_STANDARD_EVIDENCE - -Purpose: Integrates multiple standard-alignment results into a unified standard-evidence state. - -Observation: 输出统一标准证据状态,明确主要支持类别和弱支持类别。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_evidence"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_TABLE_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_TABLE_EVIDENCE.md deleted file mode 100644 index 9cb0a5f..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_FUSE_TABLE_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: FUSE_TABLE_EVIDENCE -dsl: evidence_reasoning -required_inputs: [available_table_evidence] -optional_inputs: [] -produces: [table_evidence] -terminal: false ---- -# FUSE_TABLE_EVIDENCE - -Purpose: Integrates all available table-level semantic evidence. - -Observation: 输出统一表级自然语言证据状态。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["table_evidence"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_IDENTIFY_MISSING_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_IDENTIFY_MISSING_EVIDENCE.md deleted file mode 100644 index b36a14c..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_IDENTIFY_MISSING_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: IDENTIFY_MISSING_EVIDENCE -dsl: evidence_reasoning -required_inputs: [current_evidence, candidate_categories] -optional_inputs: [] -produces: [missing_evidence] -terminal: false ---- -# IDENTIFY_MISSING_EVIDENCE - -Purpose: Identifies the most important missing evidence needed to discriminate among candidate categories. - -Observation: 输出自然语言说明缺少哪类证据(字段描述、表字段、上下文字段语义、表描述、数据库描述、标准描述等)及其必要性。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["missing_evidence"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY.md deleted file mode 100644 index 265b235..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: INFER_CATEGORY -dsl: evidence_reasoning -required_inputs: [candidate_standard_categories, all_available_evidence] -optional_inputs: [] -produces: [category, aligned_standard_entry] -terminal: false ---- -# Role -Select the best-supported category from the supplied registry candidates. - -# Evidence boundaries -The category and aligned entry must come from the supplied candidates. Do not invent categories or use ground truth. - -# Output -Return JSON with `summary`, `data.category`, and `data.aligned_standard_entry`. - -# Failure -Return an explicit error when no candidate is supported. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY_FROM_TOPK.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY_FROM_TOPK.md deleted file mode 100644 index 96a1155..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_CATEGORY_FROM_TOPK.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: INFER_CATEGORY_FROM_TOPK -dsl: evidence_reasoning -required_inputs: [candidate_standard_categories, all_available_evidence] -optional_inputs: [] -produces: [category, aligned_standard_entry] -terminal: false ---- -# Role -Choose the single best-supported short option ID from the prior Top-K choices. - -# Evidence boundary -The executor adds descriptions for only those K candidates. Do not use any option outside the supplied set, grading level, evaluation label, or long canonical category ID. - -# Output -Return one supplied short option ID and a concise evidence summary. The executor maps it to the canonical category ID and binds the frozen Registry entry after the choice. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_GRADING_LEVEL.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_GRADING_LEVEL.md deleted file mode 100644 index 0f61b63..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_INFER_GRADING_LEVEL.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: INFER_GRADING_LEVEL -dsl: evidence_reasoning -required_inputs: [aligned_category, aligned_standard_entry] -optional_inputs: [] -produces: [grading_level] -terminal: false ---- -# Role -Read the approved sensitivity level associated with the aligned registry entry. - -# Evidence boundaries -Use only the aligned category and frozen registry entry. Do not infer a level from ground truth or unrelated examples. - -# Output -Return JSON with `summary` and `data.grading_level`, restricted to an approved level. - -# Failure -Return an explicit error when the entry does not support a valid level. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_FIELD_CONTEXT_CONFLICT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_FIELD_CONTEXT_CONFLICT.md deleted file mode 100644 index 746a767..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_FIELD_CONTEXT_CONFLICT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: RESOLVE_FIELD_CONTEXT_CONFLICT -dsl: evidence_reasoning -required_inputs: [field_evidence, context_evidence] -optional_inputs: [] -produces: [field_context_resolution] -terminal: false ---- -# RESOLVE_FIELD_CONTEXT_CONFLICT - -Purpose: Resolves conflicts between target-field evidence and contextual-field evidence. - -Observation: 输出冲突点、比较依据、保留的解释以及仍需补充的信息。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["field_context_resolution"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_METADATA_CONFLICT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_METADATA_CONFLICT.md deleted file mode 100644 index 3593ec1..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_METADATA_CONFLICT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: RESOLVE_METADATA_CONFLICT -dsl: evidence_reasoning -required_inputs: [conflicting_metadata_evidence] -optional_inputs: [] -produces: [metadata_conflict_resolution] -terminal: false ---- -# RESOLVE_METADATA_CONFLICT - -Purpose: Resolves conflicting semantic evidence across metadata granularities. - -Observation: 输出自然语言冲突消解结论和依据。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["metadata_conflict_resolution"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_STANDARD_CONFLICT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_STANDARD_CONFLICT.md deleted file mode 100644 index 5492796..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_RESOLVE_STANDARD_CONFLICT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: RESOLVE_STANDARD_CONFLICT -dsl: evidence_reasoning -required_inputs: [conflicting_standard_alignments] -optional_inputs: [] -produces: [standard_conflict_resolution] -terminal: false ---- -# RESOLVE_STANDARD_CONFLICT - -Purpose: Resolves conflicts among competing standard alignments. - -Observation: 输出哪个标准候选更可信、为什么,以及仍存在的歧义。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_conflict_resolution"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CATEGORY_WITH_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CATEGORY_WITH_STANDARD.md deleted file mode 100644 index de3852f..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CATEGORY_WITH_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: VERIFY_CATEGORY_WITH_STANDARD -dsl: evidence_reasoning -required_inputs: [candidate_category, standard_evidence, metadata_evidence] -optional_inputs: [] -produces: [category_verification] -terminal: false ---- -# VERIFY_CATEGORY_WITH_STANDARD - -Purpose: Verifies whether a candidate category is jointly supported by metadata and standard evidence. - -Observation: 输出自然语言验证结论,明确标准描述与元数据语义是否一致。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["category_verification"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CLASSIFICATION_GRADING_CONSISTENCY.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CLASSIFICATION_GRADING_CONSISTENCY.md deleted file mode 100644 index 482763b..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_VERIFY_CLASSIFICATION_GRADING_CONSISTENCY.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: VERIFY_CLASSIFICATION_GRADING_CONSISTENCY -dsl: evidence_reasoning -required_inputs: [category_candidate, grading_level_candidate, current_evidence] -optional_inputs: [] -produces: [grading_consistency] -terminal: false ---- -# VERIFY_CLASSIFICATION_GRADING_CONSISTENCY - -Purpose: Checks semantic consistency between the predicted category and Grading-level. - -Observation: 输出自然语言一致性检查结论及可能的矛盾点。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["grading_consistency"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_WEIGH_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_WEIGH_EVIDENCE.md deleted file mode 100644 index c9649ca..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/evidence_reasoning_WEIGH_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: WEIGH_EVIDENCE -dsl: evidence_reasoning -required_inputs: [evidence_set] -optional_inputs: [] -produces: [evidence_weights] -terminal: false ---- -# WEIGH_EVIDENCE - -Purpose: Assesses the relative reliability and importance of available evidence. - -Observation: 输出自然语言说明哪些证据更强、哪些只是辅助,以及原因;不输出未经依据的数值权重。 - -Use only supplied evidence and actual standards. Explain agreement, conflict, missing evidence and relative strength. Do not invent metadata, standard entries, categories or grades, or overwrite normative state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["evidence_weights"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_ACQUIRE_MISSING_METADATA.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_ACQUIRE_MISSING_METADATA.md deleted file mode 100644 index a8256f1..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_ACQUIRE_MISSING_METADATA.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ACQUIRE_MISSING_METADATA -dsl: metadata_acquisition -required_inputs: [missing_metadata_type, current_metadata] -optional_inputs: [] -produces: [acquired_metadata] -terminal: false ---- -# ACQUIRE_MISSING_METADATA - -Purpose: Acquires a specific type of missing metadata requested by the current reasoning state. - -Observation: 输出尝试获取的元数据类型、实际获得的信息及其自然语言摘要;若无法获取,明确失败原因。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["acquired_metadata"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_CHECK_METADATA_AVAILABILITY.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_CHECK_METADATA_AVAILABILITY.md deleted file mode 100644 index 99385a6..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_CHECK_METADATA_AVAILABILITY.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: CHECK_METADATA_AVAILABILITY -dsl: metadata_acquisition -required_inputs: [current_record] -optional_inputs: [] -produces: [metadata_availability] -terminal: false ---- -# Role -Report which approved metadata fields are present and which are absent. - -# Evidence boundaries -Inspect only the supplied record. Never reconstruct hidden descriptions, values, labels, or ground truth. - -# Output -Return JSON with `summary` and `data.metadata_availability`, containing `available` and `missing` lists. - -# Failure -Return an explicit error when the record is unavailable or malformed. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_EXPAND_SELECTED_CONTEXT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_EXPAND_SELECTED_CONTEXT.md deleted file mode 100644 index d6d9105..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_EXPAND_SELECTED_CONTEXT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: EXPAND_SELECTED_CONTEXT -dsl: metadata_acquisition -required_inputs: [selected_context_fields] -optional_inputs: [] -produces: [context_fields] -terminal: false ---- -# EXPAND_SELECTED_CONTEXT - -Purpose: Organizes selected contextual metadata into a usable state for subsequent semantic interpretation. - -Observation: 输出自然语言上下文摘要,保持字段名与其可用描述/类型/值之间的对应关系。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["context_fields"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_DATABASE_CONTEXT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_DATABASE_CONTEXT.md deleted file mode 100644 index c119048..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_DATABASE_CONTEXT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_COMPLETE_DATABASE_CONTEXT -dsl: metadata_acquisition -required_inputs: [database_name] -optional_inputs: [] -produces: [database_context] -terminal: false ---- -# GET_COMPLETE_DATABASE_CONTEXT - -Purpose: Retrieves the available high-level metadata context of the current database. - -Observation: 输出数据库级自然语言背景摘要,不引入跨库信息。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["database_context"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_TABLE_CONTEXT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_TABLE_CONTEXT.md deleted file mode 100644 index 0838b6e..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_COMPLETE_TABLE_CONTEXT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_COMPLETE_TABLE_CONTEXT -dsl: metadata_acquisition -required_inputs: [table_name] -optional_inputs: [] -produces: [table_context] -terminal: false ---- -# GET_COMPLETE_TABLE_CONTEXT - -Purpose: Retrieves the complete available metadata context of the current table. - -Observation: 输出当前表完整可用元数据的自然语言摘要,并明确哪些属性缺失。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["table_context"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_DESCRIPTIONS.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_DESCRIPTIONS.md deleted file mode 100644 index c6afadf..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_DESCRIPTIONS.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_CONTEXT_FIELD_DESCRIPTIONS -dsl: metadata_acquisition -required_inputs: [table_name, context_fields] -optional_inputs: [] -produces: [context_field_descriptions] -terminal: false ---- -# GET_CONTEXT_FIELD_DESCRIPTIONS - -Purpose: Retrieves descriptions for selected contextual fields. - -Observation: 输出所选上下文字段的描述及自然语言摘要;缺失描述需明确标记。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["context_field_descriptions"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_TYPES.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_TYPES.md deleted file mode 100644 index 1515c03..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_TYPES.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_CONTEXT_FIELD_TYPES -dsl: metadata_acquisition -required_inputs: [table_name, context_fields] -optional_inputs: [] -produces: [context_field_types] -terminal: false ---- -# GET_CONTEXT_FIELD_TYPES - -Purpose: Retrieves data types of selected contextual fields as supporting evidence. - -Observation: 输出上下文字段类型的自然语言摘要,说明类型能提供的有限辅助信息。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["context_field_types"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_VALUES.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_VALUES.md deleted file mode 100644 index 3566bb5..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_CONTEXT_FIELD_VALUES.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_CONTEXT_FIELD_VALUES -dsl: metadata_acquisition -required_inputs: [table_name, context_fields] -optional_inputs: [] -produces: [context_field_values] -terminal: false ---- -# GET_CONTEXT_FIELD_VALUES - -Purpose: Retrieves available values of contextual fields and summarizes their semantic patterns. - -Observation: 输出样例值模式的自然语言摘要;避免输出不必要的敏感原始值,重点描述模式和语义。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["context_field_values"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_DATABASE_DESCRIPTION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_DATABASE_DESCRIPTION.md deleted file mode 100644 index a394829..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_DATABASE_DESCRIPTION.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_DATABASE_DESCRIPTION -dsl: metadata_acquisition -required_inputs: [database_name] -optional_inputs: [] -produces: [database_description] -terminal: false ---- -# GET_DATABASE_DESCRIPTION - -Purpose: Retrieves and summarizes the description of the current database. - -Observation: 输出数据库描述及自然语言摘要;不存在时明确说明。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["database_description"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_DESCRIPTION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_DESCRIPTION.md deleted file mode 100644 index 2015e2c..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_DESCRIPTION.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_FIELD_DESCRIPTION -dsl: metadata_acquisition -required_inputs: [table_name, field_name] -optional_inputs: [] -produces: [field_description] -terminal: false ---- -# GET_FIELD_DESCRIPTION - -Purpose: Retrieves the description of the target field from the available database metadata. - -Observation: 输出获取到的字段描述及自然语言摘要;若不存在,应明确说明未获得该信息。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["field_description"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_METADATA.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_METADATA.md deleted file mode 100644 index f8504a3..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_FIELD_METADATA.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -name: GET_FIELD_METADATA -dsl: metadata_acquisition -required_inputs: [current_record] -optional_inputs: [] -produces: [field_metadata] -terminal: false ---- -# Role -Retrieve approved real metadata for this exact source record from the external -metadata store. This is a deterministic lookup, not a language-model guess. - -# Evidence boundary -Only database name, table name, field description, and table description may be -returned. Match source ID, domain, and field name. Never expose the category, -grading level, split, or other target data. The Agent sees these fields only -after this Skill has been called and its Observation appended to state. - -# Output -Return `field_metadata` with the available approved fields. Missing values -are omitted. The result is an Observation for subsequent Skill calls. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_DESCRIPTION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_DESCRIPTION.md deleted file mode 100644 index 2bf0689..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_DESCRIPTION.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_TABLE_DESCRIPTION -dsl: metadata_acquisition -required_inputs: [table_name] -optional_inputs: [] -produces: [table_description] -terminal: false ---- -# GET_TABLE_DESCRIPTION - -Purpose: Retrieves and summarizes the description of the current table. - -Observation: 输出表描述及自然语言摘要;不存在时明确说明。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["table_description"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_FIELDS.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_FIELDS.md deleted file mode 100644 index c1779ba..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_GET_TABLE_FIELDS.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: GET_TABLE_FIELDS -dsl: metadata_acquisition -required_inputs: [table_name] -optional_inputs: [] -produces: [table_fields] -terminal: false ---- -# GET_TABLE_FIELDS - -Purpose: Retrieves other fields from the current table to provide local schema context. - -Observation: 输出同表字段名称列表的自然语言摘要,突出可能与目标字段相关的字段;不臆造不存在字段。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["table_fields"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_SELECT_CONTEXT_FIELDS.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_SELECT_CONTEXT_FIELDS.md deleted file mode 100644 index ca0decc..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/metadata_acquisition_SELECT_CONTEXT_FIELDS.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: SELECT_CONTEXT_FIELDS -dsl: metadata_acquisition -required_inputs: [target_field, table_fields] -optional_inputs: [current_semantic_state] -produces: [selected_context_fields] -terminal: false ---- -# SELECT_CONTEXT_FIELDS - -Purpose: Selects the most informative contextual fields for the target field. - -Observation: 输出自然语言说明选择了哪些上下文字段、为什么它们更有信息价值,以及哪些字段被忽略。 - -Use deterministic canonical Val access only. Verify private record identity. Never invent missing descriptions, types, values or locators; explicitly report unavailable data. Context belongs to the actual domain/database/table and has bounded, disclosed coverage. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["selected_context_fields"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_DISAMBIGUATE_FIELD_SEMANTICS.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_DISAMBIGUATE_FIELD_SEMANTICS.md deleted file mode 100644 index 1fc67c7..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_DISAMBIGUATE_FIELD_SEMANTICS.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: DISAMBIGUATE_FIELD_SEMANTICS -dsl: semantic_interpretation -required_inputs: [field_semantics] -optional_inputs: [domain, standard_candidates] -produces: [disambiguated_field_semantics] -terminal: false ---- -# Role -Resolve competing interpretations using only the current semantic state and supplied candidates. - -# Evidence boundaries -Preserve uncertainty when evidence is insufficient. Do not use hidden metadata, labels, or ground truth. - -# Output -Return JSON with `summary` and `data.disambiguated_field_semantics` as concise natural language. - -# Failure -Return an explicit error when no field semantics are available. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_DATABASE_ABBREVIATION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_DATABASE_ABBREVIATION.md deleted file mode 100644 index 76258c8..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_DATABASE_ABBREVIATION.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: EXPAND_DATABASE_ABBREVIATION -dsl: semantic_interpretation -required_inputs: [database_name] -optional_inputs: [domain, database_description] -produces: [database_abbreviation_semantics] -terminal: false ---- -# EXPAND_DATABASE_ABBREVIATION - -Purpose: Expands an abbreviated database or system name into its likely semantic meaning. - -Observation: 输出数据库/系统缩写的自然语言展开及可能的业务范围。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["database_abbreviation_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_FIELD_ABBREVIATION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_FIELD_ABBREVIATION.md deleted file mode 100644 index d6a7524..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_FIELD_ABBREVIATION.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: EXPAND_FIELD_ABBREVIATION -dsl: semantic_interpretation -required_inputs: [field_name] -optional_inputs: [domain] -produces: [field_abbreviation_semantics] -terminal: false ---- -# Role -Expand identifier tokens and likely abbreviations in the supplied field name. - -# Evidence boundaries -Mark uncertain expansions explicitly. Do not invent table context, values, descriptions, labels, or ground truth. - -# Output -Return JSON with `summary` and `data.field_abbreviation_semantics` as concise natural language. - -# Failure -Return an explicit error when the field name is empty. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_TABLE_ABBREVIATION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_TABLE_ABBREVIATION.md deleted file mode 100644 index 1340fa2..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_EXPAND_TABLE_ABBREVIATION.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: EXPAND_TABLE_ABBREVIATION -dsl: semantic_interpretation -required_inputs: [table_name] -optional_inputs: [domain, table_description] -produces: [table_abbreviation_semantics] -terminal: false ---- -# EXPAND_TABLE_ABBREVIATION - -Purpose: Expands an abbreviated table name into plausible business meanings. - -Observation: 输出表名缩写的候选展开,以及它可能表示的数据主题或业务对象。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["table_abbreviation_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_CONTEXT_FIELDS.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_CONTEXT_FIELDS.md deleted file mode 100644 index c5a536a..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_CONTEXT_FIELDS.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: INTERPRET_CONTEXT_FIELDS -dsl: semantic_interpretation -required_inputs: [context_fields] -optional_inputs: [domain, table_name] -produces: [context_field_semantics] -terminal: false ---- -# INTERPRET_CONTEXT_FIELDS - -Purpose: Interprets neighboring fields and summarizes the business context jointly implied by them. - -Observation: 输出各上下文字段的简要语义及它们共同指向的业务场景;不直接替目标字段做最终分类。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["context_field_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_DESCRIPTION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_DESCRIPTION.md deleted file mode 100644 index 46c8b95..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_DESCRIPTION.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: INTERPRET_DATABASE_DESCRIPTION -dsl: semantic_interpretation -required_inputs: [database_description] -optional_inputs: [database_name, domain] -produces: [database_description_semantics] -terminal: false ---- -# INTERPRET_DATABASE_DESCRIPTION - -Purpose: Interprets the semantic scope expressed by the database description. - -Observation: 输出数据库描述的自然语言摘要,并说明其对字段判断的约束。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["database_description_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_NAME.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_NAME.md deleted file mode 100644 index a1fdeb0..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DATABASE_NAME.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: INTERPRET_DATABASE_NAME -dsl: semantic_interpretation -required_inputs: [database_name] -optional_inputs: [domain, database_description] -produces: [database_semantics] -terminal: false ---- -# INTERPRET_DATABASE_NAME - -Purpose: Interprets the domain and semantic scope implied by the database name. - -Observation: 输出数据库级自然语言语义,作为当前字段的高层背景。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["database_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DOMAIN.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DOMAIN.md deleted file mode 100644 index 23b3e93..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_DOMAIN.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: INTERPRET_DOMAIN -dsl: semantic_interpretation -required_inputs: [domain] -optional_inputs: [] -produces: [domain_semantics] -terminal: false ---- -# Role -Describe the semantic scope implied by the supplied domain. - -# Evidence boundaries -Use only the domain string. Do not replace it with a dataset name or infer hidden metadata or ground truth. - -# Output -Return JSON with `summary` and `data.domain_semantics` as concise natural language. - -# Failure -Return an explicit error when the domain is empty. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_DESCRIPTION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_DESCRIPTION.md deleted file mode 100644 index 5809752..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_DESCRIPTION.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: INTERPRET_FIELD_DESCRIPTION -dsl: semantic_interpretation -required_inputs: [field_description] -optional_inputs: [field_name, domain] -produces: [field_description_semantics] -terminal: false ---- -# Role -Explain the business meaning of an observed field description, without assigning a category. - -# Evidence boundary -Use only the supplied real description and optional supplied context. Separate stated facts -from uncertain interpretation. Never invent values, neighboring fields, labels or grading levels. - -# Output -Return JSON with a short `summary` and `data.field_description_semantics` as concise text. - -# Failure -Do not infer from an absent or empty field description. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_NAME.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_NAME.md deleted file mode 100644 index fd91c53..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_NAME.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: INTERPRET_FIELD_NAME -dsl: semantic_interpretation -required_inputs: [field_name] -optional_inputs: [domain, field_abbreviation_semantics] -produces: [field_semantics] -terminal: false ---- -# Role -Interpret the likely business meaning of the supplied field identifier. - -# Evidence boundaries -Use only resolved inputs and distinguish evidence from hypotheses. Do not invent unavailable table context, descriptions, values, labels, or ground truth. - -# Output -Return JSON with `summary` and `data.field_semantics` as concise natural language. - -# Failure -Return an explicit error when the field name is empty. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_TYPE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_TYPE.md deleted file mode 100644 index f7faeb4..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_TYPE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: INTERPRET_FIELD_TYPE -dsl: semantic_interpretation -required_inputs: [field_type] -optional_inputs: [field_name, field_description] -produces: [field_type_semantics] -terminal: false ---- -# INTERPRET_FIELD_TYPE - -Purpose: Uses the field data type as supporting semantic evidence. - -Observation: 输出字段类型可提供的约束性自然语言判断;不得仅凭类型强行确定具体类别。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["field_type_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_VALUE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_VALUE.md deleted file mode 100644 index 8fd4747..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_FIELD_VALUE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: INTERPRET_FIELD_VALUE -dsl: semantic_interpretation -required_inputs: [value] -optional_inputs: [field_name, field_type, domain] -produces: [value_semantics] -terminal: false ---- -# INTERPRET_FIELD_VALUE - -Purpose: Infers possible semantics from the observed value pattern and content. - -Observation: 输出值模式的自然语言描述、可能对应的数据含义,以及这种证据的可靠性边界。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["value_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_DESCRIPTION.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_DESCRIPTION.md deleted file mode 100644 index 31d9fd8..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_DESCRIPTION.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -name: INTERPRET_TABLE_DESCRIPTION -dsl: semantic_interpretation -required_inputs: [table_description] -optional_inputs: [table_name, domain] -produces: [table_description_semantics] -terminal: false ---- -# Role -Explain the business context of an observed table description, without assigning a category. - -# Evidence boundary -Use only the supplied real description and optional supplied context. The table's business -topic is context for the target field, not proof that all fields have one category. -Never invent values, labels or grading levels. - -# Output -Return JSON with a short `summary` and `data.table_description_semantics` as concise text. - -# Failure -Do not infer from an absent or empty table description. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_NAME.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_NAME.md deleted file mode 100644 index 799e31b..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_INTERPRET_TABLE_NAME.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: INTERPRET_TABLE_NAME -dsl: semantic_interpretation -required_inputs: [table_name] -optional_inputs: [domain, table_description] -produces: [table_semantics] -terminal: false ---- -# INTERPRET_TABLE_NAME - -Purpose: Interprets the business semantics represented by a table name. - -Observation: 输出表级自然语言语义,强调该表可能描述什么业务数据。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["table_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_SYNTHESIZE_METADATA_SEMANTICS.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_SYNTHESIZE_METADATA_SEMANTICS.md deleted file mode 100644 index 18c218c..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/semantic_interpretation_SYNTHESIZE_METADATA_SEMANTICS.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: SYNTHESIZE_METADATA_SEMANTICS -dsl: semantic_interpretation -required_inputs: [field_semantics] -optional_inputs: [domain_semantics, table_semantics, database_semantics, context_field_semantics, field_description_semantics, field_type_semantics, value_semantics] -produces: [metadata_semantics] -terminal: false ---- -# SYNTHESIZE_METADATA_SEMANTICS - -Purpose: Synthesizes all available metadata interpretations into a unified natural-language semantic state. - -Observation: 输出一段紧凑但信息充分的自然语言 semantic state,区分强证据、辅助证据和仍存在的歧义。 - -Interpret only supplied evidence. Separate direct evidence, auxiliary evidence, and uncertain hypotheses. Do not retrieve standards or predict category/grade. Never turn inferred semantics into raw metadata. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["metadata_semantics"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_CONTEXT_TO_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_CONTEXT_TO_STANDARD.md deleted file mode 100644 index dc5dae5..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_CONTEXT_TO_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ALIGN_CONTEXT_TO_STANDARD -dsl: standard_alignment -required_inputs: [context_semantics, standard_candidates] -optional_inputs: [] -produces: [align_context_to_standard] -terminal: false ---- -# ALIGN_CONTEXT_TO_STANDARD - -Purpose: Aligns contextual semantic evidence with candidate standard categories. - -Observation: 输出上下文语义对候选标准类别的支持、反对或弱相关关系。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["align_context_to_standard"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DATABASE_TO_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DATABASE_TO_STANDARD.md deleted file mode 100644 index c303142..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DATABASE_TO_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ALIGN_DATABASE_TO_STANDARD -dsl: standard_alignment -required_inputs: [database_semantics, standard_candidates] -optional_inputs: [] -produces: [align_database_to_standard] -terminal: false ---- -# ALIGN_DATABASE_TO_STANDARD - -Purpose: Aligns database-level semantics with candidate standard categories. - -Observation: Explain how database context supports, contradicts or weakly matches each actual standard candidate; context remains auxiliary to target-field evidence. - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["align_database_to_standard"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DESCRIPTION_TO_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DESCRIPTION_TO_STANDARD.md deleted file mode 100644 index cda05f1..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_DESCRIPTION_TO_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ALIGN_DESCRIPTION_TO_STANDARD -dsl: standard_alignment -required_inputs: [field_description_semantics, standard_candidates] -optional_inputs: [] -produces: [align_description_to_standard] -terminal: false ---- -# ALIGN_DESCRIPTION_TO_STANDARD - -Purpose: Aligns field-description semantics with standard category descriptions. - -Observation: 输出字段描述与各标准候选的语义匹配理由,显式描述通常可作为较强证据。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["align_description_to_standard"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_FIELD_TO_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_FIELD_TO_STANDARD.md deleted file mode 100644 index 0dde182..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_FIELD_TO_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ALIGN_FIELD_TO_STANDARD -dsl: standard_alignment -required_inputs: [field_semantics, standard_candidates] -optional_inputs: [] -produces: [field_standard_alignment] -terminal: false ---- -# ALIGN_FIELD_TO_STANDARD - -Purpose: Aligns the target-field semantics with candidate standard categories. - -Observation: 输出字段语义与各候选标准描述的匹配/不匹配理由,以及当前更优候选。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["field_standard_alignment"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_TABLE_TO_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_TABLE_TO_STANDARD.md deleted file mode 100644 index f20ed54..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_TABLE_TO_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ALIGN_TABLE_TO_STANDARD -dsl: standard_alignment -required_inputs: [table_semantics, standard_candidates] -optional_inputs: [] -produces: [align_table_to_standard] -terminal: false ---- -# ALIGN_TABLE_TO_STANDARD - -Purpose: Aligns table-level semantics with candidate standard categories. - -Observation: Explain how table context supports, contradicts or weakly matches each actual standard candidate; context remains auxiliary to target-field evidence. - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["align_table_to_standard"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_VALUE_TO_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_VALUE_TO_STANDARD.md deleted file mode 100644 index 43a354f..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_ALIGN_VALUE_TO_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: ALIGN_VALUE_TO_STANDARD -dsl: standard_alignment -required_inputs: [value_semantics, standard_candidates] -optional_inputs: [] -produces: [align_value_to_standard] -terminal: false ---- -# ALIGN_VALUE_TO_STANDARD - -Purpose: Aligns value-derived semantics with candidate standard categories. - -Observation: 输出字段值模式对标准候选的支持程度;强调值证据通常是辅助证据。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["align_value_to_standard"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_COMPARE_STANDARD_CANDIDATES.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_COMPARE_STANDARD_CANDIDATES.md deleted file mode 100644 index 1654fc5..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_COMPARE_STANDARD_CANDIDATES.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: COMPARE_STANDARD_CANDIDATES -dsl: standard_alignment -required_inputs: [standard_candidates, semantic_evidence] -optional_inputs: [] -produces: [standard_comparison, aligned_standard_entry] -terminal: false ---- -# Role -Compare retrieved candidates against the current semantic evidence and identify the best-supported entry. - -# Evidence boundaries -Compare only supplied candidates. Do not add categories, hidden metadata, labels, or ground truth. - -# Output -Return JSON with a nonempty `summary`. `data.standard_comparison` must be a non-empty string explaining the comparison, never a list. `data.aligned_standard_entry` must be one exact object copied from `standard_candidate_details`, containing exactly `category`, `label`, and `description`. Copy all three values without changes or extra fields. Select only an actual supplied candidate. - -# Failure -Return an explicit error when candidates or semantic evidence are absent. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_REFINE_STANDARD_QUERY.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_REFINE_STANDARD_QUERY.md deleted file mode 100644 index 29433fb..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_REFINE_STANDARD_QUERY.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: REFINE_STANDARD_QUERY -dsl: standard_alignment -required_inputs: [previous_standard_results, current_semantic_state] -optional_inputs: [] -produces: [refined_semantic_query] -terminal: false ---- -# REFINE_STANDARD_QUERY - -Purpose: Refines the standard-search query using previous retrieval results and the current semantic state. - -Observation: 输出一段更聚焦的自然语言查询表达,并说明为何这样改写能区分当前候选。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["refined_semantic_query"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_RESEARCH_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_RESEARCH_STANDARD.md deleted file mode 100644 index 421cda4..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_RESEARCH_STANDARD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: RESEARCH_STANDARD -dsl: standard_alignment -required_inputs: [refined_semantic_query] -optional_inputs: [] -produces: [standard_candidates] -terminal: false ---- -# RESEARCH_STANDARD - -Purpose: Performs a subsequent standard search after semantic refinement. - -Observation: 输出新一轮标准候选、与上一轮相比新增或变化的证据,以及是否更有区分度。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_candidates"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD.md deleted file mode 100644 index 79a5d12..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -name: SEARCH_STANDARD -dsl: standard_alignment -required_inputs: [semantic_query] -optional_inputs: [] -produces: [standard_candidates] -terminal: false ---- -# Role -Retrieve ranked category candidates from the frozen standard registry. - -# Evidence boundaries -Use only the supplied query and registry. Never consult evaluation labels or ground truth. - -# Output -Return JSON with `summary` and `data.standard_candidates` as a ranked list of registry entries. - -# Failure -Return an explicit error when the query is empty or the registry cannot be searched. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_CONTEXT.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_CONTEXT.md deleted file mode 100644 index 20055df..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_CONTEXT.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: SEARCH_STANDARD_BY_CONTEXT -dsl: standard_alignment -required_inputs: [context_semantics] -optional_inputs: [] -produces: [standard_candidates] -terminal: false ---- -# SEARCH_STANDARD_BY_CONTEXT - -Purpose: Retrieves standard categories using contextual-field semantics. - -Observation: 输出上下文语义最相关的标准候选,并说明其对目标字段的辅助意义。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_candidates"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_DATABASE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_DATABASE.md deleted file mode 100644 index 97b3bff..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_DATABASE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: SEARCH_STANDARD_BY_DATABASE -dsl: standard_alignment -required_inputs: [database_semantics] -optional_inputs: [] -produces: [standard_candidates] -terminal: false ---- -# SEARCH_STANDARD_BY_DATABASE - -Purpose: Uses database-level semantics to retrieve or constrain candidate standard categories. - -Observation: 输出数据库级语义可能支持的标准类别范围和依据。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_candidates"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_FIELD.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_FIELD.md deleted file mode 100644 index 5af62e3..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_FIELD.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: SEARCH_STANDARD_BY_FIELD -dsl: standard_alignment -required_inputs: [field_semantics] -optional_inputs: [] -produces: [standard_candidates] -terminal: false ---- -# SEARCH_STANDARD_BY_FIELD - -Purpose: Retrieves standard categories relevant to the target-field semantics. - -Observation: 输出字段语义最相关的标准候选及匹配依据。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_candidates"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_TABLE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_TABLE.md deleted file mode 100644 index 2ffdd24..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SEARCH_STANDARD_BY_TABLE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: SEARCH_STANDARD_BY_TABLE -dsl: standard_alignment -required_inputs: [table_semantics] -optional_inputs: [] -produces: [standard_candidates] -terminal: false ---- -# SEARCH_STANDARD_BY_TABLE - -Purpose: Retrieves candidate standard categories using table-level semantics. - -Observation: 输出表级语义相关的标准候选及其描述摘要。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_candidates"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SELECT_CATEGORY_TOPK.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SELECT_CATEGORY_TOPK.md deleted file mode 100644 index 99684b0..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SELECT_CATEGORY_TOPK.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: SELECT_CATEGORY_TOPK -dsl: standard_alignment -required_inputs: [semantic_query] -optional_inputs: [] -produces: [standard_candidates] -terminal: false ---- -# Role -Select ranked Top-K short option IDs from the full frozen label catalog. The executor maps each selected option back to its canonical Registry category ID. - -# Evidence boundary -This stage receives deterministic short option IDs and full category-path labels only, never canonical long IDs, category descriptions, grading levels, or evaluation labels. Do not invent option IDs. - -# Output -Return exactly K distinct short option IDs from the supplied catalog. The executor validates them and normalizes them into label-only standard_candidates carrying canonical category IDs. diff --git a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SUMMARIZE_STANDARD_EVIDENCE.md b/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SUMMARIZE_STANDARD_EVIDENCE.md deleted file mode 100644 index 3318075..0000000 --- a/research/finance_program_v1/nontraining/vendor/runtime/skills/full_pool/standard_alignment_SUMMARIZE_STANDARD_EVIDENCE.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: SUMMARIZE_STANDARD_EVIDENCE -dsl: standard_alignment -required_inputs: [aligned_standard_candidates] -optional_inputs: [] -produces: [standard_evidence_summary] -terminal: false ---- -# SUMMARIZE_STANDARD_EVIDENCE - -Purpose: Summarizes multiple standard-search and alignment results into a unified standard-evidence state. - -Observation: 输出自然语言总结:当前标准证据主要支持哪些类别、哪些类别已被排除、还存在哪些冲突。 - -Use only the actual frozen standard candidates and their disclosed descriptions. Explain support, contradictions, auxiliary context and unresolved distinctions. Never invent standard entries or overwrite canonical candidate/category/grade state. - -Return exactly {"summary": "nonempty natural-language observation", "data": {...}}. Data keys must be exactly ["standard_evidence_summary"]. Semantic and reasoning outputs are nonempty strings; metadata/context/candidate outputs retain their typed validated structures. No extra keys. diff --git a/research/finance_program_v1/nontraining/vendor/skill_reference.json b/research/finance_program_v1/nontraining/vendor/skill_reference.json deleted file mode 100644 index dac74e8..0000000 --- a/research/finance_program_v1/nontraining/vendor/skill_reference.json +++ /dev/null @@ -1,380 +0,0 @@ -{ - "COMPARE_STANDARD_CANDIDATES": { - "required": "standard_candidates, semantic_evidence", - "output": "输出候选类别的排序、关键支持/反对依据及仍需区分的歧义点。", - "optional": "无", - "purpose": "Compares competing standard candidates based on accumulated semantic evidence." - }, - "GET_FIELD_DESCRIPTION": { - "required": "table_name, field_name", - "output": "输出获取到的字段描述及自然语言摘要;若不存在,应明确说明未获得该信息。", - "optional": "无", - "purpose": "Retrieves the description of the target field from the available database metadata." - }, - "GET_TABLE_DESCRIPTION": { - "required": "table_name", - "output": "输出表描述及自然语言摘要;不存在时明确说明。", - "optional": "无", - "purpose": "Retrieves and summarizes the description of the current table." - }, - "GET_DATABASE_DESCRIPTION": { - "required": "database_name", - "output": "输出数据库描述及自然语言摘要;不存在时明确说明。", - "optional": "无", - "purpose": "Retrieves and summarizes the description of the current database." - }, - "INTERPRET_FIELD_DESCRIPTION": { - "required": "field_description", - "output": "输出字段描述中最关键的数据对象、属性或业务语义,以及其与 field_name 的一致或冲突之处。", - "optional": "field_name, domain", - "purpose": "Extracts and interprets explicit semantic information from the field description." - }, - "SUMMARIZE_STANDARD_EVIDENCE": { - "required": "aligned_standard_candidates", - "output": "输出自然语言总结:当前标准证据主要支持哪些类别、哪些类别已被排除、还存在哪些冲突。", - "optional": "无", - "purpose": "Summarizes multiple standard-search and alignment results into a unified standard-evidence state." - }, - "GET_TABLE_FIELDS": { - "required": "table_name", - "output": "输出同表字段名称列表的自然语言摘要,突出可能与目标字段相关的字段;不臆造不存在字段。", - "optional": "无", - "purpose": "Retrieves other fields from the current table to provide local schema context." - }, - "FUSE_CONTEXT_EVIDENCE": { - "required": "context_field_evidence", - "output": "输出自然语言总结上下文字段共同指向的业务场景及其对目标字段的支持。", - "optional": "无", - "purpose": "Integrates semantic evidence from selected contextual fields." - }, - "ALIGN_DESCRIPTION_TO_STANDARD": { - "required": "field_description_semantics, standard_candidates", - "output": "输出字段描述与各标准候选的语义匹配理由,显式描述通常可作为较强证据。", - "optional": "无", - "purpose": "Aligns field-description semantics with standard category descriptions." - }, - "GET_COMPLETE_TABLE_CONTEXT": { - "required": "table_name", - "output": "输出当前表完整可用元数据的自然语言摘要,并明确哪些属性缺失。", - "optional": "无", - "purpose": "Retrieves the complete available metadata context of the current table." - }, - "RESEARCH_STANDARD": { - "required": "refined_semantic_query", - "output": "输出新一轮标准候选、与上一轮相比新增或变化的证据,以及是否更有区分度。", - "optional": "无", - "purpose": "Performs a subsequent standard search after semantic refinement." - }, - "SEARCH_STANDARD_BY_TABLE": { - "required": "table_semantics", - "output": "输出表级语义相关的标准候选及其描述摘要。", - "optional": "无", - "purpose": "Retrieves candidate standard categories using table-level semantics." - }, - "EXPAND_TABLE_ABBREVIATION": { - "required": "table_name", - "output": "输出表名缩写的候选展开,以及它可能表示的数据主题或业务对象。", - "optional": "domain, table_description", - "purpose": "Expands an abbreviated table name into plausible business meanings." - }, - "DISAMBIGUATE_FIELD_SEMANTICS": { - "required": "candidate_field_semantics, available_semantic_context", - "output": "输出候选解释之间的比较、保留/排除依据,以及当前更可信的字段语义。", - "optional": "无", - "purpose": "Disambiguates competing interpretations of the target field using available semantic context." - }, - "IDENTIFY_MISSING_EVIDENCE": { - "required": "current_evidence, candidate_categories", - "output": "输出自然语言说明缺少哪类证据(字段描述、表字段、上下文字段语义、表描述、数据库描述、标准描述等)及其必要性。", - "optional": "无", - "purpose": "Identifies the most important missing evidence needed to discriminate among candidate categories." - }, - "EXPAND_SELECTED_CONTEXT": { - "required": "selected_context_fields", - "output": "输出自然语言上下文摘要,保持字段名与其可用描述/类型/值之间的对应关系。", - "optional": "无", - "purpose": "Organizes selected contextual metadata into a usable state for subsequent semantic interpretation." - }, - "GET_CONTEXT_FIELD_VALUES": { - "required": "table_name, context_fields", - "output": "输出样例值模式的自然语言摘要;避免输出不必要的敏感原始值,重点描述模式和语义。", - "optional": "无", - "purpose": "Retrieves available values of contextual fields and summarizes their semantic patterns." - }, - "ACQUIRE_MISSING_METADATA": { - "required": "missing_metadata_type, current_metadata", - "output": "输出尝试获取的元数据类型、实际获得的信息及其自然语言摘要;若无法获取,明确失败原因。", - "optional": "无", - "purpose": "Acquires a specific type of missing metadata requested by the current reasoning state." - }, - "INTERPRET_DATABASE_DESCRIPTION": { - "required": "database_description", - "output": "输出数据库描述的自然语言摘要,并说明其对字段判断的约束。", - "optional": "database_name, domain", - "purpose": "Interprets the semantic scope expressed by the database description." - }, - "VERIFY_CATEGORY_WITH_STANDARD": { - "required": "candidate_category, standard_evidence, metadata_evidence", - "output": "输出自然语言验证结论,明确标准描述与元数据语义是否一致。", - "optional": "无", - "purpose": "Verifies whether a candidate category is jointly supported by metadata and standard evidence." - }, - "SEARCH_STANDARD_BY_FIELD": { - "required": "field_semantics", - "output": "输出字段语义最相关的标准候选及匹配依据。", - "optional": "无", - "purpose": "Retrieves standard categories relevant to the target-field semantics." - }, - "GET_CONTEXT_FIELD_TYPES": { - "required": "table_name, context_fields", - "output": "输出上下文字段类型的自然语言摘要,说明类型能提供的有限辅助信息。", - "optional": "无", - "purpose": "Retrieves data types of selected contextual fields as supporting evidence." - }, - "CHECK_METADATA_AVAILABILITY": { - "required": "current_record", - "output": "输出自然语言可用性摘要,列出当前可直接使用和缺失的元数据类型,并指出可行的下一步信息获取方向。", - "optional": "无", - "purpose": "Identifies which metadata attributes are currently available or missing." - }, - "RESOLVE_METADATA_CONFLICT": { - "required": "conflicting_metadata_evidence", - "output": "输出自然语言冲突消解结论和依据。", - "optional": "无", - "purpose": "Resolves conflicting semantic evidence across metadata granularities." - }, - "VERIFY_CLASSIFICATION_GRADING_CONSISTENCY": { - "required": "category_candidate, grading_level_candidate, current_evidence", - "output": "输出自然语言一致性检查结论及可能的矛盾点。", - "optional": "无", - "purpose": "Checks semantic consistency between the predicted category and Grading-level." - }, - "RESOLVE_FIELD_CONTEXT_CONFLICT": { - "required": "field_evidence, context_evidence", - "output": "输出冲突点、比较依据、保留的解释以及仍需补充的信息。", - "optional": "无", - "purpose": "Resolves conflicts between target-field evidence and contextual-field evidence." - }, - "FINALIZE_CLASSIFICATION": { - "required": "final_evidence_state", - "output": "最终输出结构化结果:category 与 grading_level;可附一段简短 final_reasoning,但不再继续获取新证据。", - "optional": "无", - "purpose": "Terminates the reasoning program and produces the final classification and grading prediction." - }, - "GET_CONTEXT_FIELD_DESCRIPTIONS": { - "required": "table_name, context_fields", - "output": "输出所选上下文字段的描述及自然语言摘要;缺失描述需明确标记。", - "optional": "无", - "purpose": "Retrieves descriptions for selected contextual fields." - }, - "SELECT_CONTEXT_FIELDS": { - "required": "target_field, table_fields", - "output": "输出自然语言说明选择了哪些上下文字段、为什么它们更有信息价值,以及哪些字段被忽略。", - "optional": "current_semantic_state", - "purpose": "Selects the most informative contextual fields for the target field." - }, - "FUSE_FIELD_EVIDENCE": { - "required": "available_field_evidence", - "output": "输出字段级统一自然语言证据状态,区分直接证据、辅助证据和歧义。", - "optional": "无", - "purpose": "Integrates all available evidence directly associated with the target field." - }, - "INTERPRET_TABLE_DESCRIPTION": { - "required": "table_description", - "output": "输出表描述的自然语言摘要,并说明其对目标字段语义理解的辅助作用。", - "optional": "table_name, domain", - "purpose": "Extracts and summarizes the semantic content of a table description." - }, - "FUSE_TABLE_EVIDENCE": { - "required": "available_table_evidence", - "output": "输出统一表级自然语言证据状态。", - "optional": "无", - "purpose": "Integrates all available table-level semantic evidence." - }, - "INFER_GRADING_LEVEL": { - "required": "aligned_category, aligned_standard_entry", - "output": "输出自然语言说明最终 category 对齐到哪个标准条目,以及该条目明确给出的 grading_level。", - "optional": "无", - "purpose": "Determines the Grading-level from the grading_level associated with the aligned standard category." - }, - "INTERPRET_FIELD_NAME": { - "required": "field_name", - "output": "输出对字段名整体语义的自然语言解释,包括主要候选含义与简要依据。", - "optional": "domain", - "purpose": "Interprets the overall semantic meaning of a field name." - }, - "DECIDE_NEXT_EVIDENCE_SOURCE": { - "required": "current_evidence_state, available_metadata", - "output": "输出自然语言下一步建议,例如解释字段、获取同表字段、解释表/库、查询/重查标准或停止;不得调用超出可用信息范围的数据源。", - "optional": "无", - "purpose": "Determines which available evidence source should be explored next." - }, - "ALIGN_CONTEXT_TO_STANDARD": { - "required": "context_semantics, standard_candidates", - "output": "输出上下文语义对候选标准类别的支持、反对或弱相关关系。", - "optional": "无", - "purpose": "Aligns contextual semantic evidence with candidate standard categories." - }, - "WEIGH_EVIDENCE": { - "required": "evidence_set", - "output": "输出自然语言说明哪些证据更强、哪些只是辅助,以及原因;不输出未经依据的数值权重。", - "optional": "无", - "purpose": "Assesses the relative reliability and importance of available evidence." - }, - "FUSE_METADATA_EVIDENCE": { - "required": "available_metadata_evidence", - "output": "输出统一 metadata evidence state,并指出不同粒度证据的一致与冲突。", - "optional": "无", - "purpose": "Integrates multi-granularity metadata evidence into a unified semantic state." - }, - "SYNTHESIZE_METADATA_SEMANTICS": { - "required": "field_semantics", - "output": "输出一段紧凑但信息充分的自然语言 semantic state,区分强证据、辅助证据和仍存在的歧义。", - "optional": "domain_semantics, table_semantics, database_semantics, context_field_semantics, field_description_semantics, field_type_semantics, value_semantics", - "purpose": "Synthesizes all available metadata interpretations into a unified natural-language semantic state." - }, - "EXPAND_DATABASE_ABBREVIATION": { - "required": "database_name", - "output": "输出数据库/系统缩写的自然语言展开及可能的业务范围。", - "optional": "domain, database_description", - "purpose": "Expands an abbreviated database or system name into its likely semantic meaning." - }, - "SEARCH_STANDARD_BY_CONTEXT": { - "required": "context_semantics", - "output": "输出上下文语义最相关的标准候选,并说明其对目标字段的辅助意义。", - "optional": "无", - "purpose": "Retrieves standard categories using contextual-field semantics." - }, - "INTERPRET_CONTEXT_FIELDS": { - "required": "context_fields", - "output": "输出各上下文字段的简要语义及它们共同指向的业务场景;不直接替目标字段做最终分类。", - "optional": "domain, table_name", - "purpose": "Interprets neighboring fields and summarizes the business context jointly implied by them." - }, - "FUSE_DATABASE_EVIDENCE": { - "required": "available_database_evidence", - "output": "输出数据库级自然语言背景及其对目标字段的高层约束。", - "optional": "无", - "purpose": "Integrates database-level semantic evidence." - }, - "ALIGN_VALUE_TO_STANDARD": { - "required": "value_semantics, standard_candidates", - "output": "输出字段值模式对标准候选的支持程度;强调值证据通常是辅助证据。", - "optional": "无", - "purpose": "Aligns value-derived semantics with candidate standard categories." - }, - "COMPARE_CATEGORY_HYPOTHESES": { - "required": "candidate_categories, evidence", - "output": "输出候选类别的自然语言排序与关键区分依据。", - "optional": "无", - "purpose": "Compares competing standard-category hypotheses." - }, - "INTERPRET_DOMAIN": { - "required": "domain", - "output": "输出一段自然语言,说明该领域通常涉及的数据对象、术语语境,以及它对当前元数据解释可提供的约束;不直接给出最终分类。", - "optional": "无", - "purpose": "Interprets the domain context and provides domain-specific semantic background for subsequent metadata understanding." - }, - "REFINE_STANDARD_QUERY": { - "required": "previous_standard_results, current_semantic_state", - "output": "输出一段更聚焦的自然语言查询表达,并说明为何这样改写能区分当前候选。", - "optional": "无", - "purpose": "Refines the standard-search query using previous retrieval results and the current semantic state." - }, - "SEARCH_STANDARD": { - "required": "semantic_query", - "output": "输出最相关的若干标准类别标签及其描述的自然语言摘要,说明为何相关;不额外引入标准库不存在的字段。", - "optional": "无", - "purpose": "Searches the standard corpus using the current semantic representation." - }, - "ASSESS_CATEGORY_SUPPORT": { - "required": "candidate_category, evidence", - "output": "输出自然语言支持评估:支持证据、反对证据、薄弱点和总体判断。", - "optional": "无", - "purpose": "Assesses how strongly the current evidence supports a candidate category." - }, - "INTERPRET_FIELD_TYPE": { - "required": "field_type", - "output": "输出字段类型可提供的约束性自然语言判断;不得仅凭类型强行确定具体类别。", - "optional": "field_name, field_description", - "purpose": "Uses the field data type as supporting semantic evidence." - }, - "RESOLVE_STANDARD_CONFLICT": { - "required": "conflicting_standard_alignments", - "output": "输出哪个标准候选更可信、为什么,以及仍存在的歧义。", - "optional": "无", - "purpose": "Resolves conflicts among competing standard alignments." - }, - "SEARCH_STANDARD_BY_DATABASE": { - "required": "database_semantics", - "output": "输出数据库级语义可能支持的标准类别范围和依据。", - "optional": "无", - "purpose": "Uses database-level semantics to retrieve or constrain candidate standard categories." - }, - "GET_COMPLETE_DATABASE_CONTEXT": { - "required": "database_name", - "output": "输出数据库级自然语言背景摘要,不引入跨库信息。", - "optional": "无", - "purpose": "Retrieves the available high-level metadata context of the current database." - }, - "INTERPRET_TABLE_NAME": { - "required": "table_name", - "output": "输出表级自然语言语义,强调该表可能描述什么业务数据。", - "optional": "domain, table_description", - "purpose": "Interprets the business semantics represented by a table name." - }, - "ALIGN_FIELD_TO_STANDARD": { - "required": "field_semantics, standard_candidates", - "output": "输出字段语义与各候选标准描述的匹配/不匹配理由,以及当前更优候选。", - "optional": "无", - "purpose": "Aligns the target-field semantics with candidate standard categories." - }, - "INTERPRET_DATABASE_NAME": { - "required": "database_name", - "output": "输出数据库级自然语言语义,作为当前字段的高层背景。", - "optional": "domain, database_description", - "purpose": "Interprets the domain and semantic scope implied by the database name." - }, - "EXPAND_FIELD_ABBREVIATION": { - "required": "field_name", - "output": "输出字段缩写的候选展开及依据;如果存在歧义,应保留多个候选并说明不确定来源。", - "optional": "domain", - "purpose": "Expands an abbreviated field name into one or more plausible natural-language meanings." - }, - "CHECK_EVIDENCE_SUFFICIENCY": { - "required": "current_evidence", - "output": "输出自然语言说明“足够/不足”的依据;不足时明确建议继续获取哪类既有信息。", - "optional": "无", - "purpose": "Determines whether the current evidence is sufficient for reliable classification." - }, - "INTERPRET_FIELD_VALUE": { - "required": "value", - "output": "输出值模式的自然语言描述、可能对应的数据含义,以及这种证据的可靠性边界。", - "optional": "field_name, field_type, domain", - "purpose": "Infers possible semantics from the observed value pattern and content." - }, - "INFER_CATEGORY": { - "required": "candidate_standard_categories, all_available_evidence", - "output": "输出自然语言说明为何选择某一 category_label 作为 category;此处仍可保留解释文本,最终结构化由 FINALIZE 完成。", - "optional": "无", - "purpose": "Infers the final Category category from candidate standard categories and accumulated evidence." - }, - "FUSE_STANDARD_EVIDENCE": { - "required": "standard_alignment_evidence", - "output": "输出统一标准证据状态,明确主要支持类别和弱支持类别。", - "optional": "无", - "purpose": "Integrates multiple standard-alignment results into a unified standard-evidence state." - }, - "ALIGN_TABLE_TO_STANDARD": { - "purpose": "Aligns table-level semantics with candidate standard categories.", - "required": "table_semantics, standard_candidates", - "optional": "无", - "output": "Explain how table context supports, contradicts or weakly matches each actual standard candidate; context remains auxiliary to target-field evidence." - }, - "ALIGN_DATABASE_TO_STANDARD": { - "purpose": "Aligns database-level semantics with candidate standard categories.", - "required": "database_semantics, standard_candidates", - "optional": "无", - "output": "Explain how database context supports, contradicts or weakly matches each actual standard candidate; context remains auxiliary to target-field evidence." - } -} diff --git a/research/finance_program_v1/nontraining/vendor/study.py b/research/finance_program_v1/nontraining/vendor/study.py deleted file mode 100644 index 82d329c..0000000 --- a/research/finance_program_v1/nontraining/vendor/study.py +++ /dev/null @@ -1,323 +0,0 @@ -"""Frozen full-pool study identity and independently reconstructible metrics.""" -from __future__ import annotations - -from collections import Counter -import hashlib -import json -import copy -from pathlib import Path - -from common import fingerprint, read_json, read_jsonl, sha256, write_json - -ROOT = Path(__file__).resolve().parent -ADAPTER_SKILLS = ('SELECT_CATEGORY_TOPK', 'INFER_CATEGORY_FROM_TOPK') -P14_SKILLS = frozenset(('CHECK_METADATA_AVAILABILITY','INTERPRET_DOMAIN','EXPAND_FIELD_ABBREVIATION', - 'INTERPRET_FIELD_NAME','DISAMBIGUATE_FIELD_SEMANTICS','SELECT_CATEGORY_TOPK', - 'COMPARE_STANDARD_CANDIDATES','CHECK_EVIDENCE_SUFFICIENCY','INFER_CATEGORY_FROM_TOPK', - 'INFER_GRADING_LEVEL','FINALIZE_CLASSIFICATION','GET_FIELD_METADATA', - 'INTERPRET_FIELD_DESCRIPTION','INTERPRET_TABLE_DESCRIPTION')) -BASE_CONFIG = { - 'raw_metadata_schema_version': 'initial-record-plus-acquired-raw-v2', - 'binding_rule_version': 'canonical-state-bindings-v1', - 'evidence_schema_version': 'typed-observed-evidence-v2', - 'schema': 1, 'pools': ['P14', 'F66'], 'conditions': ['base', 'sft'], - 'condition_order': 'all-base-before-any-sft', - 'selection': 'sha256(finance-followup-20261004: + source_id), ascending digest; ID tie-break', - 'pilot_size': 20, 'expanded_size': 60, 'smoke_size': 2, - 'generator_seed': 20260928, - 'generation': {'max_new_tokens': 512, 'enable_thinking': False, 'do_sample': False, - 'eos_token_ids': [248044, 248046], 'local_files_only': True}, - 'loop': {'max_turns': 8, 'max_identical_calls': 2, 'action_retries': 1, - 'forced_finalize_retries': 1, 'repetition_retries': 1, - 'recover_ready_finalization': True}, - 'native_standard_backend': 'model-catalog-top5-v1', - 'adapter_skills': list(ADAPTER_SKILLS), 'new_training': False, - 'primary_recall': 'last-successful-top5', - 'metadata_source_scope': 'frozen-Val-unlabelled-only', -} - -VARIANTS = {name: {'variant':name,'missing_awareness':aware,'max_turns':turns} - for name,aware,turns in [('A',False,8),('B',True,8),('C',False,12),('D',True,12)]} - -P14_ARMS = { - 'O': {'variant':'C','metadata_prefetch':False,'top1_selection_mode':'model'}, - 'D': {'variant':'D','metadata_prefetch':False,'top1_selection_mode':'model'}, - 'M': {'variant':'D','metadata_prefetch':True,'top1_selection_mode':'model'}, - 'E': {'variant':'D','metadata_prefetch':False,'top1_selection_mode':'first'}, - 'ME': {'variant':'D','metadata_prefetch':True,'top1_selection_mode':'first'}, -} - - -def load_config(root=ROOT): - path = Path(root)/'variant.json' - variant = read_json(path) if path.exists() else VARIANTS['A'] - if (not isinstance(variant,dict) or set(variant) != {'variant','missing_awareness','max_turns'} - or type(variant.get('missing_awareness')) is not bool - or type(variant.get('max_turns')) is not int - or variant.get('variant') not in VARIANTS - or variant != VARIANTS[variant['variant']]): - raise ValueError('invalid canonical variant configuration') - config = copy.deepcopy(BASE_CONFIG) - config.update({'variant':variant['variant'],'missing_awareness':variant['missing_awareness']}) - config['loop']['max_turns'] = variant['max_turns'] - control_path = Path(root)/'p14_controls.json' - if control_path.exists(): - control = read_json(control_path) - if (not isinstance(control,dict) or set(control) != {'arm','metadata_prefetch','top1_selection_mode'} - or type(control.get('arm')) is not str or control['arm'] not in P14_ARMS - or type(control.get('metadata_prefetch')) is not bool - or type(control.get('top1_selection_mode')) is not str): - raise ValueError('invalid P14 control declaration') - expected=P14_ARMS[control['arm']] - if (not path.is_file() or variant != VARIANTS[expected['variant']] - or {k:v for k,v in control.items() if k!='arm'} != {k:v for k,v in expected.items() if k!='variant'}): - raise ValueError('P14 control combination or variant differs') - config.update({'p14_arm':control['arm'],'metadata_prefetch':control['metadata_prefetch'], - 'top1_selection_mode':control['top1_selection_mode'],'pools':['P14'], - 'conditions':['sft'],'condition_order':'existing-adapter-only-no-new-training'}) - return config - - -CONFIG = load_config() - - -def select_cohorts(rows): - ids = [row.get('source_id') for row in rows] - if any(not isinstance(sid, str) or not sid for sid in ids) or len(ids) != len(set(ids)): - raise ValueError('source IDs must be nonempty unique strings') - size = CONFIG['pilot_size'] + CONFIG['expanded_size'] + CONFIG['smoke_size'] - if len(ids) < size: - raise ValueError('too few rows for disjoint Pilot, Expanded and smoke') - ordered = sorted(ids, key=lambda sid: (hashlib.sha256(('finance-followup-20261004:'+sid).encode()).hexdigest(), sid)) - return {'pilot': ordered[:20], 'expanded': ordered[20:80], 'smoke': ordered[80:82]} - - -def adapter_route(condition, messages): - if condition not in CONFIG['conditions']: - raise ValueError('unknown condition') - if condition == 'base' or not messages or messages[0].get('role') != 'system': - return None - header = messages[0].get('content', '') - return next((name for name in ADAPTER_SKILLS - if header.startswith(f'Execute only the selected Skill {name}.\n')), None) - - -def execution_files(root): - root = Path(root) - paths = list(root.glob('*.py')) + list(root.glob('*.sh')) - paths += list((root/'runtime/code').rglob('*.py')) - paths += list((root/'runtime/skills').rglob('*.md')) - paths += list((root/'runtime/tests').rglob('*.py')) - paths += [path for folder in ('runtime/config', 'runtime/tests/fixtures') - for path in (root/folder).rglob('*') if path.is_file()] - paths += list((root/'tests').rglob('*.py')) - for name in ('variant.json','p14_controls.json'): - if (root/name).exists(): - paths.append(root/name) - paths += [root/name for name in ( - 'data/val.jsonl', 'data/metadata-val.json', 'data/registry.json', - 'data/split_boundaries.json', 'reference_skills_63.json', 'skill_reference.json', 'model_artifacts.json', - 'adapter_completion_reference.json')] - if any(path.is_symlink() or not path.resolve().is_relative_to(root.resolve()) for path in paths): - raise ValueError('execution inventory path escape or symbolic link') - return {path.relative_to(root).as_posix(): sha256(path) for path in sorted(set(paths))} - - -def freeze_study(root=ROOT): - root = Path(root) - if (root/'frozen/manifest.json').exists(): - raise ValueError('refuse to overwrite frozen study') - cohorts = select_cohorts(read_jsonl(root/'data/val.jsonl')) - payload = {'config': load_config(root), 'cohorts': cohorts, 'files': execution_files(root), - 'expected_base_manifest': read_json(root/'model_artifacts.json'), - 'adapter': read_json(root/'adapter_completion_reference.json'), - 'scope': 'development validation; no new SFT; not untouched Test'} - manifest = {**payload, 'execution_signature': fingerprint(payload)} - write_json(root/'frozen/manifest.json', manifest) - return manifest - - -def check_study(root=ROOT): - root = Path(root) - manifest = read_json(root/'frozen/manifest.json') - if fingerprint({k:v for k,v in manifest.items() if k != 'execution_signature'}) != manifest.get('execution_signature'): - raise ValueError('frozen manifest signature mismatch') - if manifest.get('config') != load_config(root): - raise ValueError('frozen configuration changed') - if manifest.get('files') != execution_files(root): - raise ValueError('execution file inventory changed') - if manifest.get('cohorts') != select_cohorts(read_jsonl(root/'data/val.jsonl')): - raise ValueError('frozen cohort selection changed') - return manifest - - -def write_jsonl(path, rows): - path = Path(path) - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(path.name+'.tmp') - temporary.write_text(''.join(json.dumps(row, ensure_ascii=False, sort_keys=True)+'\n' for row in rows), encoding='utf-8') - temporary.replace(path) - - -def prepare_resume(output, identity, ids, resume): - output = Path(output) - output.mkdir(parents=True, exist_ok=True) - manifest_path = output/'manifest.json' - if manifest_path.exists(): - previous = {k:v for k,v in read_json(manifest_path).items() if k != 'status'} - if not resume or previous != identity: - raise ValueError('refuse overwrite or changed resume identity') - elif any(output.iterdir()): - raise ValueError('unknown output artifacts without identity') - saved = read_jsonl(output/'traces.jsonl') if (output/'traces.jsonl').exists() else [] - completed_ids = [row.get('source_id') for row in saved] - if len(completed_ids) != len(set(completed_ids)): - raise ValueError('duplicate saved sample IDs') - if not set(completed_ids) <= set(ids): - raise ValueError('saved sample ID outside frozen cohort') - if not manifest_path.exists(): - write_json(manifest_path, identity) - return saved - - -def candidate_history(row, registry): - history = [] - for event in row['trace'].get('events', []): - data = event.get('data', {}) - outputs = data.get('data', {}) - if event.get('kind') != 'observation' or data.get('status') != 'success' or 'standard_candidates' not in outputs: - continue - candidates = outputs['standard_candidates'] - if not isinstance(candidates, list) or any(not isinstance(c, dict) for c in candidates): - raise ValueError('invalid candidate observation shape') - ids = [c.get('category') or c.get('category_id') for c in candidates] - if len(ids) != 5 or len(set(ids)) != 5 or not set(ids) <= set(registry): - raise ValueError('candidate observation is not five distinct frozen Registry IDs') - history.append(ids) - return history - - -def _macro_f1(golds, predictions, labels): - scores = [] - for label in labels: - tp = sum(g == label and p == label for g,p in zip(golds, predictions)) - fp = sum(g != label and p == label for g,p in zip(golds, predictions)) - fn = sum(g == label and p != label for g,p in zip(golds, predictions)) - scores.append(2*tp/(2*tp+fp+fn) if 2*tp+fp+fn else 0.0) - return sum(scores)/len(scores) if scores else 0.0 - - -def summarize(rows, registry, supported_classes): - n = len(rows) - if len({r['source_id'] for r in rows}) != n: - raise ValueError('duplicate sample ID in scoring') - totals = Counter() - skills = Counter() - successes = Counter() - failures = Counter() - interventions = Counter() - stop_reasons = Counter() - golds, predictions = [], [] - elapsed = 0.0 - new_sample_count = 0 - for row in rows: - trace = row['trace'] - final = trace.get('final_result') or {} - terminated = bool(trace.get('terminated')) - prediction = final.get('category') if terminated else None - predicted_level = final.get('grading_level') if terminated else None - gold, level = row['ground_truth'], row['ground_truth_level'] - if terminated and (prediction not in registry or registry[prediction].get('grading_level') != predicted_level): - raise ValueError('terminal result disagrees with frozen Registry') - golds.append(gold) - predictions.append(prediction) - correct = terminated and prediction == gold - level_correct = terminated and predicted_level == level - totals['terminated'] += terminated - totals['category_correct'] += correct - totals['level_correct'] += level_correct - totals['joint_correct'] += correct and level_correct - stop_reasons[trace.get('stop_reason', 'unknown')] += 1 - recovered = False - used_new = False - for event in trace.get('events', []): - data = event.get('data', {}) - kind = event.get('kind') - if kind == 'controller_intervention': - reason = data.get('reason', 'unknown') - interventions[reason] += 1 - recovered |= reason in {'forced_finalization', 'invalid_action_finalization_recovery'} - if kind == 'policy_action': - tool = data.get('call', data).get('tool') - if tool: - skills[tool] += 1 - totals['skill_calls'] += 1 - used_new |= tool not in P14_SKILLS - if kind == 'observation': - tool = data.get('skill', 'unknown') - if data.get('status') == 'success': - successes[tool] += 1 - totals['successful_skill_calls'] += 1 - else: - failures[tool] += 1 - totals['observation_failures'] += 1 - totals['unavailable_skill_calls'] += data.get('status') == 'unavailable' - if kind == 'retry': - totals['retry_events'] += 1 - if kind in {'retry', 'rejected_action'} and data.get('reason') in {'invalid_action','uncallable_skill','invalid_arguments','stop_without_final_result'}: - totals['invalid_policy_attempts'] += 1 - if data.get('reason') == 'stop_without_final_result': - totals['early_stop_attempts'] += 1 - if kind == 'policy_action' and data.get('messages') and not data.get('forced_finalize'): - totals['accepted_policy_actions'] += 1 - totals['recovered_terminated'] += terminated and recovered - totals['normal_terminated'] += terminated and not recovered - new_sample_count += used_new - history = candidate_history(row, registry) - totals['top5_first_hit'] += bool(history and gold in history[0]) - totals['top5_last_hit'] += bool(history and gold in history[-1]) - totals['top5_any_hit_diagnostic'] += any(gold in c for c in history) - totals['samples_with_retrieval'] += bool(history) - totals['multiple_retrieval_samples'] += len(history) > 1 - if not correct: - if not history: - totals['no_retrieval_failures'] += 1 - elif gold not in history[-1]: - totals['last_top5_miss_failures'] += 1 - elif not terminated: - totals['hit_but_nonterminal_failures'] += 1 - else: - totals['candidate_inside_wrong_choice'] += 1 - totals['runner_errors'] += bool(row.get('error')) - for call in row.get('generation_calls', []): - meta = call.get('generation', {}) - totals['model_calls'] += 1 - totals['backend_failed_calls'] += bool(call.get('error')) - totals['total_tokens'] += int(meta.get('token_usage', {}).get('total_tokens') or 0) - elapsed += float(meta.get('elapsed_seconds') or 0) - expected_counters = ('terminated','category_correct','level_correct','joint_correct', - 'normal_terminated','recovered_terminated','top5_first_hit','top5_last_hit', - 'top5_any_hit_diagnostic','model_calls','total_tokens','skill_calls', - 'successful_skill_calls','runner_errors','backend_failed_calls', - 'no_retrieval_failures','last_top5_miss_failures','hit_but_nonterminal_failures', - 'candidate_inside_wrong_choice','observation_failures','retry_events', - 'early_stop_attempts','samples_with_retrieval','multiple_retrieval_samples') - result = {'denominator': n, **{key: totals[key] for key in expected_counters}, **dict(totals), - 'model_elapsed_seconds': elapsed, - 'macro_f1_supported': _macro_f1(golds, predictions, supported_classes), - 'macro_f1_fixed12': _macro_f1(golds, predictions, sorted(registry)), - 'supported_class_count': len(supported_classes), 'fixed_class_count': len(registry), - 'distinct_skills_used': len(skills), 'skills_called': dict(sorted(skills.items())), - 'skills_succeeded': dict(sorted(successes.items())), 'skills_failed': dict(sorted(failures.items())), - 'controller_interventions': dict(sorted(interventions.items())), - 'stop_reasons': dict(sorted(stop_reasons.items()))} - result.update({'new_skills_called':{k:v for k,v in sorted(skills.items()) if k not in P14_SKILLS}, - 'samples_using_new_skills':new_sample_count, - 'unavailable_skill_calls':totals['unavailable_skill_calls'], - 'invalid_policy_attempts':totals['invalid_policy_attempts'], - 'accepted_policy_actions':totals['accepted_policy_actions'], - 'legal_action_rate':totals['accepted_policy_actions']/(totals['accepted_policy_actions']+totals['invalid_policy_attempts']) - if totals['accepted_policy_actions']+totals['invalid_policy_attempts'] else 0.0}) - for key in ('terminated','category_correct','level_correct','joint_correct','top5_first_hit','top5_last_hit'): - result[key+'_rate'] = result[key]/n if n else 0.0 - return result diff --git a/research/finance_program_v1/publication_tests/test_dependency_closure.py b/research/finance_program_v1/publication_tests/test_dependency_closure.py index dfaaaa7..9065791 100644 --- a/research/finance_program_v1/publication_tests/test_dependency_closure.py +++ b/research/finance_program_v1/publication_tests/test_dependency_closure.py @@ -1,4 +1,5 @@ """Fresh-process public entrypoint checks; no private workspace or model calls.""" + from pathlib import Path import subprocess import sys @@ -9,37 +10,56 @@ class PublicDependencyTests(unittest.TestCase): def run_python(self, folder, code): - prefix = 'import sys; from pathlib import Path; sys.path.insert(0,str(Path.cwd())); ' - result = subprocess.run([sys.executable, '-I', '-B', '-c', prefix + code], - cwd=ROOT / folder, capture_output=True, text=True) + prefix = "import sys; from pathlib import Path; sys.path.insert(0,str(Path.cwd())); " + result = subprocess.run( + [sys.executable, "-I", "-B", "-c", prefix + code], + cwd=ROOT / folder, + capture_output=True, + text=True, + ) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - def test_nontraining_audit_imports_without_private_checkout(self): - self.run_python('nontraining', - 'import batch_audit; from reviews.independent_audit_01 import RecordedBackend; ' - 'b=RecordedBackend([]); b.finish(); ' - 'assert "torch" not in sys.modules and "transformers" not in sys.modules') - - def test_pool_metadata_resolves_through_public_controller(self): - self.run_python('nontraining', - 'import program_loop; import pool_metadata; ' - 'assert Path(pool_metadata.__file__).resolve().parent == Path.cwd()/"vendor"') + def test_mainline_uses_one_complete_f66_runtime(self): + self.run_python( + "evaluation", + """ +import io_utils +from program_loop import build_program_controller +import pool_metadata +registry={'fixture-'+str(i): {'description':'synthetic class', 'grading_level':'L1'} for i in range(12)} +budget={'max_programs':3,'max_program_steps':10,'max_skill_steps':12,'max_planner_attempts':4,'max_identical_calls':1} +controller=build_program_controller(lambda messages:'invalid JSON',registry,[],budget,skill_pool='F66') +assert len(controller.library)==66 +assert Path(pool_metadata.__file__).resolve()==Path.cwd()/'runtime/vendor/pool_metadata.py' +assert not (Path.cwd().parent/'nontraining/program_loop/controller.py').exists() +trace=controller.run({'domain':'finance','field_name':'synthetic-field'}) +assert not trace.terminated and trace.stop_reason=='planner_budget_exhausted' +assert trace.budget=={'programs':0,'planner_attempts':4,'skill_steps':0} +assert 'torch' not in sys.modules and 'transformers' not in sys.modules +""", + ) def test_teacher_recorded_audit_and_runtime_have_local_code(self): - self.run_python('teacher', - 'import detached, pilot_audit, runtime_identity; ' - 'assert callable(pilot_audit.replay_retry_one); ' - 'assert Path(runtime_identity.__file__).resolve().is_relative_to(Path.cwd().parent); ' - 'assert "torch" not in sys.modules') + self.run_python( + "teacher", + "import detached, pilot_audit, runtime_identity; " + "assert callable(pilot_audit.replay_retry_one); " + "assert Path(runtime_identity.__file__).resolve().is_relative_to(Path.cwd().parent); " + 'assert "torch" not in sys.modules', + ) def test_legacy_revision_helper_has_no_private_import(self): - self.run_python('evaluation', - 'import io_utils; from tools.freeze_revision import safe_path, signature; ' + self.run_python( + "evaluation", + "import io_utils; from tools.freeze_revision import safe_path, signature; " 'assert safe_path(Path.cwd(),"safe/file.json")==Path.cwd()/"safe/file.json"; ' - 'assert len(signature([]))==64') + "assert len(signature([]))==64", + ) def test_teacher_nonterminal_trace_replays_and_rejects_tampering(self): - self.run_python('teacher', ''' + self.run_python( + "teacher", + """ import json, copy import detached from program_loop import build_program_controller @@ -74,68 +94,9 @@ def backend(messages): except AssertionError: pass else: raise AssertionError('tampered teacher request accepted') assert 'torch' not in sys.modules -''') - - def test_public_audit_manifest_binds_shipped_source(self): - self.run_python('nontraining', - 'from local_smoke import environment; from reviews.independent_audit_01 import validate_sources; ' - 'validate_sources(Path.cwd(),environment("not-a-model"))') - - def test_public_source_audit_rejects_mutation_and_missing_file(self): - self.run_python('nontraining', ''' -import shutil, tempfile -from local_smoke import environment -from reviews.independent_audit_01 import validate_sources, AuditError -with tempfile.TemporaryDirectory() as d: - snapshot=Path(d)/'snapshot'; shutil.copytree(Path.cwd(),snapshot) - environment_evidence=environment('not-a-model') - validate_sources(snapshot,environment_evidence) - target=snapshot/'vendor/pool_metadata.py'; original=target.read_bytes() - target.write_bytes(original+bytes([10])+b'# changed') - try: validate_sources(snapshot,environment_evidence) - except AuditError: pass - else: raise AssertionError('changed source accepted') - target.unlink() - try: validate_sources(snapshot,environment_evidence) - except AuditError: pass - else: raise AssertionError('missing source accepted') -''') - - def test_batch_audit_replays_real_scripted_controller(self): - self.run_python('nontraining', ''' -import json, tempfile, hashlib -from batch_runner import run_batch -from batch_audit import audit -class Scripted: - def __init__(self, model, call_dir): - self.folder=Path(call_dir); self.folder.mkdir(parents=True); self.calls=[]; self.failures=[] - def __call__(self,messages): - system=messages[0]['content'] - if 'Global Program Planner' in system: - raw=json.dumps({'program':[{'tool':n,'arguments':{}} for n in ('GET_FIELD_METADATA','INTERPRET_FIELD_NAME','SELECT_CATEGORY_TOPK','INFER_CATEGORY_FROM_TOPK','INFER_GRADING_LEVEL','FINALIZE_CLASSIFICATION')]}) - elif 'selected Skill SELECT_CATEGORY_TOPK.' in system: - raw=json.dumps({'option_ids':['C001','C002','C003','C004','C005'],'summary':'rank'}) - elif 'selected Skill INFER_CATEGORY_FROM_TOPK.' in system: - raw=json.dumps({'option_id':'C001','summary':'choice'}) - else: raw=json.dumps({'summary':'interpret','data':{'field_semantics':'observed field'}}) - folder=self.folder/('call-%04d'%(len(self.calls)+1)); folder.mkdir(); self.calls.append(str(folder)) - for name,value in [('request',{'messages':messages}),('result',{'messages':messages,'raw_text':raw,'error':None,'input_tokens':1,'output_tokens':2,'seconds':0.01})]: - (folder/(name+'.json')).write_text(json.dumps(value),encoding='utf-8') - return raw -with tempfile.TemporaryDirectory() as d: - d=Path(d) - study={'schema':1,'cohorts':{'smoke':['fixture-001'],'pilot':[],'expanded':[]},'rows':[{'id':'fixture-001','domain':'finance','metadata':{'field_name':'balance','field_description':'fixture description'}}],'registry':{'cat'+str(i):{'description':'fixture class '+str(i),'grading_level':'L1'} for i in range(1,13)},'budget':{'max_programs':3,'max_program_steps':10,'max_skill_steps':12,'max_planner_attempts':4,'max_identical_calls':1}} - p=d/'study.json'; p.write_text(json.dumps(study),encoding='utf-8') - (d/'study-manifest.json').write_text(json.dumps({'study_sha256':hashlib.sha256(p.read_bytes()).hexdigest()}),encoding='utf-8') - assert run_batch('not-a-model',d/'run','smoke',study_path=p,backend_factory=Scripted)==0 - proof=audit(d/'run',study_path=p,allow_scripted_fixture=True) - assert proof['verified_samples']==1 and proof['full_trace_exact'] and proof['all_calls_consumed'] - q=d/'run/calls/call-0001/request.json'; data=json.loads(q.read_bytes()); data['messages'][0]['content']+='changed'; q.write_text(json.dumps(data),encoding='utf-8') - try: audit(d/'run',study_path=p,allow_scripted_fixture=True) - except AssertionError: pass - else: raise AssertionError('tampered request incorrectly accepted') -''') +""", + ) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/research/finance_program_v1/sft/README.md b/research/finance_program_v1/sft/README.md new file mode 100644 index 0000000..2843f08 --- /dev/null +++ b/research/finance_program_v1/sft/README.md @@ -0,0 +1,7 @@ +# 第一版 Planner-only SFT + +按 `export_dataset.py` → `token_audit.py` → 最长来源trial → fresh formal顺序阅读。只监督真实Planner Program JSON与EOS;Skill返回和评估标签不进入loss。200来源、1epoch、13更新、LoRA r8/alpha16/dropout.05,语言层40目标,base/vision冻结。完整参数及资源见 [实验协议](../docs/EXPERIMENT_PROTOCOL.md)。 + +`train_student.py`负责计算,`completion_loss.py`对齐因果completion logits,`training_contract.py`核trial/GPU门,`pipeline.py`管理子进程与独占锁,`runtime_io.py`保存不可覆盖的manifest证据。源码使用实际PyTorch/Transformers Trainer/PEFT接口;这不是替换为其他训练框架或新训练。 + +运行CPU检查:`python -B -m unittest discover -s tests -v`。真实训练需要未公开的planner200、token审计、manifest和模型文件,不能把公开脱敏teacher轨迹直接喂入训练。当前整理没有重训或生成新checkpoint。 diff --git a/research/finance_program_v1/sft/archive_run.py b/research/finance_program_v1/sft/archive_run.py index 6c20b96..2be07bb 100644 --- a/research/finance_program_v1/sft/archive_run.py +++ b/research/finance_program_v1/sft/archive_run.py @@ -1,4 +1,5 @@ """Immutable complete post-stage evidence snapshot; excludes external base weights.""" + # 阶段写入进程退出后再封存证据,归档成员带哈希;外部基座权重不复制进运行档案。 from pathlib import Path import tarfile @@ -8,25 +9,40 @@ def main(): root = Path(__file__).resolve().parent verify_manifest(root) - read(root / 'runs/pipeline.exit.json') - out = root / 'exports/final-01' + read(root / "runs/pipeline.exit.json") + out = root / "exports/final-01" out.mkdir(parents=True, exist_ok=False) - files = sorted(p for p in root.rglob('*') if p.is_file() - and 'exports' not in p.relative_to(root).parts and '__pycache__' not in p.parts - and p.relative_to(root).as_posix() != 'runs/pipeline.log') + files = sorted( + p + for p in root.rglob("*") + if p.is_file() + and "exports" not in p.relative_to(root).parts + and "__pycache__" not in p.parts + and p.relative_to(root).as_posix() != "runs/pipeline.log" + ) # pipeline.log is still open in the outer supervisor; stage logs/true exits are complete. - items = [{'path': p.relative_to(root).as_posix(), 'sha256': digest(p), 'bytes': p.stat().st_size} for p in files] - put(out / 'members.json', items) - archive = out / 'student-sft200-evidence.tar.gz' - with archive.open('xb') as stream, tarfile.open(fileobj=stream, mode='w:gz') as tar: + items = [ + {"path": p.relative_to(root).as_posix(), "sha256": digest(p), "bytes": p.stat().st_size} + for p in files + ] + put(out / "members.json", items) + archive = out / "student-sft200-evidence.tar.gz" + with archive.open("xb") as stream, tarfile.open(fileobj=stream, mode="w:gz") as tar: for p in files: tar.add(p, arcname=p.relative_to(root).as_posix(), recursive=False) - tar.add(out / 'members.json', arcname='archive-members.json', recursive=False) - put(out / 'archive.json', {'archive_sha256': digest(archive), 'bytes': archive.stat().st_size, - 'members': len(items) + 1, 'member_manifest_sha256': digest(out / 'members.json'), - 'pipeline_exit': read(root / 'runs/pipeline.exit.json'), - 'supervisor_log_excluded_because_writer_open': True}) + tar.add(out / "members.json", arcname="archive-members.json", recursive=False) + put( + out / "archive.json", + { + "archive_sha256": digest(archive), + "bytes": archive.stat().st_size, + "members": len(items) + 1, + "member_manifest_sha256": digest(out / "members.json"), + "pipeline_exit": read(root / "runs/pipeline.exit.json"), + "supervisor_log_excluded_because_writer_open": True, + }, + ) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/research/finance_program_v1/sft/completion_loss.py b/research/finance_program_v1/sft/completion_loss.py index 2c2c5f8..7ee7aa9 100644 --- a/research/finance_program_v1/sft/completion_loss.py +++ b/research/finance_program_v1/sft/completion_loss.py @@ -1,4 +1,5 @@ """Full-context causal loss using only logits needed for assistant supervision.""" + # 输入上下文保持完整,仅保留计算响应损失所需的末尾 logits,以减少大词表输出占用的显存。 import torch @@ -14,10 +15,16 @@ def completion_cross_entropy(suffix_logits: torch.Tensor, labels: torch.Tensor): raise ValueError("one example with assistant supervision is required") count = int(counts[0]) start = labels.shape[1] - count - if start < 1 or not torch.all(labels[:, :start].eq(-100)) or not torch.all(supervised[:, start:]): + if ( + start < 1 + or not torch.all(labels[:, :start].eq(-100)) + or not torch.all(supervised[:, start:]) + ): raise ValueError("supervision must be one contiguous suffix after prompt") if suffix_logits.shape[1] != count + 1: raise ValueError("logits must include prompt boundary and one logit per target") # 因果预测向右错一位:prompt 最后位置预测首个响应 token,最后一个 logit 无对应目标。 - return F.cross_entropy(suffix_logits[:, :-1, :].float().reshape(-1, suffix_logits.shape[-1]), - labels[:, start:].reshape(-1)) + return F.cross_entropy( + suffix_logits[:, :-1, :].float().reshape(-1, suffix_logits.shape[-1]), + labels[:, start:].reshape(-1), + ) diff --git a/research/finance_program_v1/sft/export_dataset.py b/research/finance_program_v1/sft/export_dataset.py index ad2b2fb..100c116 100644 --- a/research/finance_program_v1/sft/export_dataset.py +++ b/research/finance_program_v1/sft/export_dataset.py @@ -1,3 +1,4 @@ +# 导出必须绑定真实teacher接受的Program与原始消息;不从redacted视图反造监督。 """Export only frozen, actually executed initial Planner supervision; no labels.""" # 仅导出已复核、实际完成执行的首次 Planner 请求与原始响应,保留来源哈希以追溯监督样本。 import argparse @@ -7,78 +8,186 @@ from pathlib import Path -ROOT=Path(__file__).resolve().parent -TEACHER=ROOT.parent/'finance_program_teacher_balanced_20261016_r9/reviews/final-01' -DELIVERY_SHA='cc9609e98a6b11a4cd0355cef132949d2bb3b171887883b826b31ad751cc8412' +ROOT = Path(__file__).resolve().parent +TEACHER = ROOT.parent / "finance_program_teacher_balanced_20261016_r9/reviews/final-01" +DELIVERY_SHA = "cc9609e98a6b11a4cd0355cef132949d2bb3b171887883b826b31ad751cc8412" -def read(p):return json.loads(Path(p).read_text(encoding='utf-8-sig')) -def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest() -def save(p,value): - p=Path(p);p.parent.mkdir(parents=True,exist_ok=True) - with p.open('x',encoding='utf-8') as f:json.dump(value,f,ensure_ascii=False,indent=2,allow_nan=False) +def read(p): + return json.loads(Path(p).read_text(encoding="utf-8-sig")) -def validate_selection(ids,reserve,expected=200): - if (len(ids)!=expected or len(set(ids))!=expected or len(set(reserve))!=len(reserve) - or set(ids).intersection(reserve) or any(not isinstance(x,str) or not x for x in ids+reserve)): - raise ValueError('frozen unique selection or reserve boundary differs') +def sha(p): + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def save(p, value): + p = Path(p) + p.parent.mkdir(parents=True, exist_ok=True) + with p.open("x", encoding="utf-8") as f: + json.dump(value, f, ensure_ascii=False, indent=2, allow_nan=False) + + +def validate_selection(ids, reserve, expected=200): + if ( + len(ids) != expected + or len(set(ids)) != expected + or len(set(reserve)) != len(reserve) + or set(ids).intersection(reserve) + or any(not isinstance(x, str) or not x for x in ids + reserve) + ): + raise ValueError("frozen unique selection or reserve boundary differs") def reject_label_keys(value): - if isinstance(value,dict): - if set(value).intersection({'gold','classification','grading','correct_answer','expected_label','evaluation_label'}): - raise ValueError('label-bearing input is forbidden') - for v in value.values():reject_label_keys(v) - elif isinstance(value,list): - for v in value:reject_label_keys(v) - - -def extract_example(trace,source_id,trace_sha): - if trace.get('terminated') is not True or len(trace.get('planner_attempts',[]))!=1 or len(trace.get('programs',[]))!=1: - raise ValueError('this frozen dataset contains only complete initial single-Program trajectories') - a=trace['planner_attempts'][0];messages=a.get('messages');response=a.get('raw_response') - if (not isinstance(messages,list) or len(messages)!=2 or [m.get('role') for m in messages]!=['system','user'] - or any(not isinstance(m.get('content'),str) or not m['content'] for m in messages) - or not messages[0]['content'].startswith('You are the Global Program Planner')): - raise ValueError('Planner inputs are not the original two-message initial interface') - payload=json.loads(messages[1]['content']);reject_label_keys(payload) - library=payload.get('skill_library',[]);names=[s['name'] for s in library] - if len(names)!=66 or len(set(names))!=66:raise ValueError('complete F66 contracts required') + if isinstance(value, dict): + if set(value).intersection( + { + "gold", + "classification", + "grading", + "correct_answer", + "expected_label", + "evaluation_label", + } + ): + raise ValueError("label-bearing input is forbidden") + for v in value.values(): + reject_label_keys(v) + elif isinstance(value, list): + for v in value: + reject_label_keys(v) + + +def extract_example(trace, source_id, trace_sha): + if ( + trace.get("terminated") is not True + or len(trace.get("planner_attempts", [])) != 1 + or len(trace.get("programs", [])) != 1 + ): + raise ValueError( + "this frozen dataset contains only complete initial single-Program trajectories" + ) + a = trace["planner_attempts"][0] + messages = a.get("messages") + response = a.get("raw_response") + if ( + not isinstance(messages, list) + or len(messages) != 2 + or [m.get("role") for m in messages] != ["system", "user"] + or any(not isinstance(m.get("content"), str) or not m["content"] for m in messages) + or not messages[0]["content"].startswith("You are the Global Program Planner") + ): + raise ValueError("Planner inputs are not the original two-message initial interface") + payload = json.loads(messages[1]["content"]) + reject_label_keys(payload) + library = payload.get("skill_library", []) + names = [s["name"] for s in library] + if len(names) != 66 or len(set(names)) != 66: + raise ValueError("complete F66 contracts required") # 监督目标直接取原始响应,并与实际执行计划核对,避免重新拼装答案改变训练目标。 - plan=json.loads(response) - if (set(plan)!= {'program'} or not isinstance(plan['program'],list) or not plan['program'] - or any(set(s)!= {'tool','arguments'} or s['tool'] not in names or not isinstance(s['arguments'],dict) for s in plan['program']) - or plan!=trace['programs'][0]['plan'] or not trace['programs'][0].get('terminated')): - raise ValueError('raw response differs from actual executed Program') - return {'source_id':source_id,'kind':'initial','messages':messages,'response':response,'trace_sha256':trace_sha} + plan = json.loads(response) + if ( + set(plan) != {"program"} + or not isinstance(plan["program"], list) + or not plan["program"] + or any( + set(s) != {"tool", "arguments"} + or s["tool"] not in names + or not isinstance(s["arguments"], dict) + for s in plan["program"] + ) + or plan != trace["programs"][0]["plan"] + or not trace["programs"][0].get("terminated") + ): + raise ValueError("raw response differs from actual executed Program") + return { + "source_id": source_id, + "kind": "initial", + "messages": messages, + "response": response, + "trace_sha256": trace_sha, + } def main(): - final=TEACHER/'final-review-01';selection=read(final/'final-set.json');reviews=read(final/'manual-final-review.json') - validate_selection(selection['training_ids'],selection['reserve_ids']) - if not selection['final_review_complete'] or not selection['delivery_ready'] or selection['hard_evidence_faults']: - raise ValueError('final teacher evidence not ready') - if sha(final/'teacher-200-delivery-01.tar.gz')!=DELIVERY_SHA:raise ValueError('teacher delivery identity changed') - all_rows={r['id']:r for r in read(TEACHER/'combined-admission.json')['rows']};rows=[];provenance=[];classes=Counter() - for source_id in selection['training_ids']: - r=all_rows[source_id];review=reviews[source_id];p=Path(r['trace_path']) - if not r['accepted'] or review['reviewed'] is not True or review['serious_issue'] or sha(p)!=r['trace_sha256'] or review['trace_sha256']!=r['trace_sha256']: - raise ValueError('selected source review/trace changed') - t=read(p);rows.append(extract_example(t,source_id,r['trace_sha256']));classes[t['final_result']['category']]+=1 - provenance.append({'source_id':source_id,'trace_path':str(p),'trace_sha256':r['trace_sha256'],'source_batch':r['source_batch'], - 'warnings':r['warnings'],'messages_sha256':hashlib.sha256(json.dumps(rows[-1]['messages'],ensure_ascii=False,sort_keys=True).encode()).hexdigest(), - 'response_sha256':hashlib.sha256(rows[-1]['response'].encode()).hexdigest()}) - folder=ROOT/'data';folder.mkdir(exist_ok=False);data=folder/'planner200.jsonl' - with data.open('x',encoding='utf-8',newline='\n') as f: - for row in rows:f.write(json.dumps(row,ensure_ascii=False,separators=(',',':'))+'\n') - save(ROOT/'reviews/dataset-provenance-01.json',{'rows':provenance,'teacher_delivery_sha256':DELIVERY_SHA, - 'selection_sha256':sha(final/'final-set.json'),'review_sha256':sha(final/'manual-final-review.json')}) - report={'rows':len(rows),'unique_sources':len({r['source_id'] for r in rows}),'reserve_sources_not_used':len(selection['reserve_ids']), - 'data_sha256':sha(data),'data_bytes':data.stat().st_size,'kinds':{'initial':len(rows),'recovery':0},'category_counts_local_only':dict(classes), - 'source_labels_in_model_input':False,'future_observations_in_initial_input':False,'raw_reasoning_supervised':False, - 'skill_responses_supervised':False,'source_equally_weighted':True,'student_training_started':False} - save(ROOT/'reviews/dataset-export-01.json',report);print(json.dumps(report,ensure_ascii=False)) - - -if __name__=='__main__':main() + final = TEACHER / "final-review-01" + selection = read(final / "final-set.json") + reviews = read(final / "manual-final-review.json") + validate_selection(selection["training_ids"], selection["reserve_ids"]) + if ( + not selection["final_review_complete"] + or not selection["delivery_ready"] + or selection["hard_evidence_faults"] + ): + raise ValueError("final teacher evidence not ready") + if sha(final / "teacher-200-delivery-01.tar.gz") != DELIVERY_SHA: + raise ValueError("teacher delivery identity changed") + all_rows = {r["id"]: r for r in read(TEACHER / "combined-admission.json")["rows"]} + rows = [] + provenance = [] + classes = Counter() + for source_id in selection["training_ids"]: + r = all_rows[source_id] + review = reviews[source_id] + p = Path(r["trace_path"]) + if ( + not r["accepted"] + or review["reviewed"] is not True + or review["serious_issue"] + or sha(p) != r["trace_sha256"] + or review["trace_sha256"] != r["trace_sha256"] + ): + raise ValueError("selected source review/trace changed") + t = read(p) + rows.append(extract_example(t, source_id, r["trace_sha256"])) + classes[t["final_result"]["category"]] += 1 + provenance.append( + { + "source_id": source_id, + "trace_path": str(p), + "trace_sha256": r["trace_sha256"], + "source_batch": r["source_batch"], + "warnings": r["warnings"], + "messages_sha256": hashlib.sha256( + json.dumps(rows[-1]["messages"], ensure_ascii=False, sort_keys=True).encode() + ).hexdigest(), + "response_sha256": hashlib.sha256(rows[-1]["response"].encode()).hexdigest(), + } + ) + folder = ROOT / "data" + folder.mkdir(exist_ok=False) + data = folder / "planner200.jsonl" + with data.open("x", encoding="utf-8", newline="\n") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") + save( + ROOT / "reviews/dataset-provenance-01.json", + { + "rows": provenance, + "teacher_delivery_sha256": DELIVERY_SHA, + "selection_sha256": sha(final / "final-set.json"), + "review_sha256": sha(final / "manual-final-review.json"), + }, + ) + report = { + "rows": len(rows), + "unique_sources": len({r["source_id"] for r in rows}), + "reserve_sources_not_used": len(selection["reserve_ids"]), + "data_sha256": sha(data), + "data_bytes": data.stat().st_size, + "kinds": {"initial": len(rows), "recovery": 0}, + "category_counts_local_only": dict(classes), + "source_labels_in_model_input": False, + "future_observations_in_initial_input": False, + "raw_reasoning_supervised": False, + "skill_responses_supervised": False, + "source_equally_weighted": True, + "student_training_started": False, + } + save(ROOT / "reviews/dataset-export-01.json", report) + print(json.dumps(report, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/research/finance_program_v1/sft/pipeline.py b/research/finance_program_v1/sft/pipeline.py index ce2f8bd..3cd7fcd 100644 --- a/research/finance_program_v1/sft/pipeline.py +++ b/research/finance_program_v1/sft/pipeline.py @@ -1,4 +1,5 @@ """One detached, mutually exclusive trial -> fresh formal training pipeline.""" + # 持有 GPU 互斥锁依次启动 trial 和 formal;正式训练须通过试跑证据门禁,每阶段独立记录退出状态。 import argparse import datetime @@ -17,107 +18,161 @@ def now(): def claim_launch(root, signature): - put(Path(root) / 'runs/launch-claim.json', {'manifest_sha256': signature, 'claimed_at': now()}) + put(Path(root) / "runs/launch-claim.json", {"manifest_sha256": signature, "claimed_at": now()}) def formal_gate(trial_exit, proof, config): - if trial_exit.get('exit_code') != 0 or not isinstance(proof, dict): - raise ValueError('actual successful trial exit and proof required') + if trial_exit.get("exit_code") != 0 or not isinstance(proof, dict): + raise ValueError("actual successful trial exit and proof required") validate_trial(proof, config) def gpu_snapshot(expected): - values = subprocess.check_output(['nvidia-smi', '--query-gpu=index,uuid,memory.free', - '--format=csv,noheader,nounits'], text=True) + values = subprocess.check_output( + ["nvidia-smi", "--query-gpu=index,uuid,memory.free", "--format=csv,noheader,nounits"], + text=True, + ) observed, free = {}, {} for line in values.strip().splitlines(): - idx, uuid, memory = [x.strip() for x in line.split(',')] + idx, uuid, memory = [x.strip() for x in line.split(",")] if idx in expected: observed[idx], free[idx] = uuid, int(memory) - busy_text = subprocess.check_output(['nvidia-smi', '--query-compute-apps=gpu_uuid,pid', - '--format=csv,noheader,nounits'], text=True) - busy = [line.split(',')[0].strip() for line in busy_text.splitlines() if line.strip()] + busy_text = subprocess.check_output( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, + ) + busy = [line.split(",")[0].strip() for line in busy_text.splitlines() if line.strip()] validate_gpu_snapshot(expected, observed, free, busy) - return {'observed': observed, 'free_mib': free, 'busy_gpu_uuids': busy, 'checked_at': now()} + return {"observed": observed, "free_mib": free, "busy_gpu_uuids": busy, "checked_at": now()} def run(root): import fcntl + m = verify_manifest(root) - c = m['config'] + c = m["config"] handles = [] rc = 1 try: - for idx in sorted(c['gpu_uuids']): - f = open(c['lock_dir'] + '/gpu' + idx + '-experiment.lock', 'a+') + for idx in sorted(c["gpu_uuids"]): + f = open(c["lock_dir"] + "/gpu" + idx + "-experiment.lock", "a+") handles.append(f) fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) - put(root / 'runs/resource-gate.json', gpu_snapshot(c['gpu_uuids'])) - if subprocess.check_output(['nvidia-smi', '--query-gpu=driver_version', '--format=csv,noheader'], text=True).strip() == '': - raise RuntimeError('GPU driver query failed') + put(root / "runs/resource-gate.json", gpu_snapshot(c["gpu_uuids"])) + if ( + subprocess.check_output( + ["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"], text=True + ).strip() + == "" + ): + raise RuntimeError("GPU driver query failed") from shutil import disk_usage - if disk_usage(root).free < 20 * 1024 ** 3: - raise RuntimeError('less than 20 GiB disk available') - identity = read(root / 'model-identity.json') - for item in identity['files']: - if digest(Path(c['model']) / item['path']) != item['sha256']: - raise ValueError('base model identity changed: ' + item['path']) - put(root / 'runs/base-identity-proof.json', {'all_files_verified': True, - 'revision': identity['revision'], 'identity_sha256': digest(root / 'model-identity.json'), 'time': now()}) + + if disk_usage(root).free < 20 * 1024**3: + raise RuntimeError("less than 20 GiB disk available") + identity = read(root / "model-identity.json") + for item in identity["files"]: + if digest(Path(c["model"]) / item["path"]) != item["sha256"]: + raise ValueError("base model identity changed: " + item["path"]) + put( + root / "runs/base-identity-proof.json", + { + "all_files_verified": True, + "revision": identity["revision"], + "identity_sha256": digest(root / "model-identity.json"), + "time": now(), + }, + ) env = dict(os.environ) - env.update(CUDA_VISIBLE_DEVICES=','.join(sorted(c['gpu_uuids'])), PYTHONUTF8='1', - PYTHONDONTWRITEBYTECODE='1', TOKENIZERS_PARALLELISM='false', - PYTHONPATH=c['deps'], OMP_NUM_THREADS='8', MKL_NUM_THREADS='8', - HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1') + env.update( + CUDA_VISIBLE_DEVICES=",".join(sorted(c["gpu_uuids"])), + PYTHONUTF8="1", + PYTHONDONTWRITEBYTECODE="1", + TOKENIZERS_PARALLELISM="false", + PYTHONPATH=c["deps"], + OMP_NUM_THREADS="8", + MKL_NUM_THREADS="8", + HF_HUB_OFFLINE="1", + TRANSFORMERS_OFFLINE="1", + ) # 每阶段启动独立训练进程,formal 重新加载基座,不继承 trial 的权重或优化器。 - for stage in ('trial', 'formal'): - if stage == 'formal': - formal_gate(read(root / 'runs/trial.exit.json'), read(root / 'trial/proof.json'), c) + for stage in ("trial", "formal"): + if stage == "formal": + formal_gate(read(root / "runs/trial.exit.json"), read(root / "trial/proof.json"), c) started = now() - with (root / 'runs' / (stage + '.log')).open('xb') as log: - worker = subprocess.Popen([c['python'], '-u', '-B', str(root / 'train_student.py'), '--mode', stage], - cwd=root, env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) - put(root / 'runs' / (stage + '.pid.json'), {'pid': worker.pid, 'stage': stage, 'started_at': started}) + with (root / "runs" / (stage + ".log")).open("xb") as log: + worker = subprocess.Popen( + [c["python"], "-u", "-B", str(root / "train_student.py"), "--mode", stage], + cwd=root, + env=env, + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + ) + put( + root / "runs" / (stage + ".pid.json"), + {"pid": worker.pid, "stage": stage, "started_at": started}, + ) code = worker.wait() - put(root / 'runs' / (stage + '.exit.json'), {'exit_code': code, 'pid': worker.pid, - 'started_at': started, 'ended_at': now()}) + put( + root / "runs" / (stage + ".exit.json"), + {"exit_code": code, "pid": worker.pid, "started_at": started, "ended_at": now()}, + ) if code: - raise RuntimeError(stage + ' exited with code ' + str(code)) - complete = read(root / 'formal/completion.json') - if complete['global_step'] != 13 or complete['sources'] != 200 or complete['epoch'] != 1.0: - raise RuntimeError('formal training incomplete') + raise RuntimeError(stage + " exited with code " + str(code)) + complete = read(root / "formal/completion.json") + if complete["global_step"] != 13 or complete["sources"] != 200 or complete["epoch"] != 1.0: + raise RuntimeError("formal training incomplete") rc = 0 except Exception as exc: traceback.print_exc() - put(root / 'runs/failure.json', {'type': type(exc).__name__, 'message': str(exc), 'time': now()}) + put( + root / "runs/failure.json", + {"type": type(exc).__name__, "message": str(exc), "time": now()}, + ) finally: for f in reversed(handles): f.close() - put(root / 'runs/pipeline.exit.json', {'exit_code': rc, 'ended_at': now(), 'pid': os.getpid()}) + put(root / "runs/pipeline.exit.json", {"exit_code": rc, "ended_at": now(), "pid": os.getpid()}) # Stage writers have exited; archive regardless of success, without restarting training. - archive = subprocess.run([c['python'], '-B', str(root / 'archive_run.py')], cwd=root, - stdin=subprocess.DEVNULL, check=False) - put(root / 'runs/archive.exit.json', {'exit_code': archive.returncode, 'ended_at': now()}) + archive = subprocess.run( + [c["python"], "-B", str(root / "archive_run.py")], + cwd=root, + stdin=subprocess.DEVNULL, + check=False, + ) + put(root / "runs/archive.exit.json", {"exit_code": archive.returncode, "ended_at": now()}) return rc if rc else archive.returncode def main(): parser = argparse.ArgumentParser() - parser.add_argument('mode', choices=('launch', 'run')) + parser.add_argument("mode", choices=("launch", "run")) a = parser.parse_args() root = Path(__file__).resolve().parent - if a.mode == 'run': + if a.mode == "run": raise SystemExit(run(root)) m = verify_manifest(root) - claim_launch(root, digest(root / 'manifest.json')) - with (root / 'runs/pipeline.log').open('xb') as log: - worker = subprocess.Popen([m['config']['python'], '-u', '-B', str(root / 'pipeline.py'), 'run'], - cwd=root, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True) - receipt = {'pid': worker.pid, 'manifest_sha256': digest(root / 'manifest.json'), 'started_at': now(), - 'detached': True, 'no_automatic_restart': True} - put(root / 'runs/worker.json', receipt) - print(__import__('json').dumps(receipt), flush=True) + claim_launch(root, digest(root / "manifest.json")) + with (root / "runs/pipeline.log").open("xb") as log: + worker = subprocess.Popen( + [m["config"]["python"], "-u", "-B", str(root / "pipeline.py"), "run"], + cwd=root, + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + receipt = { + "pid": worker.pid, + "manifest_sha256": digest(root / "manifest.json"), + "started_at": now(), + "detached": True, + "no_automatic_restart": True, + } + put(root / "runs/worker.json", receipt) + print(__import__("json").dumps(receipt), flush=True) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/research/finance_program_v1/sft/runtime_io.py b/research/finance_program_v1/sft/runtime_io.py index b1de43a..40fccbb 100644 --- a/research/finance_program_v1/sft/runtime_io.py +++ b/research/finance_program_v1/sft/runtime_io.py @@ -1,4 +1,5 @@ """Exclusive evidence writes and frozen-file identity checks; no credentials.""" + import hashlib import json from pathlib import Path @@ -6,31 +7,31 @@ def digest(path): h = hashlib.sha256() - with Path(path).open('rb') as f: - for chunk in iter(lambda: f.read(1024 * 1024), b''): + with Path(path).open("rb") as f: + for chunk in iter(lambda: f.read(1024 * 1024), b""): h.update(chunk) return h.hexdigest() def read(path): - return json.loads(Path(path).read_text(encoding='utf-8')) + return json.loads(Path(path).read_text(encoding="utf-8")) def put(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) - with path.open('x', encoding='utf-8', newline='\n') as f: + with path.open("x", encoding="utf-8", newline="\n") as f: json.dump(value, f, ensure_ascii=False, indent=2, allow_nan=False) - f.write('\n') + f.write("\n") def verify_manifest(root): root = Path(root) - m = read(root / 'manifest.json') - for item in m['files']: - p = root / item['path'] - if not p.is_relative_to(root) or digest(p) != item['sha256']: - raise ValueError('frozen file SHA mismatch: ' + item['path']) - if digest(root / 'data/planner200.jsonl') != m['config']['data_sha256']: - raise ValueError('data identity mismatch') + m = read(root / "manifest.json") + for item in m["files"]: + p = root / item["path"] + if not p.is_relative_to(root) or digest(p) != item["sha256"]: + raise ValueError("frozen file SHA mismatch: " + item["path"]) + if digest(root / "data/planner200.jsonl") != m["config"]["data_sha256"]: + raise ValueError("data identity mismatch") return m diff --git a/research/finance_program_v1/sft/token_audit.py b/research/finance_program_v1/sft/token_audit.py index a3c5061..3be4927 100644 --- a/research/finance_program_v1/sft/token_audit.py +++ b/research/finance_program_v1/sft/token_audit.py @@ -1,3 +1,4 @@ +# prompt必须是完整token前缀;labels仅覆盖原Program+EOS,超长拒绝而非截断。 """Full, untruncated student chat encoding and assistant-only suffix audit.""" # 完整保留规划上下文,只对响应及 EOS 设置监督;分词边界不一致或超长时直接拒绝样本。 import argparse @@ -7,41 +8,94 @@ from pathlib import Path -def encode_training_row(row,tokenizer,max_length): - prompt=tokenizer.apply_chat_template(row['messages'],tokenize=False,add_generation_prompt=True,enable_thinking=False) - if not tokenizer.eos_token:raise ValueError('tokenizer requires EOS') - prefix=tokenizer(prompt,add_special_tokens=False)['input_ids'] - full=tokenizer(prompt+row['response']+tokenizer.eos_token,add_special_tokens=False)['input_ids'] - if full[:len(prefix)]!=prefix:raise ValueError('prompt is not an exact token prefix') - if len(full)>max_length:raise ValueError('context too long; no truncation permitted') - if len(full)<=len(prefix):raise ValueError('empty assistant suffix') - return {'input_ids':full,'attention_mask':[1]*len(full),'labels':[-100]*len(prefix)+full[len(prefix):]} +def encode_training_row(row, tokenizer, max_length): + prompt = tokenizer.apply_chat_template( + row["messages"], tokenize=False, add_generation_prompt=True, enable_thinking=False + ) + if not tokenizer.eos_token: + raise ValueError("tokenizer requires EOS") + prefix = tokenizer(prompt, add_special_tokens=False)["input_ids"] + full = tokenizer(prompt + row["response"] + tokenizer.eos_token, add_special_tokens=False)[ + "input_ids" + ] + if full[: len(prefix)] != prefix: + raise ValueError("prompt is not an exact token prefix") + if len(full) > max_length: + raise ValueError("context too long; no truncation permitted") + if len(full) <= len(prefix): + raise ValueError("empty assistant suffix") + return { + "input_ids": full, + "attention_mask": [1] * len(full), + "labels": [-100] * len(prefix) + full[len(prefix) :], + } def main(): - p=argparse.ArgumentParser();p.add_argument('--data',type=Path,required=True);p.add_argument('--model',type=Path,required=True) - p.add_argument('--output',type=Path,required=True);p.add_argument('--limit',type=int,default=262144);a=p.parse_args() + p = argparse.ArgumentParser() + p.add_argument("--data", type=Path, required=True) + p.add_argument("--model", type=Path, required=True) + p.add_argument("--output", type=Path, required=True) + p.add_argument("--limit", type=int, default=262144) + a = p.parse_args() from transformers import AutoTokenizer - tok=AutoTokenizer.from_pretrained(a.model,local_files_only=True) - if not tok.is_fast:raise ValueError('fast tokenizer required') - rows=[json.loads(x) for x in a.data.read_text(encoding='utf-8').splitlines() if x.strip()] - if len(rows)!=200 or len({r['source_id'] for r in rows})!=200:raise ValueError('exactly 200 sources required') - stats=[] + + tok = AutoTokenizer.from_pretrained(a.model, local_files_only=True) + if not tok.is_fast: + raise ValueError("fast tokenizer required") + rows = [json.loads(x) for x in a.data.read_text(encoding="utf-8").splitlines() if x.strip()] + if len(rows) != 200 or len({r["source_id"] for r in rows}) != 200: + raise ValueError("exactly 200 sources required") + stats = [] for row in rows: - enc=encode_training_row(row,tok,a.limit);count=sum(x!=-100 for x in enc['labels']);boundary=len(enc['labels'])-count - assert all(x==-100 for x in enc['labels'][:boundary]) and enc['labels'][boundary:]==enc['input_ids'][boundary:] - assert tok.decode(enc['input_ids'][boundary:],skip_special_tokens=False)==row['response']+tok.eos_token - assert enc['input_ids'][-1]==tok.eos_token_id - stats.append({'source_id':row['source_id'],'length':len(enc['input_ids']),'prompt_tokens':boundary,'supervised_tokens':count}) - lengths=sorted(x['length'] for x in stats);report={'rows':len(rows),'data_sha256':hashlib.sha256(a.data.read_bytes()).hexdigest(), - 'min_length':min(lengths),'max_length':max(lengths),'p95_length':lengths[int(.95*(len(lengths)-1))], - 'max_length_limit':math.ceil(max(lengths)/1024)*1024,'total_tokens':sum(lengths), - 'min_supervised_tokens':min(x['supervised_tokens'] for x in stats),'max_supervised_tokens':max(x['supervised_tokens'] for x in stats), - 'longest_source_id':max(stats,key=lambda x:x['length'])['source_id'],'truncated_rows':0,'all_prompt_positions_masked':True, - 'all_assistant_targets_exact_with_eos':True,'enable_thinking':False,'model_tokenizer_sha256':hashlib.sha256((a.model/'tokenizer.json').read_bytes()).hexdigest(), - 'tokenizer_config_sha256':hashlib.sha256((a.model/'tokenizer_config.json').read_bytes()).hexdigest(),'per_source':stats} - with a.output.open('x',encoding='utf-8') as f:json.dump(report,f,ensure_ascii=False,indent=2) - print(json.dumps({k:v for k,v in report.items() if k!='per_source'},ensure_ascii=False)) + enc = encode_training_row(row, tok, a.limit) + count = sum(x != -100 for x in enc["labels"]) + boundary = len(enc["labels"]) - count + assert ( + all(x == -100 for x in enc["labels"][:boundary]) + and enc["labels"][boundary:] == enc["input_ids"][boundary:] + ) + assert ( + tok.decode(enc["input_ids"][boundary:], skip_special_tokens=False) + == row["response"] + tok.eos_token + ) + assert enc["input_ids"][-1] == tok.eos_token_id + stats.append( + { + "source_id": row["source_id"], + "length": len(enc["input_ids"]), + "prompt_tokens": boundary, + "supervised_tokens": count, + } + ) + lengths = sorted(x["length"] for x in stats) + report = { + "rows": len(rows), + "data_sha256": hashlib.sha256(a.data.read_bytes()).hexdigest(), + "min_length": min(lengths), + "max_length": max(lengths), + "p95_length": lengths[int(0.95 * (len(lengths) - 1))], + "max_length_limit": math.ceil(max(lengths) / 1024) * 1024, + "total_tokens": sum(lengths), + "min_supervised_tokens": min(x["supervised_tokens"] for x in stats), + "max_supervised_tokens": max(x["supervised_tokens"] for x in stats), + "longest_source_id": max(stats, key=lambda x: x["length"])["source_id"], + "truncated_rows": 0, + "all_prompt_positions_masked": True, + "all_assistant_targets_exact_with_eos": True, + "enable_thinking": False, + "model_tokenizer_sha256": hashlib.sha256( + (a.model / "tokenizer.json").read_bytes() + ).hexdigest(), + "tokenizer_config_sha256": hashlib.sha256( + (a.model / "tokenizer_config.json").read_bytes() + ).hexdigest(), + "per_source": stats, + } + with a.output.open("x", encoding="utf-8") as f: + json.dump(report, f, ensure_ascii=False, indent=2) + print(json.dumps({k: v for k, v in report.items() if k != "per_source"}, ensure_ascii=False)) -if __name__=='__main__':main() +if __name__ == "__main__": + main() diff --git a/research/finance_program_v1/sft/train_student.py b/research/finance_program_v1/sft/train_student.py index 35ef5d2..97ae89a 100644 --- a/research/finance_program_v1/sft/train_student.py +++ b/research/finance_program_v1/sft/train_student.py @@ -1,3 +1,5 @@ +# 只更新语言LoRA;trial为最长样本工程门,formal重新载入基座。 +# completion-only loss不删除prompt上下文;200来源与最后不足累积批次均核账。 """Fresh-base Planner LoRA: actual longest-source trial, then one full epoch.""" # 最长样本试跑验证真实前反向与更新;正式阶段重新加载基座,仅训练语言层 LoRA 并核对整轮来源。 import argparse @@ -13,121 +15,186 @@ def main(): parser = argparse.ArgumentParser() - parser.add_argument('--mode', choices=('trial', 'formal'), required=True) + parser.add_argument("--mode", choices=("trial", "formal"), required=True) args = parser.parse_args() root = Path(__file__).resolve().parent manifest = verify_manifest(root) - c = manifest['config'] + c = manifest["config"] import torch import peft import transformers from peft import LoraConfig, get_peft_model - from transformers import AutoModelForImageTextToText, AutoTokenizer, Trainer, TrainingArguments, TrainerCallback, set_seed + from transformers import ( + AutoModelForImageTextToText, + AutoTokenizer, + Trainer, + TrainingArguments, + TrainerCallback, + set_seed, + ) from completion_loss import completion_cross_entropy - if (not torch.cuda.is_available() or torch.cuda.device_count() != 3 - or not torch.cuda.is_bf16_supported()): - raise RuntimeError('three BF16 CUDA GPUs required') + + if ( + not torch.cuda.is_available() + or torch.cuda.device_count() != 3 + or not torch.cuda.is_bf16_supported() + ): + raise RuntimeError("three BF16 CUDA GPUs required") output = root / args.mode output.mkdir(exist_ok=False) started = time.time() - if args.mode == 'formal': - trial = read(root / 'trial/proof.json') + if args.mode == "formal": + trial = read(root / "trial/proof.json") validate_trial(trial, c) - if trial['manifest_sha256'] != digest(root / 'manifest.json'): - raise ValueError('trial belongs to a different frozen run') - set_seed(c['seed']) - tok = AutoTokenizer.from_pretrained(c['model'], local_files_only=True) - rows = [json.loads(line) for line in (root / 'data/planner200.jsonl').read_text(encoding='utf-8').splitlines() if line.strip()] - if len(rows) != 200 or len({r['source_id'] for r in rows}) != 200: - raise ValueError('exact frozen 200 unique sources required') - enc = [encode_training_row(r, tok, c['max_length_limit']) for r in rows] - audit = read(root / 'reviews/token-audit-01.json') - for row, item, stat in zip(rows, enc, audit['per_source']): - count = sum(x != -100 for x in item['labels']) - if (stat['source_id'] != row['source_id'] or stat['length'] != len(item['input_ids']) - or stat['supervised_tokens'] != count - or tok.decode(item['input_ids'][-count:], skip_special_tokens=False) != row['response'] + tok.eos_token): - raise ValueError('full token/mask audit changed') - if max(len(x['input_ids']) for x in enc) != c['max_length']: - raise ValueError('actual longest length changed') - model = AutoModelForImageTextToText.from_pretrained(c['model'], local_files_only=True, - dtype=torch.bfloat16, attn_implementation='sdpa', device_map='balanced', - max_memory={0: '27GiB', 1: '27GiB', 2: '27GiB'}) + if trial["manifest_sha256"] != digest(root / "manifest.json"): + raise ValueError("trial belongs to a different frozen run") + set_seed(c["seed"]) + tok = AutoTokenizer.from_pretrained(c["model"], local_files_only=True) + rows = [ + json.loads(line) + for line in (root / "data/planner200.jsonl").read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != 200 or len({r["source_id"] for r in rows}) != 200: + raise ValueError("exact frozen 200 unique sources required") + enc = [encode_training_row(r, tok, c["max_length_limit"]) for r in rows] + audit = read(root / "reviews/token-audit-01.json") + for row, item, stat in zip(rows, enc, audit["per_source"]): + count = sum(x != -100 for x in item["labels"]) + if ( + stat["source_id"] != row["source_id"] + or stat["length"] != len(item["input_ids"]) + or stat["supervised_tokens"] != count + or tok.decode(item["input_ids"][-count:], skip_special_tokens=False) + != row["response"] + tok.eos_token + ): + raise ValueError("full token/mask audit changed") + if max(len(x["input_ids"]) for x in enc) != c["max_length"]: + raise ValueError("actual longest length changed") + model = AutoModelForImageTextToText.from_pretrained( + c["model"], + local_files_only=True, + dtype=torch.bfloat16, + attn_implementation="sdpa", + device_map="balanced", + max_memory={0: "27GiB", 1: "27GiB", 2: "27GiB"}, + ) placements = {str(d) for d in model.hf_device_map.values()} - if any(not placements.intersection({str(i), 'cuda:' + str(i)}) for i in range(3)): - raise RuntimeError('base must be sharded over all three GPUs') + if any(not placements.intersection({str(i), "cuda:" + str(i)}) for i in range(3)): + raise RuntimeError("base must be sharded over all three GPUs") model.config.use_cache = False - targets = [name for name, layer in model.named_modules() - if name.startswith('model.language_model.layers.') - and name.endswith(('.q_proj', '.v_proj', '.in_proj_qkv')) - and isinstance(layer, torch.nn.Linear)] + targets = [ + name + for name, layer in model.named_modules() + if name.startswith("model.language_model.layers.") + and name.endswith((".q_proj", ".v_proj", ".in_proj_qkv")) + and isinstance(layer, torch.nn.Linear) + ] if len(targets) != 40: - raise ValueError('expected 40 language LoRA targets') - model = get_peft_model(model, LoraConfig(r=8, lora_alpha=16, lora_dropout=.05, - target_modules=targets, bias='none', task_type='CAUSAL_LM')) + raise ValueError("expected 40 language LoRA targets") + model = get_peft_model( + model, + LoraConfig( + r=8, + lora_alpha=16, + lora_dropout=0.05, + target_modules=targets, + bias="none", + task_type="CAUSAL_LM", + ), + ) trainable = [(n, p) for n, p in model.named_parameters() if p.requires_grad] def frozen(): - return bool(trainable) and all('.lora_' in n and '.language_model.layers.' in n - for n, p in model.named_parameters() if p.requires_grad) + return bool(trainable) and all( + ".lora_" in n and ".language_model.layers." in n + for n, p in model.named_parameters() + if p.requires_grad + ) - if not frozen() or sorted({str(p.device) for _, p in trainable}) != ['cuda:0', 'cuda:1', 'cuda:2']: - raise ValueError('only distributed language LoRA may be trainable; base/vision frozen') - put(output / 'trainable-parameters.json', {'count': sum(p.numel() for _, p in trainable), - 'targets': targets, 'devices': sorted({str(p.device) for _, p in trainable}), 'base_and_vision_frozen': frozen()}) + if not frozen() or sorted({str(p.device) for _, p in trainable}) != [ + "cuda:0", + "cuda:1", + "cuda:2", + ]: + raise ValueError("only distributed language LoRA may be trainable; base/vision frozen") + put( + output / "trainable-parameters.json", + { + "count": sum(p.numel() for _, p in trainable), + "targets": targets, + "devices": sorted({str(p.device) for _, p in trainable}), + "base_and_vision_frozen": frozen(), + }, + ) for i in range(3): torch.cuda.reset_peak_memory_stats(i) def collate(items): if len(items) != 1: - raise ValueError('micro batch must be one') + raise ValueError("micro batch must be one") item = items[0] - values = {k: torch.tensor(item[k], dtype=torch.long).unsqueeze(0) - for k in ('input_ids', 'attention_mask', 'labels')} - if '_source_id' in item: - values['_source_id'] = item['_source_id'] + values = { + k: torch.tensor(item[k], dtype=torch.long).unsqueeze(0) + for k in ("input_ids", "attention_mask", "labels") + } + if "_source_id" in item: + values["_source_id"] = item["_source_id"] return values def loss_for(inputs): - labels = inputs.pop('labels') + labels = inputs.pop("labels") count = int(labels.ne(-100).sum()) # 保留完整上下文参与注意力;只缩减输出 logits,并将反向所需张量暂存 CPU。 with torch.autograd.graph.save_on_cpu(pin_memory=True): result = model(**inputs, logits_to_keep=count + 1) loss = completion_cross_entropy(result.logits, labels.to(result.logits.device)) if not torch.isfinite(loss.detach()).item(): - raise FloatingPointError('nonfinite training loss') + raise FloatingPointError("nonfinite training loss") return loss, result - if args.mode == 'trial': - idx = next(i for i, r in enumerate(rows) if r['source_id'] == c['longest_source_id']) - model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False}) + if args.mode == "trial": + idx = next(i for i, r in enumerate(rows) if r["source_id"] == c["longest_source_id"]) + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) model.enable_input_require_grads() model.train() device = model.get_input_embeddings().weight.device inputs = {k: v.to(device) for k, v in collate([enc[idx]]).items()} - optimizer = torch.optim.AdamW([p for _, p in trainable], lr=1e-4, weight_decay=.01) + optimizer = torch.optim.AdamW([p for _, p in trainable], lr=1e-4, weight_decay=0.01) loss, _ = loss_for(inputs) loss.backward() grads = [p.grad for _, p in trainable if p.grad is not None] finite = bool(grads) and all(torch.isfinite(g).all().item() for g in grads) if not finite: - raise FloatingPointError('trial gradients missing/nonfinite') - norm = torch.nn.utils.clip_grad_norm_([p for _, p in trainable], 1.) + raise FloatingPointError("trial gradients missing/nonfinite") + norm = torch.nn.utils.clip_grad_norm_([p for _, p in trainable], 1.0) optimizer.step() - updated = any('.lora_B.' in n and torch.count_nonzero(p.detach()).item() > 0 for n, p in trainable) - proof = {'data_sha256': c['data_sha256'], 'manifest_sha256': digest(root / 'manifest.json'), - 'source_id': rows[idx]['source_id'], 'tokens': len(enc[idx]['input_ids']), 'gpu_uuids': c['gpu_uuids'], - 'target_modules': len(targets), 'base_and_vision_frozen': frozen(), 'lora_updated': updated, - 'gradients_finite': finite, 'loss_finite': True, 'loss': float(loss.detach()), 'grad_norm': float(norm), - 'trainable_devices': sorted({str(p.device) for _, p in trainable}), - 'peak_memory_allocated': {str(i): torch.cuda.max_memory_allocated(i) for i in range(3)}, - 'wall_seconds': time.time() - started, 'formal_reloads_fresh_base': True} + updated = any( + ".lora_B." in n and torch.count_nonzero(p.detach()).item() > 0 for n, p in trainable + ) + proof = { + "data_sha256": c["data_sha256"], + "manifest_sha256": digest(root / "manifest.json"), + "source_id": rows[idx]["source_id"], + "tokens": len(enc[idx]["input_ids"]), + "gpu_uuids": c["gpu_uuids"], + "target_modules": len(targets), + "base_and_vision_frozen": frozen(), + "lora_updated": updated, + "gradients_finite": finite, + "loss_finite": True, + "loss": float(loss.detach()), + "grad_norm": float(norm), + "trainable_devices": sorted({str(p.device) for _, p in trainable}), + "peak_memory_allocated": {str(i): torch.cuda.max_memory_allocated(i) for i in range(3)}, + "wall_seconds": time.time() - started, + "formal_reloads_fresh_base": True, + } validate_trial(proof, c) if not all(torch.isfinite(p.detach()).all().item() for _, p in trainable): - raise FloatingPointError('trial updated parameters nonfinite') - put(output / 'proof.json', proof) - print(json.dumps({'stage': 'trial_complete', **proof}), flush=True) + raise FloatingPointError("trial updated parameters nonfinite") + put(output / "proof.json", proof) + print(json.dumps({"stage": "trial_complete", **proof}), flush=True) return consumed = [] @@ -137,58 +204,110 @@ class FiniteGradients(TrainerCallback): def on_pre_optimizer_step(self, args, state, control, **kwargs): grads = [p.grad for _, p in trainable if p.grad is not None] if not grads or not all(torch.isfinite(g).all().item() for g in grads): - raise FloatingPointError('formal gradients missing/nonfinite') + raise FloatingPointError("formal gradients missing/nonfinite") gradient_steps.append(state.global_step + 1) class PlannerTrainer(Trainer): def compute_loss(self, model, inputs, return_outputs=False, **kwargs): - source = inputs.pop('_source_id') + source = inputs.pop("_source_id") consumed.append(source) loss, result = loss_for(inputs) return (loss, result) if return_outputs else loss for row, item in zip(rows, enc): - item['_source_id'] = row['source_id'] - training_args = TrainingArguments(output_dir=str(output), num_train_epochs=1, - per_device_train_batch_size=1, gradient_accumulation_steps=16, - learning_rate=1e-4, lr_scheduler_type='cosine', warmup_steps=3, - weight_decay=.01, max_grad_norm=1., bf16=True, optim='adamw_torch', - gradient_checkpointing=True, gradient_checkpointing_kwargs={'use_reentrant': False}, - eval_strategy='no', save_strategy='steps', save_steps=8, logging_steps=1, - report_to='none', push_to_hub=False, remove_unused_columns=False, - dataloader_num_workers=0, dataloader_drop_last=False, seed=c['seed'], data_seed=c['seed'], disable_tqdm=True) - trainer = PlannerTrainer(model=model, args=training_args, train_dataset=enc, - data_collator=collate, processing_class=tok, callbacks=[FiniteGradients()]) + item["_source_id"] = row["source_id"] + training_args = TrainingArguments( + output_dir=str(output), + num_train_epochs=1, + per_device_train_batch_size=1, + gradient_accumulation_steps=16, + learning_rate=1e-4, + lr_scheduler_type="cosine", + warmup_steps=3, + weight_decay=0.01, + max_grad_norm=1.0, + bf16=True, + optim="adamw_torch", + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"use_reentrant": False}, + eval_strategy="no", + save_strategy="steps", + save_steps=8, + logging_steps=1, + report_to="none", + push_to_hub=False, + remove_unused_columns=False, + dataloader_num_workers=0, + dataloader_drop_last=False, + seed=c["seed"], + data_seed=c["seed"], + disable_tqdm=True, + ) + trainer = PlannerTrainer( + model=model, + args=training_args, + train_dataset=enc, + data_collator=collate, + processing_class=tok, + callbacks=[FiniteGradients()], + ) # Explicit example-average accumulation: custom loss does not consume num_items_in_batch. trainer.model_accepts_loss_kwargs = False result = trainer.train() # 来源计数与梯度更新数同时核对,包含最后不足一个累积批次的样本。 wanted = expected_steps(len(rows), 16) - if (trainer.state.global_step != wanted or trainer.state.epoch != 1.0 - or Counter(consumed) != Counter(r['source_id'] for r in rows) - or gradient_steps != list(range(1, wanted + 1))): - raise RuntimeError('incomplete epoch/source accounting/finite gradient updates') + if ( + trainer.state.global_step != wanted + or trainer.state.epoch != 1.0 + or Counter(consumed) != Counter(r["source_id"] for r in rows) + or gradient_steps != list(range(1, wanted + 1)) + ): + raise RuntimeError("incomplete epoch/source accounting/finite gradient updates") if not frozen() or not all(torch.isfinite(p.detach()).all().item() for _, p in trainable): - raise FloatingPointError('invalid final trainable parameters') - if not any('.lora_B.' in n and torch.count_nonzero(p.detach()).item() > 0 for n, p in trainable): - raise RuntimeError('no nonzero LoRA update') - final = output / 'final' + raise FloatingPointError("invalid final trainable parameters") + if not any( + ".lora_B." in n and torch.count_nonzero(p.detach()).item() > 0 for n, p in trainable + ): + raise RuntimeError("no nonzero LoRA update") + final = output / "final" trainer.save_model(str(final)) tok.save_pretrained(final) trainer.save_state() - if not (final / 'adapter_model.safetensors').is_file() or list(final.glob('model*.safetensors')): - raise RuntimeError('adapter-only checkpoint required') - put(output / 'source-accounting.json', {'consumed_ids': consumed, 'unique_sources': len(set(consumed)), - 'finite_gradient_steps': gradient_steps, 'last_partial_accumulation_retained': True}) - put(output / 'completion.json', {'global_step': trainer.state.global_step, 'epoch': trainer.state.epoch, - 'sources': len(consumed), 'metrics': result.metrics, 'base_and_vision_frozen': frozen(), - 'adapter_finite_and_updated': True, 'adapter_sha256': digest(final / 'adapter_model.safetensors'), - 'adapter_config_sha256': digest(final / 'adapter_config.json'), 'manifest_sha256': digest(root / 'manifest.json'), - 'trial_proof_sha256': digest(root / 'trial/proof.json'), 'torch': torch.__version__, - 'transformers': transformers.__version__, 'peft': peft.__version__, - 'wall_seconds': time.time() - started, 'evaluation_performed': False}) - print('STUDENT_PLANNER_SFT_COMPLETE', flush=True) + if not (final / "adapter_model.safetensors").is_file() or list( + final.glob("model*.safetensors") + ): + raise RuntimeError("adapter-only checkpoint required") + put( + output / "source-accounting.json", + { + "consumed_ids": consumed, + "unique_sources": len(set(consumed)), + "finite_gradient_steps": gradient_steps, + "last_partial_accumulation_retained": True, + }, + ) + put( + output / "completion.json", + { + "global_step": trainer.state.global_step, + "epoch": trainer.state.epoch, + "sources": len(consumed), + "metrics": result.metrics, + "base_and_vision_frozen": frozen(), + "adapter_finite_and_updated": True, + "adapter_sha256": digest(final / "adapter_model.safetensors"), + "adapter_config_sha256": digest(final / "adapter_config.json"), + "manifest_sha256": digest(root / "manifest.json"), + "trial_proof_sha256": digest(root / "trial/proof.json"), + "torch": torch.__version__, + "transformers": transformers.__version__, + "peft": peft.__version__, + "wall_seconds": time.time() - started, + "evaluation_performed": False, + }, + ) + print("STUDENT_PLANNER_SFT_COMPLETE", flush=True) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/research/finance_program_v1/sft/training_contract.py b/research/finance_program_v1/sft/training_contract.py index d80a391..c13dbcc 100644 --- a/research/finance_program_v1/sft/training_contract.py +++ b/research/finance_program_v1/sft/training_contract.py @@ -1,29 +1,34 @@ """Pure gates shared by the full-length trial, training, and monitoring.""" + # 试跑证明须与数据、最长来源和资源配置一致,防止用较短样本或其他运行的结果放行正式训练。 import math def expected_steps(rows, accumulation): if rows < 1 or accumulation < 1: - raise ValueError('positive source count and accumulation required') + raise ValueError("positive source count and accumulation required") return math.ceil(rows / accumulation) def validate_trial(proof, config): - if (proof.get('data_sha256') != config['data_sha256'] - or proof.get('tokens') != config['max_length'] - or proof.get('source_id') != config['longest_source_id'] - or proof.get('gpu_uuids') != config['gpu_uuids'] - or proof.get('target_modules') != 40 - or any(proof.get(k) is not True for k in ( - 'base_and_vision_frozen', 'lora_updated', 'gradients_finite', 'loss_finite'))): - raise ValueError('actual longest-source finite backward/update proof required') + if ( + proof.get("data_sha256") != config["data_sha256"] + or proof.get("tokens") != config["max_length"] + or proof.get("source_id") != config["longest_source_id"] + or proof.get("gpu_uuids") != config["gpu_uuids"] + or proof.get("target_modules") != 40 + or any( + proof.get(k) is not True + for k in ("base_and_vision_frozen", "lora_updated", "gradients_finite", "loss_finite") + ) + ): + raise ValueError("actual longest-source finite backward/update proof required") def validate_gpu_snapshot(expected, observed, free_mb, busy_uuids): - if set(expected) != {'0', '1', '2'} or observed != expected: - raise ValueError('three exact physical GPU identities required') + if set(expected) != {"0", "1", "2"} or observed != expected: + raise ValueError("three exact physical GPU identities required") if any(free_mb.get(k, 0) < 30000 for k in expected): - raise ValueError('less than 30000 MiB free on a requested GPU') + raise ValueError("less than 30000 MiB free on a requested GPU") if set(expected.values()).intersection(busy_uuids): - raise ValueError('requested GPU has another compute process; do not interfere') + raise ValueError("requested GPU has another compute process; do not interfere") diff --git a/research/finance_program_v1/teacher/budget_base.py b/research/finance_program_v1/teacher/budget_base.py index d693470..7884225 100644 --- a/research/finance_program_v1/teacher/budget_base.py +++ b/research/finance_program_v1/teacher/budget_base.py @@ -1,4 +1,5 @@ """Append-only cross-process campaign accounting; no secret or response bodies.""" + # 追加日志保存跨进程请求与用量账本;线程锁和文件锁共同保护申领、结算及停止状态。 from contextlib import contextmanager import json @@ -12,109 +13,178 @@ class PersistentBudget: def __init__(self, path, *, requests=1200, tokens=10000000, failures=8): - self.path = Path(path).resolve(); self.path.mkdir(parents=True, exist_ok=True) - self.limits = {'request_cap': requests, 'known_token_cap': tokens, 'failed_attempt_cap': failures} + self.path = Path(path).resolve() + self.path.mkdir(parents=True, exist_ok=True) + self.limits = { + "request_cap": requests, + "known_token_cap": tokens, + "failed_attempt_cap": failures, + } assert all(type(n) is int and n > 0 for n in self.limits.values()) - with _LOCKS_GUARD:self.lock = _LOCKS.setdefault(str(self.path), threading.RLock()) + with _LOCKS_GUARD: + self.lock = _LOCKS.setdefault(str(self.path), threading.RLock()) self.local = threading.local() @contextmanager def _locked(self): with self.lock: - lockpath = self.path / 'budget.lock' + lockpath = self.path / "budget.lock" try: - with lockpath.open('xb') as stream:stream.write(b'0') - except FileExistsError:pass - with lockpath.open('r+b') as stream: - if os.name == 'nt': + with lockpath.open("xb") as stream: + stream.write(b"0") + except FileExistsError: + pass + with lockpath.open("r+b") as stream: + if os.name == "nt": import msvcrt + msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1) else: import fcntl + fcntl.flock(stream.fileno(), fcntl.LOCK_EX) - try:yield + try: + yield finally: stream.seek(0) - if os.name == 'nt':msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) - else:fcntl.flock(stream.fileno(), fcntl.LOCK_UN) + if os.name == "nt": + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(stream.fileno(), fcntl.LOCK_UN) def _append(self, event): - with (self.path / 'events.jsonl').open('a', encoding='utf-8') as stream: - stream.write(json.dumps(event, sort_keys=True, separators=(',', ':')) + '\n') - stream.flush(); os.fsync(stream.fileno()) + with (self.path / "events.jsonl").open("a", encoding="utf-8") as stream: + stream.write(json.dumps(event, sort_keys=True, separators=(",", ":")) + "\n") + stream.flush() + os.fsync(stream.fileno()) def _state(self): - journal = self.path / 'events.jsonl' - if not journal.exists():self._append({'type': 'limits', **self.limits}) - events = [json.loads(s) for s in journal.read_text(encoding='utf-8').splitlines()] - assert events[0] == {'type': 'limits', **self.limits}, 'campaign limits changed' - claims = set(); done = set(); tokens = failures = unknown = 0; stopped = False + journal = self.path / "events.jsonl" + if not journal.exists(): + self._append({"type": "limits", **self.limits}) + events = [json.loads(s) for s in journal.read_text(encoding="utf-8").splitlines()] + assert events[0] == {"type": "limits", **self.limits}, "campaign limits changed" + claims = set() + done = set() + tokens = failures = unknown = 0 + stopped = False for event in events[1:]: - if event['type'] == 'claim': - assert event['id'] == len(claims) + 1; claims.add(event['id']) - elif event['type'] == 'result': - assert event['id'] in claims - done; done.add(event['id']) - tokens += event['known_total_tokens']; failures += not event['complete']; unknown += event['unknown_usage'] - elif event['type'] == 'stop':stopped = True - else:raise ValueError('unknown campaign event') - return {'requests': len(claims), 'known_total_tokens': tokens, 'failed_attempts': failures, - 'unknown_usage_attempts': unknown, 'inflight_requests': len(claims - done), - 'stopped': stopped or len(claims) >= self.limits['request_cap'] or tokens >= self.limits['known_token_cap'] or failures >= self.limits['failed_attempt_cap'], - **self.limits} + if event["type"] == "claim": + assert event["id"] == len(claims) + 1 + claims.add(event["id"]) + elif event["type"] == "result": + assert event["id"] in claims - done + done.add(event["id"]) + tokens += event["known_total_tokens"] + failures += not event["complete"] + unknown += event["unknown_usage"] + elif event["type"] == "stop": + stopped = True + else: + raise ValueError("unknown campaign event") + return { + "requests": len(claims), + "known_total_tokens": tokens, + "failed_attempts": failures, + "unknown_usage_attempts": unknown, + "inflight_requests": len(claims - done), + "stopped": stopped + or len(claims) >= self.limits["request_cap"] + or tokens >= self.limits["known_token_cap"] + or failures >= self.limits["failed_attempt_cap"], + **self.limits, + } def claim(self): with self._locked(): state = self._state() - if state['stopped']:raise RuntimeError('teacher safety budget halted') - assert getattr(self.local, 'pending', None) is None - self.local.pending = state['requests'] + 1 + if state["stopped"]: + raise RuntimeError("teacher safety budget halted") + assert getattr(self.local, "pending", None) is None + self.local.pending = state["requests"] + 1 # 请求发出前持久化占位;进程中断后该次申领仍保留,避免恢复运行时漏记。 - self._append({'type': 'claim', 'id': self.local.pending, 'pid': os.getpid()}) + self._append({"type": "claim", "id": self.local.pending, "pid": os.getpid()}) def record(self, result): - usage = result.get('usage'); tokens = usage['total_tokens'] if usage is not None else 0 - assert type(tokens) is int and tokens >= 0 and type(result['complete']) is bool + usage = result.get("usage") + tokens = usage["total_tokens"] if usage is not None else 0 + assert type(tokens) is int and tokens >= 0 and type(result["complete"]) is bool with self._locked(): - self._state(); claim = getattr(self.local, 'pending', None); assert claim is not None - self._append({'type': 'result', 'id': claim, 'complete': result['complete'], - 'known_total_tokens': tokens, 'unknown_usage': usage is None}) + self._state() + claim = getattr(self.local, "pending", None) + assert claim is not None + self._append( + { + "type": "result", + "id": claim, + "complete": result["complete"], + "known_total_tokens": tokens, + "unknown_usage": usage is None, + } + ) self.local.pending = None def snapshot(self): - with self._locked():return self._state() + with self._locked(): + return self._state() def stop(self): - with self._locked():self._state(); self._append({'type': 'stop', 'pid': os.getpid()}) + with self._locked(): + self._state() + self._append({"type": "stop", "pid": os.getpid()}) class RunBudget: def __init__(self, path, *, requests, tokens, failures): self.global_budget = PersistentBudget(path) - self.request_cap = requests; self.token_cap = tokens; self.failure_cap = failures - self.requests = 0; self.tokens = 0; self.failures = 0; self.unknown = 0; self.stopped = False + self.request_cap = requests + self.token_cap = tokens + self.failure_cap = failures + self.requests = 0 + self.tokens = 0 + self.failures = 0 + self.unknown = 0 + self.stopped = False self.lock = threading.RLock() def claim(self): with self.lock: - if self.stopped or self.requests >= self.request_cap or self.tokens >= self.token_cap or self.failures >= self.failure_cap: - self.stopped = True; raise RuntimeError('teacher safety budget halted') - self.global_budget.claim(); self.requests += 1 + if ( + self.stopped + or self.requests >= self.request_cap + or self.tokens >= self.token_cap + or self.failures >= self.failure_cap + ): + self.stopped = True + raise RuntimeError("teacher safety budget halted") + self.global_budget.claim() + self.requests += 1 def record(self, result): self.global_budget.record(result) with self.lock: - usage = result.get('usage') - if usage is None:self.unknown += 1 - else:self.tokens += usage['total_tokens'] - self.failures += not result['complete'] + usage = result.get("usage") + if usage is None: + self.unknown += 1 + else: + self.tokens += usage["total_tokens"] + self.failures += not result["complete"] def snapshot(self): with self.lock: global_state = self.global_budget.snapshot() - return {'requests': self.requests, 'known_total_tokens': self.tokens, 'failed_attempts': self.failures, - 'unknown_usage_attempts': self.unknown, 'stopped': self.stopped or global_state['stopped'], - 'request_cap': self.request_cap, 'known_token_cap': self.token_cap, - 'failed_attempt_cap': self.failure_cap, 'campaign': global_state} + return { + "requests": self.requests, + "known_total_tokens": self.tokens, + "failed_attempts": self.failures, + "unknown_usage_attempts": self.unknown, + "stopped": self.stopped or global_state["stopped"], + "request_cap": self.request_cap, + "known_token_cap": self.token_cap, + "failed_attempt_cap": self.failure_cap, + "campaign": global_state, + } def stop(self): - with self.lock:self.stopped = True + with self.lock: + self.stopped = True diff --git a/research/finance_program_v1/teacher/campaign_budget.py b/research/finance_program_v1/teacher/campaign_budget.py index 8f3505c..4d87817 100644 --- a/research/finance_program_v1/teacher/campaign_budget.py +++ b/research/finance_program_v1/teacher/campaign_budget.py @@ -1,4 +1,5 @@ """Versioned, anchored limit extensions; original accounting and atomic locks reused.""" + # 额度扩展绑定已有日志前缀,保留历史消耗和失败阈值,避免通过重启或扩额重置账本。 import hashlib import json @@ -8,55 +9,89 @@ class PersistentBudget(OriginalBudget): def _state(self): - journal=self.path/'events.jsonl' - if not journal.exists():self._append({'type':'limits', **self.limits}) - lines=journal.read_bytes().splitlines(keepends=True) - assert json.loads(lines[0])=={'type':'limits', **self.limits}, 'initial limits changed' - limits=dict(self.limits);claims=set();done=set();tokens=failures=unknown=0;stopped=False - digest=hashlib.sha256(lines[0]) + journal = self.path / "events.jsonl" + if not journal.exists(): + self._append({"type": "limits", **self.limits}) + lines = journal.read_bytes().splitlines(keepends=True) + assert json.loads(lines[0]) == {"type": "limits", **self.limits}, "initial limits changed" + limits = dict(self.limits) + claims = set() + done = set() + tokens = failures = unknown = 0 + stopped = False + digest = hashlib.sha256(lines[0]) for raw in lines[1:]: - event=json.loads(raw);kind=event['type'] - if kind=='claim': - assert event['id']==len(claims)+1 - claims.add(event['id']) - elif kind=='result': - assert event['id'] in claims-done - assert type(event['known_total_tokens']) is int and event['known_total_tokens']>=0 - assert type(event['complete']) is bool and type(event['unknown_usage']) is bool - done.add(event['id']);tokens+=event['known_total_tokens'] - failures+=not event['complete'];unknown+=event['unknown_usage'] - elif kind=='stop':stopped=True - elif kind=='limit_extension': - assert not claims-done, 'extension with inflight requests' - assert event['prefix_sha256']==digest.hexdigest(), 'extension anchor mismatch' - assert isinstance(event['authorization'],str) and event['authorization'].strip() - updated={k:event[k] for k in self.limits} - assert all(type(n) is int and n>=limits[k] for k,n in updated.items()) - assert updated['failed_attempt_cap']==limits['failed_attempt_cap'], 'failure protection cannot reset' - assert updated!=limits, 'extension must increase a protection limit' - limits=updated - else:raise ValueError('unknown campaign event') + event = json.loads(raw) + kind = event["type"] + if kind == "claim": + assert event["id"] == len(claims) + 1 + claims.add(event["id"]) + elif kind == "result": + assert event["id"] in claims - done + assert type(event["known_total_tokens"]) is int and event["known_total_tokens"] >= 0 + assert type(event["complete"]) is bool and type(event["unknown_usage"]) is bool + done.add(event["id"]) + tokens += event["known_total_tokens"] + failures += not event["complete"] + unknown += event["unknown_usage"] + elif kind == "stop": + stopped = True + elif kind == "limit_extension": + assert not claims - done, "extension with inflight requests" + assert event["prefix_sha256"] == digest.hexdigest(), "extension anchor mismatch" + assert isinstance(event["authorization"], str) and event["authorization"].strip() + updated = {k: event[k] for k in self.limits} + assert all(type(n) is int and n >= limits[k] for k, n in updated.items()) + assert ( + updated["failed_attempt_cap"] == limits["failed_attempt_cap"] + ), "failure protection cannot reset" + assert updated != limits, "extension must increase a protection limit" + limits = updated + else: + raise ValueError("unknown campaign event") digest.update(raw) - return {'requests':len(claims),'known_total_tokens':tokens,'failed_attempts':failures, - 'unknown_usage_attempts':unknown,'inflight_requests':len(claims-done), - 'stopped':stopped or len(claims)>=limits['request_cap'] or tokens>=limits['known_token_cap'] or failures>=limits['failed_attempt_cap'], - **limits} + return { + "requests": len(claims), + "known_total_tokens": tokens, + "failed_attempts": failures, + "unknown_usage_attempts": unknown, + "inflight_requests": len(claims - done), + "stopped": stopped + or len(claims) >= limits["request_cap"] + or tokens >= limits["known_token_cap"] + or failures >= limits["failed_attempt_cap"], + **limits, + } def extend(self, *, requests, tokens, failures, prefix_sha256, authorization): with self._locked(): - state=self._state() - assert state['inflight_requests']==0 - assert hashlib.sha256((self.path/'events.jsonl').read_bytes()).hexdigest()==prefix_sha256 - updated={'request_cap':requests,'known_token_cap':tokens,'failed_attempt_cap':failures} - assert all(type(n) is int and n>=state[k] for k,n in updated.items()) - assert failures==state['failed_attempt_cap'] - assert any(n>state[k] for k,n in updated.items()) - assert isinstance(authorization,str) and authorization.strip() - self._append({'type':'limit_extension',**updated,'prefix_sha256':prefix_sha256,'authorization':authorization}) + state = self._state() + assert state["inflight_requests"] == 0 + assert ( + hashlib.sha256((self.path / "events.jsonl").read_bytes()).hexdigest() + == prefix_sha256 + ) + updated = { + "request_cap": requests, + "known_token_cap": tokens, + "failed_attempt_cap": failures, + } + assert all(type(n) is int and n >= state[k] for k, n in updated.items()) + assert failures == state["failed_attempt_cap"] + assert any(n > state[k] for k, n in updated.items()) + assert isinstance(authorization, str) and authorization.strip() + self._append( + { + "type": "limit_extension", + **updated, + "prefix_sha256": prefix_sha256, + "authorization": authorization, + } + ) return self._state() class RunBudget(OriginalRunBudget): def __init__(self, path, *, requests, tokens, failures): - super().__init__(path,requests=requests,tokens=tokens,failures=failures) - self.global_budget=PersistentBudget(path) + super().__init__(path, requests=requests, tokens=tokens, failures=failures) + self.global_budget = PersistentBudget(path) diff --git a/research/finance_program_v1/teacher/collect.py b/research/finance_program_v1/teacher/collect.py index 68ed9ed..f86ea30 100644 --- a/research/finance_program_v1/teacher/collect.py +++ b/research/finance_program_v1/teacher/collect.py @@ -1,4 +1,5 @@ """Explicit local bridge to the new grounded runtime, old evidence stays immutable.""" + # 连接独立冻结的采集与运行时目录,先校验来源身份,再向模型暴露允许的元数据字段。 import hashlib import importlib.util @@ -7,34 +8,61 @@ import sys ROOT = Path(__file__).resolve().parent -PROGRAM = ROOT.parent / 'finance_program_grounded_runtime_20261015_r1' -BASE = ROOT.parent / 'finance_program_teacher_f66_20261015_r6' -CAMPAIGN = ROOT.parent / 'finance_program_teacher_campaign_20261015_r1' -METADATA = frozenset(('database_name','database_description','table_name','table_description','field_name','field_description','field_type','value')) +PROGRAM = ROOT.parent / "finance_program_grounded_runtime_20261015_r1" +BASE = ROOT.parent / "finance_program_teacher_f66_20261015_r6" +CAMPAIGN = ROOT.parent / "finance_program_teacher_campaign_20261015_r1" +METADATA = frozenset( + ( + "database_name", + "database_description", + "table_name", + "table_description", + "field_name", + "field_description", + "field_type", + "value", + ) +) -def read(path):return json.loads(Path(path).read_text(encoding='utf-8-sig')) +def read(path): + return json.loads(Path(path).read_text(encoding="utf-8-sig")) -def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest() +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() def label_free(row): - return {'id': row['id'], 'domain': row['domain'], 'metadata': {k:v for k,v in row['metadata'].items() if k in METADATA}} + return { + "id": row["id"], + "domain": row["domain"], + "metadata": {k: v for k, v in row["metadata"].items() if k in METADATA}, + } def verify(): - path = BASE / 'reviews/frozen-manifest.json' - assert sha(path) == 'c6570be3abe9e2624bbbf943b27d94c46fb507f916388031e0f4a70d311b4dcb' - for item in read(path)['files']:assert sha(BASE / item['path']) == item['sha256'] - assert sha(BASE / 'reviews/fixed100-evidence-01.tar.gz') == '6d1183db77f5658ba68d76aba60a8a84279dce2d93ab3ea0152c90b54c66af44' + path = BASE / "reviews/frozen-manifest.json" + assert sha(path) == "c6570be3abe9e2624bbbf943b27d94c46fb507f916388031e0f4a70d311b4dcb" + for item in read(path)["files"]: + assert sha(BASE / item["path"]) == item["sha256"] + assert ( + sha(BASE / "reviews/fixed100-evidence-01.tar.gz") + == "6d1183db77f5658ba68d76aba60a8a84279dce2d93ab3ea0152c90b54c66af44" + ) return read(path) def verify_program(): - spec = importlib.util.spec_from_file_location('grounded_runtime_identity', PROGRAM / 'runtime_identity.py') - module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + spec = importlib.util.spec_from_file_location( + "grounded_runtime_identity", PROGRAM / "runtime_identity.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) identity = module.verify() - assert identity['core_signature_sha256'] == 'c34105f2767513d7d50a1c5fa15f8123e790865d25da681efa049182110132f8' + assert ( + identity["core_signature_sha256"] + == "c34105f2767513d7d50a1c5fa15f8123e790865d25da681efa049182110132f8" + ) sys.path.insert(0, str(PROGRAM)) return identity diff --git a/research/finance_program_v1/teacher/detached.py b/research/finance_program_v1/teacher/detached.py index 858fe1f..4ebf46b 100644 --- a/research/finance_program_v1/teacher/detached.py +++ b/research/finance_program_v1/teacher/detached.py @@ -1,4 +1,5 @@ """CPU-only detached continuation. Raw trajectories stay pending human review.""" + # 后台批次共享持久预算并保留原始调用记录;采集产物须经过回放与人工复核才能进入训练。 import argparse from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED @@ -15,63 +16,100 @@ ROOT = Path(__file__).resolve().parent # Controlled historical snapshots own runtime/; the public layout shares the # exact F66 snapshot already shipped under evaluation/runtime, not a new copy. -RUNTIME = ROOT/'runtime' +RUNTIME = ROOT / "runtime" if not RUNTIME.is_dir(): - RUNTIME = ROOT.parent/'evaluation/runtime' -sys.path[:0] = [str(ROOT/'lib'), str(RUNTIME)] + RUNTIME = ROOT.parent / "evaluation/runtime" +sys.path[:0] = [str(ROOT / "lib"), str(RUNTIME)] from campaign_budget import PersistentBudget, RunBudget from teacher_api import TeacherBackend, save from retry_backend import RetryBackend -def read(p):return json.loads(Path(p).read_text(encoding='utf-8-sig')) -def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest() -def now():return datetime.datetime.now(datetime.timezone.utc).isoformat() +def read(p): + return json.loads(Path(p).read_text(encoding="utf-8-sig")) + + +def sha(p): + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def now(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() def select_ids(rows, used, count): - ids=[r['id'] for r in rows] - if len(ids)!=len(set(ids)):raise ValueError('duplicate source') + ids = [r["id"] for r in rows] + if len(ids) != len(set(ids)): + raise ValueError("duplicate source") assert 0 < count <= 200 return [i for i in ids if i not in used][:count] def verify_files(root, manifest): - for item in manifest['files']: - path=(root/item['path']).resolve() - assert path.is_relative_to(root.resolve()) and sha(path)==item['sha256'], item['path'] + for item in manifest["files"]: + path = (root / item["path"]).resolve() + assert path.is_relative_to(root.resolve()) and sha(path) == item["sha256"], item["path"] def verify(): - manifest=read(ROOT/'manifest.json');verify_files(ROOT,manifest) + manifest = read(ROOT / "manifest.json") + verify_files(ROOT, manifest) from runtime_identity import verify as verify_runtime - assert verify_runtime()['core_signature_sha256']==manifest['runtime_signature'] - history=(ROOT/'ledger/events.jsonl').read_bytes() - assert hashlib.sha256(history[:manifest['ledger_prefix_bytes']]).hexdigest()==manifest['ledger_prefix_sha256'] - study=read(ROOT/'study.json') - assert all(set(r)=={'id','domain','metadata'} for r in study['rows']) - assert all(set(r['metadata']) <= {'database_name','database_description','table_name','table_description','field_name','field_description','field_type','value'} for r in study['rows']) - assert not set(manifest['source_ids']) & set(manifest['used_ids']) - assert len(set(manifest['source_ids']))==len(manifest['source_ids']) + + assert verify_runtime()["core_signature_sha256"] == manifest["runtime_signature"] + history = (ROOT / "ledger/events.jsonl").read_bytes() + assert ( + hashlib.sha256(history[: manifest["ledger_prefix_bytes"]]).hexdigest() + == manifest["ledger_prefix_sha256"] + ) + study = read(ROOT / "study.json") + assert all(set(r) == {"id", "domain", "metadata"} for r in study["rows"]) + assert all( + set(r["metadata"]) + <= { + "database_name", + "database_description", + "table_name", + "table_description", + "field_name", + "field_description", + "field_type", + "value", + } + for r in study["rows"] + ) + assert not set(manifest["source_ids"]) & set(manifest["used_ids"]) + assert len(set(manifest["source_ids"])) == len(manifest["source_ids"]) return manifest def seal(root): - archive=root/'evidence.tar.gz';receipt=root/'archive-receipt.json' - if archive.exists() or receipt.exists():raise FileExistsError('archive exists') - paths=sorted(p for p in root.rglob('*') if p.is_file()) - entries=[{'path':p.relative_to(root).as_posix(),'sha256':sha(p),'bytes':p.stat().st_size} for p in paths] - with archive.open('xb') as stream: - with tarfile.open(fileobj=stream, mode='w:gz') as tar: - for p,e in zip(paths,entries):tar.add(p,arcname=e['path'],recursive=False) + archive = root / "evidence.tar.gz" + receipt = root / "archive-receipt.json" + if archive.exists() or receipt.exists(): + raise FileExistsError("archive exists") + paths = sorted(p for p in root.rglob("*") if p.is_file()) + entries = [ + {"path": p.relative_to(root).as_posix(), "sha256": sha(p), "bytes": p.stat().st_size} + for p in paths + ] + with archive.open("xb") as stream: + with tarfile.open(fileobj=stream, mode="w:gz") as tar: + for p, e in zip(paths, entries): + tar.add(p, arcname=e["path"], recursive=False) with tarfile.open(archive) as tar: - members=tar.getmembers() - assert len(members)==len(entries) - for member,e in zip(members,entries): - assert member.isfile() and member.name==e['path'] - assert hashlib.sha256(tar.extractfile(member).read()).hexdigest()==e['sha256'] - result={'sha256':sha(archive),'members':len(entries),'files':entries,'all_members_sha_verified':True} - save(receipt,result) + members = tar.getmembers() + assert len(members) == len(entries) + for member, e in zip(members, entries): + assert member.isfile() and member.name == e["path"] + assert hashlib.sha256(tar.extractfile(member).read()).hexdigest() == e["sha256"] + result = { + "sha256": sha(archive), + "members": len(entries), + "files": entries, + "all_members_sha_verified": True, + } + save(receipt, result) return result @@ -79,84 +117,207 @@ def replay(): verify() from program_loop import build_program_controller from pilot_audit import read_records, replay_retry_one - study=read(ROOT/'study.json');rows={r['id']:r for r in study['rows']} - c=build_program_controller(lambda m:'',study['registry'],study['rows'],study['budget'],skill_pool='F66') - allowed=[s['name'] for s in c.library];assert len(set(allowed))==66 - proofs=[] - for folder in sorted((ROOT/'replay-fixtures').iterdir()): - records=read_records(folder/'calls') - logical=[read(p) for p in sorted((folder/'logical').glob('logical-*.json'))] - proofs.append(replay_retry_one(study,rows[folder.name],read(folder/'trace.json'),records,logical,allowed)) - assert proofs and all(p['full_trace_exact'] and p['all_calls_consumed'] for p in proofs) - result={'sources':len(proofs),'full_trace_exact':True,'http_calls':sum(p['api_attempts'] for p in proofs),'paid_calls':0,'runtime_signature':read(ROOT/'manifest.json')['runtime_signature']} + + study = read(ROOT / "study.json") + rows = {r["id"]: r for r in study["rows"]} + c = build_program_controller( + lambda m: "", study["registry"], study["rows"], study["budget"], skill_pool="F66" + ) + allowed = [s["name"] for s in c.library] + assert len(set(allowed)) == 66 + proofs = [] + for folder in sorted((ROOT / "replay-fixtures").iterdir()): + records = read_records(folder / "calls") + logical = [read(p) for p in sorted((folder / "logical").glob("logical-*.json"))] + proofs.append( + replay_retry_one( + study, rows[folder.name], read(folder / "trace.json"), records, logical, allowed + ) + ) + assert proofs and all(p["full_trace_exact"] and p["all_calls_consumed"] for p in proofs) + result = { + "sources": len(proofs), + "full_trace_exact": True, + "http_calls": sum(p["api_attempts"] for p in proofs), + "paid_calls": 0, + "runtime_signature": read(ROOT / "manifest.json")["runtime_signature"], + } return result def run_batch(number, ids, key): from program_loop import build_program_controller from pilot_audit import replay_retry_one - study=read(ROOT/'study.json');config=read(ROOT/'config.json');rows={r['id']:r for r in study['rows']} - root=ROOT/'batches'/('batch-%03d'%number);root.mkdir(parents=True,exist_ok=False) - save(root/'manifest.json',{'ids':ids,'started_utc':now(),'manifest_sha256':sha(ROOT/'manifest.json'),'gold_in_input':False,'student_training':False}) - c=build_program_controller(lambda m:'',study['registry'],study['rows'],study['budget'],skill_pool='F66') - allowed=[s['name'] for s in c.library];assert len(set(allowed))==66 - budget=RunBudget(ROOT/'ledger',requests=config['request_cap'],tokens=config['total_token_cap'],failures=config['failed_attempt_cap']) + + study = read(ROOT / "study.json") + config = read(ROOT / "config.json") + rows = {r["id"]: r for r in study["rows"]} + root = ROOT / "batches" / ("batch-%03d" % number) + root.mkdir(parents=True, exist_ok=False) + save( + root / "manifest.json", + { + "ids": ids, + "started_utc": now(), + "manifest_sha256": sha(ROOT / "manifest.json"), + "gold_in_input": False, + "student_training": False, + }, + ) + c = build_program_controller( + lambda m: "", study["registry"], study["rows"], study["budget"], skill_pool="F66" + ) + allowed = [s["name"] for s in c.library] + assert len(set(allowed)) == 66 + budget = RunBudget( + ROOT / "ledger", + requests=config["request_cap"], + tokens=config["total_token_cap"], + failures=config["failed_attempt_cap"], + ) + def source(i): - folder=root/'sources'/i;folder.mkdir(parents=True,exist_ok=False) - print('source start',i,flush=True) - backend=RetryBackend(TeacherBackend(key,config,folder/'calls',allowed),config['model'],folder/'logical',budget) - row=rows[i];controller=build_program_controller(backend,study['registry'],study['rows'],study['budget'],skill_pool='F66') - trace=controller.run({'source_id':i,'domain':row['domain'],'field_name':row['metadata']['field_name']}) - trace.write_json(folder/'trace.json') - proof=replay_retry_one(study,row,trace.to_dict(),backend.calls,backend.logical,allowed) - save(folder/'replay.json',proof) - entry={'id':i,'status':'pending_review','terminated':trace.terminated,'stop_reason':trace.stop_reason,'http_attempts':len(backend.calls),'logical_calls':len(backend.logical),'accepted':None} - save(folder/'receipt.json',entry);print('source done',i,trace.stop_reason,flush=True) + folder = root / "sources" / i + folder.mkdir(parents=True, exist_ok=False) + print("source start", i, flush=True) + backend = RetryBackend( + TeacherBackend(key, config, folder / "calls", allowed), + config["model"], + folder / "logical", + budget, + ) + row = rows[i] + controller = build_program_controller( + backend, study["registry"], study["rows"], study["budget"], skill_pool="F66" + ) + trace = controller.run( + {"source_id": i, "domain": row["domain"], "field_name": row["metadata"]["field_name"]} + ) + trace.write_json(folder / "trace.json") + proof = replay_retry_one( + study, row, trace.to_dict(), backend.calls, backend.logical, allowed + ) + save(folder / "replay.json", proof) + entry = { + "id": i, + "status": "pending_review", + "terminated": trace.terminated, + "stop_reason": trace.stop_reason, + "http_attempts": len(backend.calls), + "logical_calls": len(backend.logical), + "accepted": None, + } + save(folder / "receipt.json", entry) + print("source done", i, trace.stop_reason, flush=True) return entry - started=time.monotonic();entries={};queue=iter(ids);failed=False - with ThreadPoolExecutor(max_workers=config['concurrency']) as pool: - active={} + + started = time.monotonic() + entries = {} + queue = iter(ids) + failed = False + with ThreadPoolExecutor(max_workers=config["concurrency"]) as pool: + active = {} + def fill(): - while len(active)= self.request_cap or self.tokens >= self.token_cap or self.failures >= self.failure_cap: + if ( + self.stopped + or self.requests >= self.request_cap + or self.tokens >= self.token_cap + or self.failures >= self.failure_cap + ): self.stopped = True - raise RuntimeError('teacher safety budget halted') + raise RuntimeError("teacher safety budget halted") self.requests += 1 def record(self, result): with self.lock: - usage = result.get('usage') + usage = result.get("usage") if usage is None: self.unknown += 1 else: - self.tokens += usage['total_tokens'] - self.failures += not result.get('complete', False) + self.tokens += usage["total_tokens"] + self.failures += not result.get("complete", False) def stop(self): - with self.lock:self.stopped = True + with self.lock: + self.stopped = True def snapshot(self): with self.lock: - return {'requests': self.requests, 'known_total_tokens': self.tokens, 'failed_attempts': self.failures, - 'unknown_usage_attempts': self.unknown, 'stopped': self.stopped, - 'request_cap': self.request_cap, 'known_token_cap': self.token_cap, 'failed_attempt_cap': self.failure_cap} + return { + "requests": self.requests, + "known_total_tokens": self.tokens, + "failed_attempts": self.failures, + "unknown_usage_attempts": self.unknown, + "stopped": self.stopped, + "request_cap": self.request_cap, + "known_token_cap": self.token_cap, + "failed_attempt_cap": self.failure_cap, + } class RetryBackend: def __init__(self, inner, model, logical_dir, budget, *, retries=1, backoff=3): if retries != 1: - raise ValueError('exactly one retry maximum is frozen') - self.inner = inner; self.model = model; self.logical_dir = logical_dir; self.budget = budget - self.retries = retries; self.backoff = backoff; self.logical = []; self.fatal = False + raise ValueError("exactly one retry maximum is frozen") + self.inner = inner + self.model = model + self.logical_dir = logical_dir + self.budget = budget + self.retries = retries + self.backoff = backoff + self.logical = [] + self.fatal = False @property - def calls(self):return self.inner.calls + def calls(self): + return self.inner.calls def __call__(self, messages): if self.fatal: - raise RuntimeError('teacher system halted; see recorded call failure') + raise RuntimeError("teacher system halted; see recorded call failure") start = len(self.calls) - proof = {'executor_messages_sha256': digest(messages), 'call_start': start, 'call_end': start, - 'complete': False, 'error': None, 'retry_policy': 'one transport-only retry; identical messages'} + proof = { + "executor_messages_sha256": digest(messages), + "call_start": start, + "call_end": start, + "complete": False, + "error": None, + "retry_policy": "one transport-only retry; identical messages", + } try: for index in range(self.retries + 1): try: self.budget.claim() except RuntimeError: - self.fatal = True; proof['error'] = 'teacher safety budget halted' - raise RuntimeError(proof['error']) from None + self.fatal = True + proof["error"] = "teacher safety budget halted" + raise RuntimeError(proof["error"]) from None before = len(self.calls) try: value = self.inner(messages) except RuntimeError: if len(self.calls) != before + 1: - self.fatal = True; proof['error'] = 'teacher source backend failed before receipt' - raise RuntimeError(proof['error']) from None - result = self.calls[-1]['result']; self.budget.record(result) + self.fatal = True + proof["error"] = "teacher source backend failed before receipt" + raise RuntimeError(proof["error"]) from None + result = self.calls[-1]["result"] + self.budget.record(result) transient = retryable(result, self.model) if transient and index < self.retries: self.inner.fatal = False @@ -90,12 +135,13 @@ def __call__(self, messages): self.fatal = True if not transient: self.budget.stop() - proof['error'] = 'teacher response incomplete; recorded and halted' - raise RuntimeError(proof['error']) from None + proof["error"] = "teacher response incomplete; recorded and halted" + raise RuntimeError(proof["error"]) from None else: - self.budget.record(self.calls[-1]['result']); proof['complete'] = True + self.budget.record(self.calls[-1]["result"]) + proof["complete"] = True return value finally: - proof['call_end'] = len(self.calls) + proof["call_end"] = len(self.calls) self.logical.append(proof) - save(self.logical_dir / ('logical-%04d.json' % len(self.logical)), proof) + save(self.logical_dir / ("logical-%04d.json" % len(self.logical)), proof) diff --git a/research/finance_program_v1/teacher/teacher_api.py b/research/finance_program_v1/teacher/teacher_api.py index cad5a3f..a31c44d 100644 --- a/research/finance_program_v1/teacher/teacher_api.py +++ b/research/finance_program_v1/teacher/teacher_api.py @@ -1,4 +1,5 @@ """Strict, bounded, credential-free-on-disk Bailian SSE backend.""" + # 一次 HTTP 请求对应一组不可覆盖的请求与流式响应记录,完整性门禁决定响应能否交给执行器。 import hashlib from copy import deepcopy @@ -11,84 +12,108 @@ def save(path, value): - path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) - with path.open('x', encoding='utf-8') as stream: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", encoding="utf-8") as stream: json.dump(value, stream, ensure_ascii=False, indent=2, allow_nan=False) def digest(value): - return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + return hashlib.sha256( + json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() class CompletionError(RuntimeError): def __init__(self, result): self.result = result - super().__init__('teacher response failed complete-model/stop/DONE/usage gate') + super().__init__("teacher response failed complete-model/stop/DONE/usage gate") def parse_sse(lines, model, *, state=None): result = state if state is not None else {} - result.update({'content': '', 'reasoning_content': '', 'models': [], 'finish_reason': None, - 'stream_done': False, 'usage': None, 'events': [], 'complete': False}) + result.update( + { + "content": "", + "reasoning_content": "", + "models": [], + "finish_reason": None, + "stream_done": False, + "usage": None, + "events": [], + "complete": False, + } + ) for raw in lines: - line = raw.decode('utf-8').strip() if isinstance(raw, bytes) else raw.strip() - if not line.startswith('data:'): + line = raw.decode("utf-8").strip() if isinstance(raw, bytes) else raw.strip() + if not line.startswith("data:"): continue data = line[5:].strip() - if data == '[DONE]': - result['stream_done'] = True + if data == "[DONE]": + result["stream_done"] = True break try: obj = json.loads(data) except (ValueError, TypeError): - result['malformed_event'] = True + result["malformed_event"] = True raise CompletionError(result) from None - result['events'].append(obj) - if obj.get('model') and obj['model'] not in result['models']: - result['models'].append(obj['model']) - if obj.get('usage'): - result['usage'] = obj['usage'] - for choice in obj.get('choices', []): - if choice.get('index', 0) != 0: + result["events"].append(obj) + if obj.get("model") and obj["model"] not in result["models"]: + result["models"].append(obj["model"]) + if obj.get("usage"): + result["usage"] = obj["usage"] + for choice in obj.get("choices", []): + if choice.get("index", 0) != 0: raise CompletionError(result) - delta = choice.get('delta', {}) - result['content'] += delta.get('content') or '' - result['reasoning_content'] += delta.get('reasoning_content') or '' - if choice.get('finish_reason'): - result['finish_reason'] = choice['finish_reason'] - usage = result['usage'] + delta = choice.get("delta", {}) + result["content"] += delta.get("content") or "" + result["reasoning_content"] += delta.get("reasoning_content") or "" + if choice.get("finish_reason"): + result["finish_reason"] = choice["finish_reason"] + usage = result["usage"] try: - json_object = isinstance(json.loads(result['content']), dict) + json_object = isinstance(json.loads(result["content"]), dict) except (ValueError, TypeError): json_object = False # JSON 可解析仍不足以接收:还需正常停止、流结束、模型身份及完整用量同时成立。 - result['complete'] = bool(result['stream_done'] and result['finish_reason'] == 'stop' and - result['models'] == [model] and json_object and isinstance(usage, dict) and - all(type(usage.get(k)) is int and usage[k] >= 0 for k in ('prompt_tokens', 'completion_tokens', 'total_tokens')) and - usage['total_tokens'] == usage['prompt_tokens'] + usage['completion_tokens']) - if not result['complete']: + result["complete"] = bool( + result["stream_done"] + and result["finish_reason"] == "stop" + and result["models"] == [model] + and json_object + and isinstance(usage, dict) + and all( + type(usage.get(k)) is int and usage[k] >= 0 + for k in ("prompt_tokens", "completion_tokens", "total_tokens") + ) + and usage["total_tokens"] == usage["prompt_tokens"] + usage["completion_tokens"] + ) + if not result["complete"]: raise CompletionError(result) return result def role(messages, allowed_skills): - if not messages or messages[0].get('role') != 'system': - raise ValueError('trusted first system message required') - head = messages[0]['content'].splitlines()[0] - if head == 'You are the Global Program Planner for a database-field classification task.': - return 'planner' - match = re.fullmatch(r'Execute only the selected Skill ([A-Z_]+)\.', head) + if not messages or messages[0].get("role") != "system": + raise ValueError("trusted first system message required") + head = messages[0]["content"].splitlines()[0] + if head == "You are the Global Program Planner for a database-field classification task.": + return "planner" + match = re.fullmatch(r"Execute only the selected Skill ([A-Z_]+)\.", head) if match and match[1] in allowed_skills: - return 'skill:' + match[1] - raise ValueError('unknown trusted model role') + return "skill:" + match[1] + raise ValueError("unknown trusted model role") def api_messages(messages): from policy import apply_policy + value = apply_policy(messages) - value[0]['content'] += ('\nTransport output contract: The final content must be exactly one raw JSON object. ' - 'No Markdown, no code fences, no prose before or after the JSON object. ' - 'Put any reasoning only in the separate reasoning channel. Preserve all original task contracts and budgets.') + value[0]["content"] += ( + "\nTransport output contract: The final content must be exactly one raw JSON object. " + "No Markdown, no code fences, no prose before or after the JSON object. " + "Put any reasoning only in the separate reasoning channel. Preserve all original task contracts and budgets." + ) return value @@ -104,58 +129,95 @@ def __init__(self, key, config, call_dir, allowed_skills): def __call__(self, messages): if self.fatal: - raise RuntimeError('teacher system halted; see recorded call failure') - if len(self.calls) >= self.config['request_cap'] or self.total_tokens >= self.config['total_token_cap']: + raise RuntimeError("teacher system halted; see recorded call failure") + if ( + len(self.calls) >= self.config["request_cap"] + or self.total_tokens >= self.config["total_token_cap"] + ): self.fatal = True - raise RuntimeError('teacher request/token safety cap reached') + raise RuntimeError("teacher request/token safety cap reached") selected_role = role(messages, self.allowed_skills) - body = {'model': self.config['model'], 'messages': api_messages(messages), 'stream': True, - 'stream_options': {'include_usage': True}, 'temperature': 0, - 'thinking_budget': self.config['thinking_budget'], 'max_tokens': self.config['max_tokens'], - 'response_format': {'type': 'json_object'}} - folder = self.call_dir / ('call-%04d' % (len(self.calls) + 1)) + body = { + "model": self.config["model"], + "messages": api_messages(messages), + "stream": True, + "stream_options": {"include_usage": True}, + "temperature": 0, + "thinking_budget": self.config["thinking_budget"], + "max_tokens": self.config["max_tokens"], + "response_format": {"type": "json_object"}, + } + folder = self.call_dir / ("call-%04d" % (len(self.calls) + 1)) folder.mkdir(parents=True, exist_ok=False) - request_record = {'role': selected_role, 'body': body, 'body_sha256': digest(body), - 'executor_messages': deepcopy(messages), - 'endpoint': self.config['endpoint'], 'credential_recorded': False} - save(folder / 'request.json', request_record) - result = {'complete': False, 'content': '', 'reasoning_content': '', 'usage': None, - 'finish_reason': None, 'stream_done': False, 'models': [], 'events': []} + request_record = { + "role": selected_role, + "body": body, + "body_sha256": digest(body), + "executor_messages": deepcopy(messages), + "endpoint": self.config["endpoint"], + "credential_recorded": False, + } + save(folder / "request.json", request_record) + result = { + "complete": False, + "content": "", + "reasoning_content": "", + "usage": None, + "finish_reason": None, + "stream_done": False, + "models": [], + "events": [], + } started = time.monotonic() try: # Headers remain in memory; request records deliberately contain no headers. - request = urllib.request.Request(self.config['endpoint'] + '/chat/completions', + request = urllib.request.Request( + self.config["endpoint"] + "/chat/completions", data=json.dumps(body, ensure_ascii=False).encode(), - headers={'Authorization': 'Bearer ' + self._key, 'Content-Type': 'application/json'}, method='POST') - with urllib.request.urlopen(request, timeout=self.config['timeout_seconds']) as response: + headers={ + "Authorization": "Bearer " + self._key, + "Content-Type": "application/json", + }, + method="POST", + ) + with urllib.request.urlopen( + request, timeout=self.config["timeout_seconds"] + ) as response: + def bounded_lines(): - with (folder / 'stream.jsonl').open('x', encoding='utf-8') as stream: + with (folder / "stream.jsonl").open("x", encoding="utf-8") as stream: for raw in response: - stream.write(json.dumps({'line': raw.decode('utf-8')}, ensure_ascii=False) + '\n') + stream.write( + json.dumps({"line": raw.decode("utf-8")}, ensure_ascii=False) + "\n" + ) stream.flush() - if time.monotonic() - started > self.config['timeout_seconds']: - raise TimeoutError('teacher wall deadline') + if time.monotonic() - started > self.config["timeout_seconds"]: + raise TimeoutError("teacher wall deadline") yield raw - result = parse_sse(bounded_lines(), self.config['model'], state=result) - result['http_status'] = response.status + + result = parse_sse(bounded_lines(), self.config["model"], state=result) + result["http_status"] = response.status except CompletionError as exc: result = exc.result - result['error_type'] = 'IncompleteCompletion' + result["error_type"] = "IncompleteCompletion" self.fatal = True except urllib.error.HTTPError as exc: - result['error_type'] = 'HTTPError'; result['http_status'] = exc.code + result["error_type"] = "HTTPError" + result["http_status"] = exc.code self.fatal = True except Exception as exc: # Never log exception text, request repr, or response body containing credentials. - result['error_type'] = type(exc).__name__ + result["error_type"] = type(exc).__name__ self.fatal = True finally: - result['seconds'] = time.monotonic() - started - result['role'] = selected_role - result['response_sha256'] = digest({'content': result['content'], 'reasoning_content': result['reasoning_content']}) - self.total_tokens += (result.get('usage') or {}).get('total_tokens', 0) - save(folder / 'result.json', result) - self.calls.append({'request': request_record, 'result': result}) - if not result['complete']: - raise RuntimeError('teacher response incomplete; recorded and halted') - return result['content'] + result["seconds"] = time.monotonic() - started + result["role"] = selected_role + result["response_sha256"] = digest( + {"content": result["content"], "reasoning_content": result["reasoning_content"]} + ) + self.total_tokens += (result.get("usage") or {}).get("total_tokens", 0) + save(folder / "result.json", result) + self.calls.append({"request": request_record, "result": result}) + if not result["complete"]: + raise RuntimeError("teacher response incomplete; recorded and halted") + return result["content"]