From cbb36230fd653f84c49d25bc3cd89957a009a466 Mon Sep 17 00:00:00 2001 From: tzhouam Date: Wed, 25 Nov 2026 20:59:49 +0800 Subject: [PATCH 1/4] Verify Strict review claims and preserve unresolved findings in the verdict --- README.md | 12 +- doc/architecture/SPEC/app/request_policy.md | 5 +- doc/architecture/SPEC/contract.md | 7 +- doc/architecture/SPEC/engine/agent_runtime.md | 3 + doc/architecture/SPEC/engine/steps/_common.md | 4 + doc/architecture/SPEC/engine/steps/pr.md | 6 + doc/architecture/SPEC/engine/steps/review.md | 20 + doc/architecture/SPEC/improve.md | 5 +- doc/architecture/SPEC/intent.md | 4 +- doc/architecture/SPEC/mcp_server.md | 4 +- doc/architecture/SPEC/sdk.md | 7 +- doc/architecture/SPEC/thin_mcp_server.md | 3 +- doc/guide/hosts/codex.md | 3 +- playbooks/pr-review.yaml | 1 + src/infermatrix_copilot/app/request_policy.py | 7 +- src/infermatrix_copilot/contract.py | 2 + .../engine/agent_runtime/ensemble.py | 19 +- .../engine/steps/_common.py | 4 +- .../engine/steps/pr/fetch.py | 13 +- .../engine/steps/review/claim_evidence.py | 384 ++++++++++++++++++ .../engine/steps/review/feedback.py | 77 ++++ .../engine/steps/review/prompts.py | 8 +- .../engine/steps/review/publication.py | 116 ++++++ .../engine/steps/review/refinement.py | 5 + .../engine/steps/review/steps.py | 177 +++----- .../engine/steps/review/utils.py | 33 +- src/infermatrix_copilot/improve/drivers.py | 7 +- src/infermatrix_copilot/improve/runtime.py | 22 +- src/infermatrix_copilot/intent.py | 31 +- src/infermatrix_copilot/mcp_server.py | 5 +- src/infermatrix_copilot/sdk/v1/models.py | 11 +- src/infermatrix_copilot/sdk/v1/strict.py | 9 + src/infermatrix_copilot/thin_mcp_server.py | 10 +- test/test_agent_ensemble.py | 16 + test/test_contract.py | 1 + test/test_e2e_strict_mock.py | 91 +++++ test/test_mcp.py | 17 + test/test_quality_workstreams.py | 7 +- test/test_replay_capture_pr_review.py | 14 + test/test_review_step.py | 85 ++++ test/test_sdk_v1.py | 4 +- test/test_strict_claim_evidence.py | 140 +++++++ test/test_thin_mcp_server.py | 10 + 43 files changed, 1233 insertions(+), 176 deletions(-) create mode 100644 src/infermatrix_copilot/engine/steps/review/claim_evidence.py create mode 100644 src/infermatrix_copilot/engine/steps/review/feedback.py create mode 100644 src/infermatrix_copilot/engine/steps/review/publication.py create mode 100644 test/test_strict_claim_evidence.py diff --git a/README.md b/README.md index 465572967..574a5738d 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,7 @@ Strict——运行完整 CLI 工作流: ```bash ./infermatrix-copilot -p "review pr 5172" +./infermatrix-copilot --playbook pr-review --task-param pr=5172 --task-param include_score=true ./infermatrix-copilot -p "review pr 5172" --plan-only # 只看计划不执行 ./infermatrix-copilot -p "review pr 5172" --performance # 用高能力模型档 ``` @@ -159,6 +160,15 @@ Strict 在固定到 PR head 的 checkout 上运行,并按改动规模和风险 “Use InferMatrixCopilot in Strict mode to review …”;拿到 `run_id` 后,用 `get_review_status` 和 `get_review_result` 轮询。 +Strict 根据改动承诺检查证据。性能比较需要同一工作负载下可比的原始记录,生成结果需要检查实际输出。 +报告会列出无法核实的主张。评审结论考虑所有独立核实的实质性发现。即使某个严重问题已有当前 +head 上的活跃讨论、无需再发一条行内评论,它仍可导致 `REQUEST CHANGES`。 + +需要百分制评分时,CLI 可使用上面的 `include_score=true`,MCP 可传 +`review(..., mode="strict", include_score=true)`,SDK 可传 `StrictReviewRequest(..., include_score=True)`。 +评分默认关闭。结构化结果的 `review_claim_evidence` 给出证据检查,`review_score` 仅在请求时出现。 +有数值时它只供参考;head 已移动、无法复核或审查不完整时,报告列出原因并保留已支持的分项。 + ## 快速上手 2 · rebase 把单个 PR rebase 到最新 base。工作流会识别 fork,检出 PR 分支,完成 rebase、 @@ -366,7 +376,7 @@ Agent 会先读取仓库约定、相关源码和知识,明确完成条件, zero(`vllm-omni`),可传任何已接入仓库的短名、别名或 owner/name: - `review(target, repo="vllm-omni", mode="direct", post=false, - review_depth="", title="", body="", changed_files=[], repo_path="")`: + review_depth="", title="", body="", changed_files=[], repo_path="", include_score=false)`: Direct 返回至多 3 条精确知识路由和审查门禁;Strict 返回 `run_id`。 `repo_path` 可临时指定 Strict 使用的本地 checkout。 - `validate_direct_review(subtraction_signal, subtraction?, diff --git a/doc/architecture/SPEC/app/request_policy.md b/doc/architecture/SPEC/app/request_policy.md index c7011ccca..1e4230ab4 100644 --- a/doc/architecture/SPEC/app/request_policy.md +++ b/doc/architecture/SPEC/app/request_policy.md @@ -1,6 +1,6 @@ # app/request_policy.py — request safety policy - + This headless application module validates untrusted read-only requests for the SDK, MCP transport, and reserved-run worker. It derives a new `TaskSpec` @@ -11,7 +11,8 @@ reading `request.json`; persisted input alone is not an authority. `post=False`, limits repositories to the configured allowlist, checks positive PR/issue numbers, validates full expected-head SHAs, and strips unknown params. A bounded `deterministic_signals` list applies only to quality review; -carried findings are validated for PR review. `authorize_repo_path` verifies +carried findings are validated for PR review. PR review accepts boolean +`include_score`. False and omission have the same idempotency fingerprint. `authorize_repo_path` verifies both checkout origin identity and containment under allowed roots. `enforce_strict_review_policy` accepts only PR review, forces eco mode, and diff --git a/doc/architecture/SPEC/contract.md b/doc/architecture/SPEC/contract.md index 1d55b8d24..0911b1110 100644 --- a/doc/architecture/SPEC/contract.md +++ b/doc/architecture/SPEC/contract.md @@ -1,6 +1,6 @@ # contract.py —— 规范 - + `旧版跨仓库契约兼容层 · refactor-status: compatibility-shim` @@ -13,7 +13,7 @@ ## 公开契约(`__all__`) `SDK_API_VERSION` / `DIRECT_API_VERSION` / `STRICT_API_VERSION` / -`QUALITY_API_VERSION` / `KNOWLEDGE_API_VERSION`(SDK、Quality 为 `"1.0.0"`,Direct 为 `"1.1.0"`,Strict 为 `"1.4.0"`,Knowledge 为 `"1.1.0"`,且都从 `sdk.v1.models` +`QUALITY_API_VERSION` / `KNOWLEDGE_API_VERSION`(SDK、Quality 为 `"1.0.0"`,Direct 为 `"1.1.0"`,Strict 为 `"1.5.0"`,Knowledge 为 `"1.1.0"`,且都从 `sdk.v1.models` 取唯一值)。`capabilities(max_strict_workers=1, supports_file_locking=True) -> dict` 委托 SDK typed handshake 再投影为兼容 dict;它包含 distribution/SDK/Direct/Strict/Quality/Knowledge 版本、resource @@ -23,7 +23,8 @@ revision、supported repositories,以及 `supports_expected_head`、 `max_strict_workers`(服务真实的并发 worker 数,即 `STRICT_MAX_WORKERS`, 同一 checkout+PR 的 run 仍逐个执行)。其余兼容导出包括 `build_review_result(run_dir) -> dict`(结构化评审 结果:`contract_version`、`run_id`、`state`、`reviewed_head_sha`、`verdict`、 -`summary_markdown`、`comments`、`finding_dispositions`、`findings`、 +`summary_markdown`、`comments`、`finding_dispositions`、`findings`、本次运行记录的 +`review_claim_evidence` 及按请求生成的 `review_score`、 `stale`/`expected_head_sha`/`actual_head_sha`、`diagnostics`);`unknown_run_result(run_id)`(显式 `state: unknown`,绝不抛错 —— 丢响应和还在跑必须可区分); `sanitize_comments` 与 `COMMENT_FIELDS`,以及 `finding_id` / `build_findings`;另有从 `direct_routing` 再导出的 diff --git a/doc/architecture/SPEC/engine/agent_runtime.md b/doc/architecture/SPEC/engine/agent_runtime.md index faaef02b5..338597a20 100644 --- a/doc/architecture/SPEC/engine/agent_runtime.md +++ b/doc/architecture/SPEC/engine/agent_runtime.md @@ -55,6 +55,9 @@ - briefing 只在 `profile_briefing_enabled` 时进 prompt(消融开关)。 - 输出:base+extension schema、一轮修复、状态→FailureKind;预算耗尽会**强制最终答复**。 全程 trace(`agent_dispatch`/`agent_output`)。 +- Strict 的每个调查可以返回 `claim_checks`。请求评分时还会返回 `dimension_ratings`。 + 重试和深度升级保留已获取的证据。reducer 独立合并调查记录,即使所有评论都被丢弃, + 证据仍会进入固定版本的核验和结果输出。 - ensemble reducer:逐编号候选做 keep/drop/dup、确定性组装、**未提及即保留** (fail-open)、共识门控的快路径。 - **零产出的 lens 单独重问一次**(`ensemble_zero_yield_retry`), diff --git a/doc/architecture/SPEC/engine/steps/_common.md b/doc/architecture/SPEC/engine/steps/_common.md index da1776c5e..05e49303c 100644 --- a/doc/architecture/SPEC/engine/steps/_common.md +++ b/doc/architecture/SPEC/engine/steps/_common.md @@ -61,3 +61,7 @@ step 样板的收敛就落在这个文件。`require_repo`(K3)、`no_llm_gap `store_for(adapter)`(K3)。 已落地与待抽取的每一个都必须**保住它所包裹的那条保证**(B1 类型化返回、B2 交接、 E2 `capability_gap` 事件)。**只在 ≥2 个真实现场时才抽取**。 + +Strict review passes `issue_comments=False` to `gh_read_tools`. Its issue reader +can inspect issue title, body and labels without exposing conversation on a PR +addressed by the same number. Issue workflows retain the default comment access. diff --git a/doc/architecture/SPEC/engine/steps/pr.md b/doc/architecture/SPEC/engine/steps/pr.md index 9fbd0934b..1570c105e 100644 --- a/doc/architecture/SPEC/engine/steps/pr.md +++ b/doc/architecture/SPEC/engine/steps/pr.md @@ -129,3 +129,9 @@ K3/K4/K7 的精简(require_repo/published/from_state)已在各子模块落 ## 自进化接入(2026-10-04) 影子模式下 `pr.fetch_diff`、gate 和 CI 取数从可信控制器准备的 `pr_snapshot` 读取;快照缺少必要字段即阻塞,不回退到实时网络。基线和候选共用冻结的 base/head 与上下文。 + +Strict review fetches the PR description, commit subjects and linked issue +acceptance criteria before source investigation. Its initial GitHub query omits +PR discussion and review threads. Full PR quality assessments may still include +discussion. The checkpoint records whether the fetched context is independent of +feedback, so reviews resumed from older combined bundles can exclude discussion. diff --git a/doc/architecture/SPEC/engine/steps/review.md b/doc/architecture/SPEC/engine/steps/review.md index 708a7b8bd..e15fe7865 100644 --- a/doc/architecture/SPEC/engine/steps/review.md +++ b/doc/architecture/SPEC/engine/steps/review.md @@ -138,3 +138,23 @@ Direct 1.1 / Strict 1.3 accept typed `CarriedFinding` inputs (unique IDs, source ## 自进化接入(2026-10-04) 影子评审继承严格工具 scope;PR 文件、基础版本与历史工具只能读取冻结仓库,涉及生产写入的步骤由执行器拒绝。 + +## Independent findings and publication + +`publication.py` derives the verdict from selected findings before applying +thread suppression, the unit-test comment cap or the inline comment budget. +Current-head rechecks may contribute a confirmed carried defect. An open recheck +gap is reported and precludes an otherwise empty approval. + +`feedback.py` compares at most the latest 50 inline threads after candidate +selection. Suppression requires an active, current RIGHT-side thread at the same +path and line with matching concern text on the reviewed head. The review links +the existing thread and retains its impact in the verdict. Missing feedback and +a moved head preserve the independently selected findings. No-discussion and +isolated snapshot reviews perform no GitHub feedback lookup. + +The host verifies claim evidence against the pinned source or raw CI log +records tied to the reviewed revision. A verified acceptance requirement can +affect the verdict. When the caller requests `include_score`, missing required +artifacts zero the claim-evidence dimension. The scoring result explains a +withheld total when the head is stale or material checks remain incomplete. diff --git a/doc/architecture/SPEC/improve.md b/doc/architecture/SPEC/improve.md index 4041199ca..a943ecbfd 100644 --- a/doc/architecture/SPEC/improve.md +++ b/doc/architecture/SPEC/improve.md @@ -1,6 +1,6 @@ # improve/ —— 规范(元改进引擎) - + `设计:/data/zhoutaichang/copilot/meta-improvement-engine-design.md v1(GPT-6 sol 批准 2026-09-29) · refactor-status: building (P0–P4 已落地)` @@ -16,7 +16,8 @@ Replay envelope 保留完整文件与引用,由 TraceStore 脱敏、压缩和按内容寻址;未压缩 UTF-8 JSON 上限为 64,000,000 bytes。超限只记录 `replay_capture_deferred` 的大小、上限和摘要并抛出专用 `ReplayCaptureLimit`,不保存截断输入,也不进入 replay 数据集。知识起草无活动进化工作流时继续原生固定生成器;活动工作流(含已禁用项)缺少完整 replay 时保持事件 pending。其他捕获错误不能走此延期路径。 -`runtime.py` 重新应用补丁核验实际评估树,原子采用本地不可变 release,原生 PR 评审、知识草稿、lint 和归因在活动制品的沙箱中运行。宿主记录运行指纹才更新部署基线。首次八个不同 item 与上一版比较,七日缺证据自动恢复;保留后每周最多八个新 item 持续比较。契约、凭据/隔离/预算、指纹失败或资源显著退化自动恢复上一版;恢复制品不可验证则禁用执行。执行/切换锁及持久化激活、回滚意图支持重启恢复。 +`runtime.py` 重新应用补丁核验实际评估树,原子采用本地不可变 release,原生 PR 评审、知识草稿、lint 和归因在活动制品的沙箱中运行。PR 评分和主张证据在宿主的真实评审版本上验证,沙箱重建的 Git SHA 不作为实际 PR 的标识。 +宿主记录运行指纹才更新部署基线。首次八个不同 item 与上一版比较,七日缺证据自动恢复;保留后每周最多八个新 item 持续比较。契约、凭据/隔离/预算、指纹失败或资源显著退化自动恢复上一版;恢复制品不可验证则禁用执行。执行/切换锁及持久化激活、回滚意图支持重启恢复。 默认 `IMPROVE_EVALUATION_MODE=objective`、`IMPROVE_PROMOTION_MODE=automatic`,不要求人工标签、判官或 performance 模型。总开关仍关闭,固定模型取 `IMPROVE_EVOLVE_MODEL` 或 eco;每周一个候选、一次修复及共享 20 美元预算不变。`gold/pr` 模式保留原有双家族取证及人工流程。无隔离生产驱动的机械工作流仍可 lint,但不自动采用。当前主机命名空间关闭,代码候选实际执行延期。 diff --git a/doc/architecture/SPEC/intent.md b/doc/architecture/SPEC/intent.md index 9f8da7322..75dad22e3 100644 --- a/doc/architecture/SPEC/intent.md +++ b/doc/architecture/SPEC/intent.md @@ -1,6 +1,6 @@ # intent.py —— 规范 - + `LOC ~379 · 任务层 · refactor-status: ok` @@ -30,6 +30,8 @@ LLM 把命令(kind / pr / issue / flags)分类成 `TaskSpec`;低于置信 推理模型会先把预算花在思考上,500 的上限下它**一个 JSON 字符都吐不出来**,于是一条 完全清楚的命令被答成"I couldn't parse that"。`review/planner.py` 踩过同一个坑并定在 8000;**修复轮同样要给足**——那正是被饿死的模型会落到的地方。 +- PR 评审可以按明确请求附加数值评分,例如 `review PR 7 with a score`。 + 省略或否定评分请求时保留默认值。 - 空命令或未配置 LLM → 澄清(绝不猜测)。 - **有歧义就澄清 —— 绝不猜测**:LLM 置信度 < 0.7、显式澄清、畸形回复、未知 kind, 全都 → 澄清。 diff --git a/doc/architecture/SPEC/mcp_server.md b/doc/architecture/SPEC/mcp_server.md index 64a57ae76..76b99eca7 100644 --- a/doc/architecture/SPEC/mcp_server.md +++ b/doc/architecture/SPEC/mcp_server.md @@ -1,6 +1,6 @@ # mcp_server.py —— 规范 - + `MCP 协议适配器 · refactor-status: ok` @@ -18,7 +18,7 @@ `CopilotMCP` 是 `RunService` 的兼容别名;`build_mcp()` 注册 start/poll 工具,外加 `get_capabilities()`(包 `contract.capabilities`,含 `MAX_STRICT_WORKERS=1` 与文件锁能力上报)。`start_review` 接受 -`expected_head_sha`;`start_strict_review` 接受 `idempotency_key` 并把 +`expected_head_sha` 及默认关闭的 `include_score`;`start_strict_review` 接受 `idempotency_key` 并把 `(run_id, created)` 语义(见下)落到入队决定上。新增内部 `reserve_strict_review` 原样返回该 tuple,供 typed SDK 准确报告幂等复用; `start_strict_review` 继续只返 `run_id`,保持 MCP/既有调用兼容; diff --git a/doc/architecture/SPEC/sdk.md b/doc/architecture/SPEC/sdk.md index b4175d962..444c867a7 100644 --- a/doc/architecture/SPEC/sdk.md +++ b/doc/architecture/SPEC/sdk.md @@ -1,6 +1,6 @@ # sdk/ —— 规范 - + `Python SDK v1 · 跨仓库唯一 typed 边界 · refactor-status: ok` @@ -157,9 +157,10 @@ push、开 PR 或 schedule。ReviewBot 必须向 `KnowledgeCurator` 传 dedicated work checkout,并继续拥有重试、artifact 与本地补丁导出;SDK 也绝不写 packaged knowledge tree。自适应 DirectClient 仅管理知识上下文的运行账本,不代替知识出版治理。 -- SDK、Quality API 版本常量为 `1.0.0`;Direct 为 `1.1.0`,Strict 为 `1.4.0` +- SDK、Quality API 版本常量为 `1.0.0`;Direct 为 `1.1.0`,Strict 为 `1.5.0` (1.1 新增 `finding_dispositions`;1.2 新增 `findings`;1.3 新增显式 recheck; - 1.4 新增 `StrictRuntimeConfig.max_workers`),Knowledge 为 `1.1.0` + 1.4 新增 `StrictRuntimeConfig.max_workers`;1.5 新增 `StrictReviewRequest.include_score`, + 以及 `StrictReviewResult.review_claim_evidence` 与可选 `review_score`。读取旧结果时分别为空元组与 None),Knowledge 为 `1.1.0` (1.1 向后兼容地新增 `catalog_entries()` / `KnowledgeCatalogEntry` 与容量预检), distribution 为 `0.2.0`;`Capabilities.knowledge_api_version` 与 `supports_knowledge_curation` 组成 ReviewBot 的 paired-release 握手,避免只按 diff --git a/doc/architecture/SPEC/thin_mcp_server.md b/doc/architecture/SPEC/thin_mcp_server.md index 89235ff12..55e46bab8 100644 --- a/doc/architecture/SPEC/thin_mcp_server.md +++ b/doc/architecture/SPEC/thin_mcp_server.md @@ -1,6 +1,6 @@ # thin_mcp_server.py —— 规范 - + `LOC ~490 · 默认 MCP:Direct 门面 + Strict 入口 · refactor-status: ok` @@ -19,6 +19,7 @@ `get_workflow` / `get_update_status`。 ## 公开契约 +Strict 的 `review(..., include_score=true)` 请求参考分数,分页结果保留证据明细和可选评分。 上述工具;`build_mcp(...)`;`main()`。`review(knowledge_profile="adaptive")` 返回单一实际 `model_content` 和不重复正文的引用;默认 `legacy` 保持旧契约。 会话工具累积预算,跨仓库目标只在主机授权与 confirmed 固定依赖同时成立时可读; diff --git a/doc/guide/hosts/codex.md b/doc/guide/hosts/codex.md index d818872c8..1394256b4 100644 --- a/doc/guide/hosts/codex.md +++ b/doc/guide/hosts/codex.md @@ -161,7 +161,8 @@ Strict 会用它配置的模型运行打包好的 `pr-review` playbook,带进 - `review(target, repo?, mode="direct", post=false, title="", body="", changed_files=[], review_depth="", repo_path="", expected_head_sha="", - idempotency_key="")`:在宿主发出进度更新之后, + idempotency_key="", include_score=false)`:Strict 可按要求在结论之后给出百分制参考分数。 + 在宿主发出进度更新之后, Direct 用 title/body 返回**至多三条**精确的 owner/model 路由,各自带内嵌的精简 `quick_map` 摘录。changed files 通常只做范围校验;但当返回的路由**没有一条**命中 它们推导出的 owner 时,改由 changed files 选路,并在响应里明说 diff --git a/playbooks/pr-review.yaml b/playbooks/pr-review.yaml index 2ed7fa7e0..b5f226f66 100644 --- a/playbooks/pr-review.yaml +++ b/playbooks/pr-review.yaml @@ -21,6 +21,7 @@ requires: [repo.path] # declared adaptation surface: specs carrying only these params still resolve # as reuse (L0) — an undeclared param would demote to adapt (L1, review gate) params: + include_score: "optional boolean — report a revision-bound advisory score" review_depth: "optional light|standard|full|auto — pins the adaptive review depth for this run (see review/planner.py)" steps: diff --git a/src/infermatrix_copilot/app/request_policy.py b/src/infermatrix_copilot/app/request_policy.py index 359761b3d..2a86d22c2 100644 --- a/src/infermatrix_copilot/app/request_policy.py +++ b/src/infermatrix_copilot/app/request_policy.py @@ -30,7 +30,7 @@ # strictly value-validated below — a knob may modulate cost/depth, never widen # permissions. _ALLOWED_PARAMS: frozenset[str] = frozenset({ - "review_depth", "deterministic_signals", "carried_findings", + "review_depth", "deterministic_signals", "carried_findings", "include_score", }) _REVIEW_DEPTHS = ("auto", "light", "standard", "full") @@ -156,6 +156,11 @@ def enforce_mcp_policy(raw: dict[str, Any], *, allowed_repos: list[str], f"review_depth {params['review_depth']!r} is not one of " f"{list(_REVIEW_DEPTHS)}") params["review_depth"] = str(params["review_depth"]).lower() + if "include_score" in params: + if not isinstance(params["include_score"], bool): + raise PolicyError("include_score must be a boolean") + if kind != "pr_review" or not params["include_score"]: + params.pop("include_score") if "carried_findings" in params: if kind != "pr_review": params.pop("carried_findings") diff --git a/src/infermatrix_copilot/contract.py b/src/infermatrix_copilot/contract.py index 7f561e082..ea61d8b1f 100644 --- a/src/infermatrix_copilot/contract.py +++ b/src/infermatrix_copilot/contract.py @@ -292,6 +292,8 @@ def build_review_result(run_dir: Path | str) -> dict[str, Any]: "reviewed_head_sha": str(updates.get("pr_head_sha") or ""), "verdict": str(updates.get("review_verdict") or ""), "summary_markdown": str(updates.get("review_summary") or ""), + **{field: updates[field] for field in ("review_claim_evidence", "review_score", "review_feedback_status") + if field in updates}, "comments": sanitize_comments(updates.get("review_comments")), # Every candidate this review considered and what became of it. The # published `comments` above are the finalized set; this is the proof, diff --git a/src/infermatrix_copilot/engine/agent_runtime/ensemble.py b/src/infermatrix_copilot/engine/agent_runtime/ensemble.py index 44fe7c5e6..fe36f77f5 100644 --- a/src/infermatrix_copilot/engine/agent_runtime/ensemble.py +++ b/src/infermatrix_copilot/engine/agent_runtime/ensemble.py @@ -21,6 +21,15 @@ from .utils import _build_evidence, _to_step_result +def retain_review_assessments(previous: dict, current: dict) -> None: + """Carry investigation evidence through a zero-finding retry or escalation.""" + for key in ("claim_checks", "dimension_ratings"): + prior = previous.get(key) + if isinstance(prior, list) and prior: + latest = current.get(key) + current[key] = prior + (latest if isinstance(latest, list) else []) + + def outcome_blocked(result: Any, output: dict | None) -> bool: """True when a pass returned nothing usable — no items and no tool work. @@ -278,6 +287,7 @@ def _member_died(phase: str, reason: str) -> None: effect="routed seat produced no output; retrying on " + (f"the same route (model={member})" if route else "the tier model (member proven dead)")) + first_output = output or {} retry_guidance = lens_guidance + ( "\n\nYour first pass produced NO USABLE FINAL — most " "likely it ran past the reply ceiling. Investigate less " @@ -308,6 +318,7 @@ def _member_died(phase: str, reason: str) -> None: route = {} result, output = await _attempt("/retry/tier", retry_guidance, route) + retain_review_assessments(first_output, output) return str(lens["name"]), result, output # lenses (and repeat samples of each lens — a single sample's item list is @@ -374,7 +385,8 @@ def _dedup_union(key: str) -> list: that the reducer does not judge.""" out, seen = [], set() for _, o in samples: - for v in o.get(key) or []: + values = o.get(key) + for v in values if isinstance(values, list) else []: sig = json.dumps(v, ensure_ascii=False, sort_keys=True) \ if isinstance(v, (dict, list)) else str(v) if sig not in seen: @@ -389,6 +401,11 @@ def _dedup_union(key: str) -> list: for key in ("findings", "files_read", "files_modified", "tests_requested", "tests_run", "assumptions", "blockers"): merged[key] = _dedup_union(key) + for key in ("claim_checks", "dimension_ratings"): + if key in (output_extension or {}): + merged[key] = _dedup_union(key) + if "claim_checks" in (output_extension or {}): + merged["_assessment_incomplete"] = any(not result.ok for _, result, _ in runs) # the reducer judges ITEMS, not the step: models conflate the step's status # with the reviewed artifact's verdict, so status comes from the samples if any(o.get("status") == "success" for _, o in samples): diff --git a/src/infermatrix_copilot/engine/steps/_common.py b/src/infermatrix_copilot/engine/steps/_common.py index 3163ac1bb..be6ab153a 100644 --- a/src/infermatrix_copilot/engine/steps/_common.py +++ b/src/infermatrix_copilot/engine/steps/_common.py @@ -164,7 +164,7 @@ def git(repo: Path, *args: str, timeout: int = 120) -> tuple[int, str]: return out.returncode, (out.stdout + out.stderr).strip() -def gh_read_tools(repo: Path | None) -> dict: +def gh_read_tools(repo: Path | None, *, issue_comments: bool = True) -> dict: """Read-only gh tools for agent steps (int-coerced args — no injection).""" from ...tools import ToolDef @@ -184,7 +184,7 @@ def gh_pr_view(pr, **_: object) -> str: def gh_issue_view(issue, **_: object) -> str: """Tool handler: return issue `issue`'s title/body/labels/comments as JSON text.""" - return _view("issue", issue, "title,body,labels,comments") + return _view("issue", issue, "title,body,labels,comments" if issue_comments else "title,body,labels") def gh_ci_read(pr, **_: object) -> str: """Tool handler: return PR `pr`'s CI checks (name/state/bucket) as JSON diff --git a/src/infermatrix_copilot/engine/steps/pr/fetch.py b/src/infermatrix_copilot/engine/steps/pr/fetch.py index 0038ff3c9..6ee9c9aef 100644 --- a/src/infermatrix_copilot/engine/steps/pr/fetch.py +++ b/src/infermatrix_copilot/engine/steps/pr/fetch.py @@ -223,15 +223,18 @@ def _clip(text: str, n: int = 700) -> str: def _pr_context_bundle(ctx: StepContext, repo: str, pr: int) -> str: """Assemble the PR-side evidence bundle (design W1): title/body/labels always; discussion comments, review summaries, and inline review comments - only in `pr_context_mode=full` (the eval-leakage policy: the frozen + only for PR quality tasks in `pr_context_mode=full` (the frozen dataset's ground truth IS the human review discussion, so arm runs export PR_CONTEXT_MODE=no_discussion); linked issues (fixes/closes #N in body or branch name, capped 2) in both modes. Every sub-fetch failure degrades to a note — this bundle must never block the review.""" mode = str(getattr(ctx.settings, "pr_context_mode", "full") or "full") + include_discussion = mode == "full" and (ctx.state.get("task_spec") or {}).get("kind") == "pr_quality" + fields = "title,body,labels,headRefName,commits" + if include_discussion: + fields += ",comments,reviews" parts: list[str] = [] - code, out = _gh(["pr", "view", str(pr), "--json", - "title,body,labels,headRefName,comments,reviews,commits"], + code, out = _gh(["pr", "view", str(pr), "--json", fields], cwd=repo) data: dict = {} if code == 0: @@ -258,7 +261,7 @@ def _pr_context_bundle(ctx: StepContext, repo: str, pr: int) -> str: if subjects: parts.append("## Commit timeline (subjects only — the diff below " "is the squashed net change)\n" + "\n".join(subjects)) - if mode == "full" and data: + if include_discussion and data: comments = [f"@{c.get('author', {}).get('login', '?')}: {_clip(c.get('body'))}" for c in _last_n(data.get("comments") or [])] if comments: @@ -466,6 +469,7 @@ async def _pr_fetch_diff(ctx: StepContext) -> StepResult: # partial bundle on any sub-fetch failure; never blocks the run. pr_context = _pr_context_bundle(ctx, repo, int(pr)) ctx.state["pr_context"] = pr_context + ctx.state["pr_context_independent"] = spec.get("kind") != "pr_quality" ctx.state["repo_path"] = wt_path ctx.state["checkout_note"] = note return StepResult( @@ -473,6 +477,7 @@ async def _pr_fetch_diff(ctx: StepContext) -> StepResult: summary=f"fetched PR #{pr} diff ({len(out)} chars{diff_note}, context " f"{len(pr_context)} chars); {note.split(' — ')[0]}", outputs={"state_updates": {"diff_text": out, "pr_context": pr_context, + "pr_context_independent": ctx.state["pr_context_independent"], "repo_path": wt_path, "checkout_note": note, "pr_head_sha": head_sha, diff --git a/src/infermatrix_copilot/engine/steps/review/claim_evidence.py b/src/infermatrix_copilot/engine/steps/review/claim_evidence.py new file mode 100644 index 000000000..f7a06535f --- /dev/null +++ b/src/infermatrix_copilot/engine/steps/review/claim_evidence.py @@ -0,0 +1,384 @@ +"""Ground Strict review assessments in immutable source and raw run records.""" + +from __future__ import annotations + +import asyncio +import io +import tokenize +from functools import lru_cache +from pathlib import Path +import re +import subprocess +import tempfile + +from ....tools import ToolDef +from .._common import gh, git, repo_path +from ..pr import fetch +from .repo_tools import _safe_rel_path +from .utils import _review_verdict + + +WEIGHTS = {"scope": 15, "correctness": 25, "validation": 20, "claim_evidence": 30, "simplicity": 10} +CLAIMS = """list of {claim, status, reason, kind, records}. Check each acceptance claim and every +required output separately even when there are no review findings. kind=source|runtime. +For verified source behavior cite records [{path,quote}] with an exact decisive source line. +For observed runtime behavior cite a raw CI record {job_id,quote} from read_review_ci, or a +committed raw output {path,quote,run_sha,revision_quote} whose revision_quote line identifies the +producing revision. Check real outputs (including media when required), workload/config and both +sides of comparisons; an attachment URL, hash, screenshot of metrics or a green badge alone is +insufficient. For a comparison set comparison=true and mark each reference role=baseline|head. +If repository acceptance explicitly requires the missing artifact, cite acceptance_path and +acceptance_quote from the governing policy at the base; otherwise report the verification gap. +For a missing tracked artifact use status=missing and {path,requirement_path,requirement_quote} +with the required repository location documented in the quoted requirement. For an identified CI +job whose log cannot be retrieved use status=inaccessible with {job_id}. For a wrong-run record use status=mismatched and cite its revision. +Use unverified for checks you could not perform, including unsupported media or links. +Use a single not_applicable row with rationale only when there is no applicable claim.""" +RATINGS = """list of {dimension,rating,reason,path,quote}. Assess scope, correctness, validation, +claim_evidence and simplicity exactly once, even on a clean review. Rate 3 = matching evidence +throughout, 2 = bounded gap, 1 = material gap with some support, 0 = no usable support or a +material contract violation. Cite a decisive line in the frozen source. Use N/A only if outside +scope; use unverified for incomplete review. Explain each judgment, required artifacts, and +contributor vs reviewer checks. Never calculate a total. If a trusted repo rule zeroes simplicity +for an introduced explanatory comment, cite policy_path, policy_quote at the base and quote +the added comment at path; check exceptions and scope. Set comment_penalty=true only then.""" + + +def _text(value): + return value.strip() if isinstance(value, str) else "" + + +def _sha(value): + return bool(re.fullmatch(r"[a-fA-F0-9]{40}|[a-fA-F0-9]{64}", _text(value))) + + +class ReviewRecords: + """Resolve model citations against this review's repository and pinned revisions.""" + + def __init__(self, repo: Path | None, head: str, base: str, live: bool): + self.repo, self.head, self.base, self.live = repo, head, base, live + self.job_revision = lru_cache(maxsize=None)(self._job_revision) + self.job_line = lru_cache(maxsize=None)(self._job_line) + + def _job_revision(self, job_id): + if not self.repo or not self.live or type(job_id) is not int or job_id < 1: + return "" + try: + rc, sha = gh(["api", f"repos/{{owner}}/{{repo}}/actions/jobs/{job_id}", + "--jq", ".head_sha"], cwd=self.repo) + return sha.strip() if not rc and _sha(sha) else "" + except (OSError, subprocess.SubprocessError): + return "" + + def _job_line(self, job_id, needle): + if not self.job_revision(job_id) or not needle: + return "unverified", "" + with tempfile.TemporaryFile() as log: + try: + run = subprocess.run( + ["gh", "api", f"repos/{{owner}}/{{repo}}/actions/jobs/{job_id}/logs"], + cwd=self.repo, stdout=log, stderr=subprocess.PIPE, timeout=120) + except (OSError, subprocess.SubprocessError): + return "unverified", "" + if run.returncode: + error = run.stderr.lower() + expired = b"http 404" in error or b"http 410" in error or b"log has expired" in error + return ("inaccessible" if expired else "unverified"), "" + log.seek(0) + for raw in log: + line = raw.decode("utf-8", errors="replace").strip() + if needle in line: + return "verified", line + return "unverified", "" + + def log_tool(self): + def read_review_ci(job_id: int, contains: str): + if type(job_id) is not int or not _text(contains): + return "Supply the job id and a nonempty literal search string." + revision = self.job_revision(job_id) + _, line = self.job_line(job_id, contains) + return f"Job {job_id} at {revision}: {line}" if line else "No matching raw log line." + return ToolDef("read_review_ci", "Read a matching raw Actions job log line and its producing commit.", + {"type": "object", "properties": {"job_id": {"type": "integer"}, + "contains": {"type": "string"}}, "required": ["job_id", "contains"]}, + read_review_ci) + + def tracked(self, sha, path, quote=None): + if not self.repo or not _sha(sha) or not _text(path) or "\0" in path: + return None + try: + path = _safe_rel_path(path) + rc, out = git(self.repo, "--literal-pathspecs", "ls-tree", sha, "--", path) + if rc: + return None + if not out: + return False + if not out.startswith(("100644 blob ", "100755 blob ")): + return None + if quote is None: + return True + if not _text(quote) or "\0" in quote: + return None + lines = quote.splitlines() + if len(lines) == 1: + rc, _ = git(self.repo, "--literal-pathspecs", "grep", "-I", "-q", "-F", "-e", quote, + sha, "--", path) + return rc == 0 if rc in (0, 1) else None + rc, text = git(self.repo, "--literal-pathspecs", "grep", "-I", "-h", "-F", "-A", + str(len(lines) - 1), "-e", lines[0], sha, "--", path) + return rc == 0 and quote in text + except (ValueError, OSError, subprocess.SubprocessError): + return None + + def match(self, record, kind): + if not isinstance(record, dict): + return "unverified" + path, quote = record.get("path"), record.get("quote") + expected = self.base if record.get("role") == "baseline" else self.head + if not _sha(expected): + return "unverified" + if kind not in ("source", "runtime"): + return "unverified" + if type(record.get("job_id")) is int: + actual = self.job_revision(record["job_id"]) + if _sha(actual) and actual != expected: + return "mismatched" + if actual != expected: + return "unverified" + status, _ = self.job_line(record["job_id"], _text(quote) or " ") + if not _text(quote) and status == "verified": + return "unverified" + return status + if self.tracked(expected, path, quote) is not True or not _text(quote): + return "unverified" + if kind == "source": + return "verified" + actual, line = record.get("run_sha"), record.get("revision_quote") + if _sha(actual) and actual in _text(line) and self.tracked(expected, path, line): + return "verified" if actual == expected else "mismatched" + return "unverified" + + +def assess_claims(proposals, records): + rows = [] + for row in proposals if isinstance(proposals, list) else []: + if not isinstance(row, dict) or not _text(row.get("claim")) or not _text(row.get("reason")): + rows.append({"claim": "Claim verification", "status": "unverified", "reason": "Malformed claim assessment."}) + continue + status, refs = row.get("status"), row.get("records") + refs = refs if isinstance(refs, list) else [] + failed_paths = [] + if status == "missing": + failed_paths = [ref["path"] for ref in refs if ( + isinstance(ref, dict) and _text(ref.get("path")) + and ref["path"] in _text(ref.get("requirement_quote")) + and records.tracked(records.head, ref.get("requirement_path"), ref["requirement_quote"]) is True + and records.tracked(records.head, ref["path"]) is False + )] + status = "missing" if failed_paths else "unverified" + elif status in ("verified", "mismatched", "inaccessible"): + checks = [records.match(ref, row.get("kind")) for ref in refs] + failed_paths = [_text(ref.get("path")) for ref, check in zip(refs, checks) + if isinstance(ref, dict) and check in ("inaccessible", "mismatched")] + roles = {_text(r.get("role", "head")) for r in refs if isinstance(r, dict)} + if "mismatched" in checks: + status = "mismatched" + elif "inaccessible" in checks: + status = "inaccessible" + elif (status != "verified" or not checks or "head" not in roles + or row.get("comparison") is True and "baseline" not in roles + or any(c != "verified" for c in checks)): + status = "unverified" + elif status != "not_applicable": + status = "unverified" + result = {"claim": row["claim"], "reason": row["reason"], "status": status, + "records": refs} + if status == "unverified" and row.get("status") != status: + result["reason"] = "The cited evidence could not be confirmed at the reviewed revision." + policy = _text(row.get("acceptance_path")) + statement = _text(row.get("acceptance_quote")) + if (status in ("missing", "inaccessible", "mismatched") and statement + and _policy_path(policy, "", records) and records.tracked(records.base, policy, statement) + and any(_requires_path(statement, path) for path in failed_paths if path)): + result.update(acceptance_path=policy, acceptance_quote=statement) + if result not in rows: + rows.append(result) + applicable = [r for r in rows if r["status"] != "not_applicable"] + return applicable or rows[:1] or [{"claim": "Claim verification", "status": "unverified", + "reason": "The investigation returned no claim assessment."}] + + +def score_review(proposals, claims, records, *, gap="", diff=""): + dimensions = {} + points = applicable_weight = 0 + for key, weight in WEIGHTS.items(): + candidates = [] + for row in proposals if isinstance(proposals, list) else []: + if not isinstance(row, dict) or row.get("dimension") != key or not _text(row.get("reason")): + continue + rating = row.get("rating") + if not (type(rating) is int and 0 <= rating <= 3 or rating == "N/A"): + continue + if records.tracked(records.head, row.get("path"), row.get("quote")) is not True or not _text(row.get("quote")): + continue + if key == "simplicity" and row.get("comment_penalty") is True: + rule = _text(row.get("policy_quote")) + if not (re.search(r"simplicity", rule, re.I) and re.search(r"comments?", rule, re.I) + and re.search(r"\b0\s*/\s*3\b", rule) + and _policy_path(row.get("policy_path"), row["path"], records) + and records.tracked(records.base, row.get("policy_path"), rule) + and _introduced_comment(records, diff, row["path"], row["quote"])): + continue + rating = 0 + candidates.append({"rating": rating, "reason": row["reason"], "path": row["path"], "quote": row["quote"]}) + assessed = [r for r in candidates if type(r["rating"]) is int] + dimension = min(assessed, key=lambda r: r["rating"]) if assessed else next(iter(candidates), {}) + statuses = {r["status"] for r in claims} + if key == "claim_evidence": + if statuses.intersection({"missing", "mismatched", "inaccessible"}): + dimension = {"rating": 0, "reason": "Required artifact missing, inaccessible, or tied to a different revision."} + elif statuses == {"not_applicable"}: + dimension = {"rating": "N/A", "reason": claims[0]["reason"]} + elif dimension.get("rating") == "N/A": + dimension = {} + if not dimension: + dimension = {"rating": "unverified", "reason": "No supported assessment."} + gap = gap or f"{key} is unassessed." + dimensions[key] = {**dimension, "weight": weight} + if type(dimension["rating"]) is int: + applicable_weight += weight + points += weight * dimension["rating"] + if any(row["status"] == "unverified" for row in claims): + gap = gap or "Claim verification is incomplete." + if not applicable_weight: + gap = gap or "No applicable dimensions." + denominator = 3 * applicable_weight + return {"total": None if gap else (200 * points + denominator) // (2 * denominator), + "reason": gap, "dimensions": dimensions, "applicable_weight": applicable_weight, + "reviewed_head_sha": records.head, "base_sha": records.base} + + +def _requires_path(statement, path): + flat = " ".join(statement.casefold().split()) + if re.search(r"\b(not|never|unless|optional|recommend(?:ed)?)\b", flat): + return False + artifact = re.escape(path.casefold()) + obligation = r"(?:requires?|must (?:include|produce|attach|provide|retain)|shall (?:include|provide))" + return bool(re.search(rf"\b{obligation}\s+(?:the\s+)?`?{artifact}(?:`|\b)", flat) + or re.search(rf"{artifact}`? (?:is required|must be (?:included|present|provided))\b", flat)) + + +def _policy_path(path, target, records): + path = _text(path) + if Path(path).name in ("AGENTS.md", "CLAUDE.md"): + return "/" not in path or target.startswith(str(Path(path).parent) + "/") + if path.lower() in {"contributing.md", ".github/contributing.md", "docs/contributing.md"}: + return True + match = re.fullmatch(r"((?:\.agents|\.claude)/skills/(?:review-pr|imreview))/(.+)", path) + if not match: + return False + folder, relative = match.groups() + return relative == "SKILL.md" or records.tracked(records.base, folder + "/SKILL.md", f"({relative})") is True + + +def _explanatory_comment(line): + text = line.strip() + match = re.search(r"(?:^|\s)(#|//|/\*|--|\*)\s*(.*)$", text) + if not match: + return False + return not re.match(r"(?:!|SPDX|copyright|coding[:=]|noqa|type:|fmt:|ruff:|pylint:|" + r"pragma|nosec|shellcheck|eslint|prettier|include|define|if(?:def|ndef)?\b|endif\b)", + match[2], re.I) + + +def _introduced_comment(records, diff, path, quote): + if not _explanatory_comment(quote) or not _added_line(diff, path, quote): + return False + if not path.endswith((".py", ".pyi")): + return Path(path).suffix.lower() not in (".md", ".rst", ".txt") + try: + code, source = git(records.repo, "show", f"{records.head}:{path}") + if code: + return False + return any(token.type == tokenize.COMMENT and token.line.strip() == quote.strip() + for token in tokenize.generate_tokens(io.StringIO(source).readline)) + except (OSError, subprocess.SubprocessError, tokenize.TokenError, IndentationError): + return False + + +def _added_line(diff, path, quote): + current = "" + for line in diff.splitlines(): + if line.startswith("diff --git "): + current = "" + if line.startswith("+++ b/"): + current = line[6:] + elif current == path and line.startswith("+") and line[1:].strip() == quote.strip(): + return True + return False + + +async def score_freshness(ctx): + head = _text(ctx.state.get("pr_head_sha")) + if not _sha(head): + return "The reviewed head is unknown." + if ctx.state.get("review_observed_stale_head"): + return "The PR head moved." + if getattr(ctx.settings, "pr_context_source", "live") == "snapshot": + return "" + repo = repo_path(ctx) + pr = (ctx.state.get("task_spec") or {}).get("pr") + if not repo or not pr: + return "The current PR head could not be confirmed." + try: + _, current, _ = await asyncio.to_thread(fetch._resolve_pr_head, repo, pr) + except (OSError, subprocess.SubprocessError): + current = "" + if not _sha(current): + return "The current PR head could not be confirmed." + if current != head: + ctx.trace.record("expected_head_mismatch", pr=pr, expected=head, actual=current, step="agent.review_diff") + return "The PR head moved." + return "" + + +async def apply_review_evidence(ctx, output, updates, *, partial=False, records=None): + records = records or ReviewRecords(repo_path(ctx), ctx.state.get("pr_head_sha", ""), + ctx.state.get("pr_base_sha", ""), getattr(ctx.settings, "pr_context_source", "live") != "snapshot") + claims = await asyncio.to_thread(assess_claims, output.get("claim_checks"), records) + updates["review_claim_evidence"] = claims + text = ["Claim evidence"] + for row in claims: + refs = [str(r.get("path") or f"Actions job {r['job_id']}") for r in row.get("records", []) + if isinstance(r, dict) and (_text(r.get("path")) or type(r.get("job_id")) is int)] + citations = " (" + ", ".join(refs) + ")" if refs else "" + text.append(f"- {row['status']} · {row['claim']} — {row['reason']}{citations}") + if (ctx.state.get("task_spec", {}).get("params") or {}).get("include_score") is True: + gap = "Part of the investigation was incomplete." if partial or output.get("_assessment_incomplete") else "" + score = await asyncio.to_thread(score_review, output.get("dimension_ratings"), claims, records, + gap=gap, diff=ctx.state.get("diff_text", "")) + freshness = await score_freshness(ctx) + if freshness: + score.update(total=None, reason=freshness) + updates["review_score"] = score + label = f"{score['total']}/100" if score["total"] is not None else f"withheld ({score['reason']})" + text += ["", f"Advisory score · {label} (applicable weight {score['applicable_weight']}/100)", + f"Base {records.base or 'unknown'} · head {records.head or 'unknown'}"] + for key, entry in score["dimensions"].items(): + rating = entry["rating"] + value = f"{rating}/3" if type(rating) is int else rating + source = f" ({entry['path']})" if entry.get("path") else "" + text.append(f"- {key} · {value} · {entry['reason']}{source}") + if any("acceptance_quote" in row for row in claims): + updates["review_verdict"] = _review_verdict([{"severity": "blocker"}], ctx.state.get("pr_state", "")) + text += [f"- Required by {r['acceptance_path']}: {r['acceptance_quote']}" + for r in claims if "acceptance_quote" in r] + for field in ("review_text", "review_summary"): + body = str(updates.get(field) or "").rstrip() + verdict = updates.get("review_verdict") + if verdict: + body = re.sub(r"(?:^|\n)\*\*Verdict:\*\* [^\n]*$", "", body).rstrip() + sections = [body, "\n".join(text)] + if verdict: + sections.append(f"**Verdict:** {verdict}") + updates[field] = "\n\n".join(part for part in sections if part) diff --git a/src/infermatrix_copilot/engine/steps/review/feedback.py b/src/infermatrix_copilot/engine/steps/review/feedback.py new file mode 100644 index 000000000..f1f55439e --- /dev/null +++ b/src/infermatrix_copilot/engine/steps/review/feedback.py @@ -0,0 +1,77 @@ +"""Compare independently selected findings with active, same-head inline threads.""" +from __future__ import annotations + +import json +import re +import subprocess + +from .._common import gh, repo_path +from .anchor import normalize_path + + +_THREADS = """ +query($owner:String!, $repo:String!, $pr:Int!) { + repository(owner:$owner, name:$repo) { pullRequest(number:$pr) { + headRefOid + reviewThreads(last:50) { nodes { + isResolved isOutdated path line diffSide + comments(first:1) { nodes { body url } } + } } + } } +} +""" + + +def independent_context(text: str) -> str: + """Older checkpoints stored reviewer discussion after the PR description.""" + sections = re.split(r"(?m)(^## (?:PR discussion \(do not repeat these concerns — build on or extend them\)" + r"|Review summaries|Inline review comments|Linked issue #[0-9]+:[^\n]*)$)", text) + kept = [sections[0]] + for header, content in zip(sections[1::2], sections[2::2]): + if header.startswith("## Linked issue #"): + kept.extend((header, content)) + return "".join(kept).rstrip() + + +def existing_threads(ctx, pr, head): + """Index active RIGHT-side roots by path, line, and exact concern text.""" + if ctx.settings.pr_context_mode == "no_discussion": + return {}, "disabled" + if (not head or not pr or not repo_path(ctx) or ctx.settings.improve_shadow + or ctx.settings.pr_context_source == "snapshot"): + return {}, "unavailable" + try: + code, response = gh(["api", "graphql", "-f", f"query={_THREADS}", "-F", "owner={owner}", + "-F", "repo={repo}", "-F", f"pr={int(pr)}"], cwd=repo_path(ctx)) + if code: + return {}, "unavailable" + pull = json.loads(response)["data"]["repository"]["pullRequest"] + if pull["headRefOid"] != head: + return {}, "stale" + threads = {} + for node in pull["reviewThreads"]["nodes"]: + if node["isResolved"] is not False or node["isOutdated"] is not False or node["diffSide"] != "RIGHT": + continue + roots = node["comments"]["nodes"] + if not roots or type(node["line"]) is not int: + continue + if not isinstance(roots[0].get("body"), str): + continue + body = roots[0]["body"].strip() + # The publisher formats severity and appends its evidence after the finding. + formatted = re.match(r"^\*\*\[(?:blocker|major|minor|nit)\]\*\* ", body) + if formatted: + body = body[formatted.end():].partition("\n\nEvidence: ")[0] + key = (node["path"], node["line"], body) + threads[key] = roots[0]["url"] + return threads, "checked" + except (KeyError, TypeError, ValueError, OSError, subprocess.SubprocessError): + return {}, "unavailable" + + +def match_thread(finding, threads): + line = finding.get("line") + if type(line) is not int or finding.get("_anchor_unverified") or not str(finding.get("evidence") or "").strip(): + return None + key = (normalize_path(finding.get("file")), line, str(finding.get("comment") or "").strip()) + return threads.get(key) diff --git a/src/infermatrix_copilot/engine/steps/review/prompts.py b/src/infermatrix_copilot/engine/steps/review/prompts.py index 0bdb970b8..56c29edea 100644 --- a/src/infermatrix_copilot/engine/steps/review/prompts.py +++ b/src/infermatrix_copilot/engine/steps/review/prompts.py @@ -14,11 +14,9 @@ _REVIEW_SYSTEM = """You review pull requests like an engaged maintainer: grounded, \ specific, and useful — real reviewers leave nits and doc asks, not just blockers. -The `pr_context` evidence (when present) carries the PR description, discussion, and \ -linked issues: treat the description + linked issues as the acceptance criteria the \ -diff must satisfy (scope dropped from the description is a finding). DO NOT repeat \ -concerns maintainers already raised in the discussion — build on or extend them, or \ -stay silent on that point. Verifying that a hunk does what it says is the FLOOR, not \ +Use the PR description and linked issues as the acceptance criteria. Independently \ +verify concerns at the pinned head and freeze findings before comparing prior feedback. \ +Verifying that a hunk does what it says is the FLOOR, not \ the review: a hunk that narrows, gates, or fixes an earlier problem usually leaves \ residual risk — interrogate the residual (other batch sizes, other platforms, other \ launch paths, other models sharing the code) instead of recording the fix as \ diff --git a/src/infermatrix_copilot/engine/steps/review/publication.py b/src/infermatrix_copilot/engine/steps/review/publication.py new file mode 100644 index 000000000..4a4071485 --- /dev/null +++ b/src/infermatrix_copilot/engine/steps/review/publication.py @@ -0,0 +1,116 @@ +"""Finalize independent Strict findings against the pinned host context.""" +from __future__ import annotations + +import asyncio + +from ....ut_coverage import CoverageReport, PublicDef, cap_gap_comments +from .anchor import resolve_review_comments +from .feedback import existing_threads, match_thread +from .utils import ( + _SEVERITY_ORDER, _render_review_md, _render_review_summary, _review_verdict, + disposition_records, finalize_review_dispositions, +) + + +async def finalize_review_publication(ctx, packet, carried, rechecks, recheck_missing): + """Apply thread suppression and output budgets after substantive selection.""" + diff = ctx.state.get("diff_text") or "" + pr_state = str(ctx.state.get("pr_state") or "") + output = {key: packet.get(key) for key in ("review_comments", "findings", "summary")} + ut_report = CoverageReport(candidates=[PublicDef(**row) for row in packet["ut_candidates"]]) + all_candidates, anchor_stats = resolve_review_comments( + [c for c in (output.get("review_comments") or []) if isinstance(c, dict)], str(diff)) + output["review_comments"] = all_candidates + ctx.trace.record("anchor_resolution", **anchor_stats) + substantive_findings, withheld = finalize_review_dispositions(output) + titles = {row["finding_id"]: row for row in carried} + active = [] + review_notes = [] + for check in rechecks: + original = titles[check["finding_id"]] + if check["outcome"] == "still_affected": + active.append({"severity": original.get("severity"), "evidence": check["evidence"]}) + review_notes.append(f"Still affected: {original['title']} — {check['evidence']}") + elif check["outcome"] == "unverified": + review_notes.append(f"Recheck unverified: {original['title']}") + review_notes.extend(recheck_missing) + verdict = _review_verdict([*substantive_findings, *active], pr_state) + if review_notes and verdict == "APPROVE": + verdict = "COMMENT" + output["_recheck_notes"] = review_notes + if review_notes: + output["summary"] = "" + existing = {} + feedback_status = "not_needed" + if substantive_findings: + threads, feedback_status = await asyncio.to_thread( + existing_threads, ctx, (ctx.state.get("task_spec") or {}).get("pr"), ctx.state.get("pr_head_sha")) + for finding in substantive_findings: + thread = match_thread(finding, threads) + if thread: + existing[id(finding)] = thread + published = [c for c in substantive_findings if id(c) not in existing] + output["_existing_findings"] = [ + {**c, "thread_url": existing[id(c)]} for c in substantive_findings if id(c) in existing + ] + output["_feedback_status"] = feedback_status + # at most three untested-function comments; the rest are named, not lost + published, ut_dropped = cap_gap_comments(published, ut_report) + output["review_comments"] = published + output["_withheld_findings"] = withheld + comments = sorted(output.get("review_comments") or [], + key=lambda c: (_SEVERITY_ORDER.get( + str(c.get("severity", "minor")).lower(), 2), + -len(c.get("corroborated_by") or []))) + for c in comments: + c.pop("corroborated_by", None) + output["review_comments"] = comments[:8] + final_selection = [ + (c.get("file"), c.get("line"), c.get("comment"), c.get("severity")) + for c in output["review_comments"] + ] + if sorted(map(tuple, packet["draft_selection"]), key=repr) != sorted(final_selection, key=repr): + # The reducer's prose describes its draft selection. After promotion, + # verification or a budget cut it may contradict the published set. + # Let the renderer derive a truthful summary from the final comments. + output["summary"] = "" + if ut_dropped: + output["summary"] = (str(output.get("summary") or "").rstrip() + + "\n\nAlso without a unit test: " + + ", ".join(f"`{n}`" for n in ut_dropped) + ".").lstrip() + # Recorded AFTER the cut: a candidate the review chose to publish but the + # budget dropped is `over_budget`, never `excluded`. A consumer checking + # that no withheld finding was published must not trip over a healthy + # review whose ninth comment simply did not fit. + output["_finding_dispositions"] = disposition_records( + all_candidates, output["review_comments"], existing) + if withheld or existing: + ctx.trace.record( + "finding_dispositions", + withheld=len(withheld) + len(existing), + published=len(output["review_comments"]), + dispositions=[r["disposition"] + for r in output["_finding_dispositions"]], + ) + rich = sum(1 for c in comments[:8] + if _SEVERITY_ORDER.get(str(c.get("severity", "minor")).lower(), + 2) <= _SEVERITY_ORDER["major"]) >= 2 + # Overflow renders on evidence-rich reviews (unchanged), and ALSO for any + # cut comment the verify pass individually CONFIRMED on the tree — wave-2 + # forensics measured three verify-confirmed findings (one echoing the GT + # thread) silently dying here because the kept eight were minors and the + # rich gate never opened. A confirmed tail is evidence, not noise; the + # unverified tail still renders only on rich reviews. + output["_review_overflow"] = [ + c for c in comments[8:] + if _SEVERITY_ORDER.get(str(c.get("severity", "minor")).lower(), 2) + <= _SEVERITY_ORDER["minor"] + and (rich or c.get("_verified"))][:4] + return { + "review_text": _render_review_md(output, pr_state, verdict=verdict), + "review_summary": _render_review_summary(output, pr_state, verdict=verdict), + "review_comments": output["review_comments"], + "review_verdict": verdict, + "review_finding_dispositions": output["_finding_dispositions"], + "review_feedback_status": feedback_status, + } diff --git a/src/infermatrix_copilot/engine/steps/review/refinement.py b/src/infermatrix_copilot/engine/steps/review/refinement.py index 9af2b8832..23b336d0e 100644 --- a/src/infermatrix_copilot/engine/steps/review/refinement.py +++ b/src/infermatrix_copilot/engine/steps/review/refinement.py @@ -328,6 +328,11 @@ async def _second_round(ctx: StepContext, output: dict, common: dict, ("[validated]", "[resolved]", "[claim-", "[sweep]", "[upstream-verify]"))] out2 = dict(output) + for key in ("claim_checks", "dimension_ratings"): + values = (extra or {}).get(key) + if isinstance(values, list): + previous = output.get(key) + out2[key] = (previous if isinstance(previous, list) else []) + values if new_comments: out2["review_comments"] = list( output.get("review_comments") or []) + new_comments diff --git a/src/infermatrix_copilot/engine/steps/review/steps.py b/src/infermatrix_copilot/engine/steps/review/steps.py index 8a555f6f5..62cf7db06 100644 --- a/src/infermatrix_copilot/engine/steps/review/steps.py +++ b/src/infermatrix_copilot/engine/steps/review/steps.py @@ -15,17 +15,19 @@ import json import re import subprocess -from dataclasses import replace +from dataclasses import asdict, replace from pathlib import Path from ....review.planner import DEFAULT_STANDARD_LENSES, DEPTHS, plan_review from ....ut_coverage import UTCoverageRules, analyze as _ut_analyze -from ....ut_coverage import cap_gap_comments, render as _ut_render +from ....ut_coverage import render as _ut_render from ...step import FailureKind, StepContext, StepResult from .._common import gh_read_tools as _gh_read_tools from .._common import repo_path as _repo_path from .._common import step -from .anchor import resolve_review_comments +from .claim_evidence import CLAIMS, RATINGS, ReviewRecords, apply_review_evidence +from .feedback import independent_context +from .publication import finalize_review_publication from .repo_tools import review_repo_tools from .refinement import refine_review from .prompts import ( @@ -36,15 +38,7 @@ _REVIEW_MERGE, _REVIEW_SYSTEM, ) -from .utils import ( - _SEVERITY_ORDER, - _render_review_md, - _render_review_summary, - _review_verdict, - disposition_records, - finalize_review_dispositions, - _sweep_targets, -) +from .utils import _sweep_targets # Planner causes that are NOT a capability gap: no client configured at all, and @@ -158,6 +152,9 @@ async def _review_diff(ctx: StepContext) -> StepResult: ctx.trace.record("review_ut_candidates", step="agent.review_diff", **ut_report.to_dict()) + pr_context = str(ctx.state.get("pr_context") or "") + if not ctx.state.get("pr_context_independent"): + pr_context = independent_context(pr_context) common = dict( step_name="agent.review_diff", purpose=f"Review PR #{spec.get('pr')} like an engaged maintainer: " @@ -167,7 +164,7 @@ async def _review_diff(ctx: StepContext) -> StepResult: "evidence/disposition; APPROVE-equivalent = empty " "review_comments with a summary.", evidence={"pr_diff": str(diff), - "pr_context": ctx.state.get("pr_context", ""), + "pr_context": pr_context, "gate_report": ctx.state.get("gate_report", ""), "sweep_targets": _sweep_targets(str(diff), language), "changed_symbol_consumers": await asyncio.to_thread( @@ -183,9 +180,25 @@ async def _review_diff(ctx: StepContext) -> StepResult: "no_issue — only publish is published, kind: " "optional, `untested_api` only for a missing unit " "test on a listed untested-function candidate}"}, - extra_tools={**_gh_read_tools(_repo_path(ctx)), + extra_tools={**_gh_read_tools(_repo_path(ctx), issue_comments=False), **review_repo_tools(_repo_path(ctx), str(ctx.state.get('pr_base_sha') or ''))}, ) + records = ReviewRecords(_repo_path(ctx), ctx.state.get("pr_head_sha", ""), + ctx.state.get("pr_base_sha", ""), + getattr(ctx.settings, "pr_context_source", "live") != "snapshot") + if records.repo and records.live: + common["extra_tools"]["read_review_ci"] = records.log_tool() + common["output_extension"]["claim_checks"] = CLAIMS + common["guidance"] += ( + "\nInvestigate the PR's acceptance claims and report claim_checks independently of " + "review_comments. A breached acceptance requirement belongs in the usual findings. " + "Verify applicable outputs and matching raw records at the pinned revision. " + "Issues, comments and CI badges alone do not establish a measured result." + ) + common["evidence"]["review_revisions"] = f"Base: {records.base}\nHead: {records.head}" + if (spec.get("params") or {}).get("include_score") is True: + common["output_extension"]["dimension_ratings"] = RATINGS + light_output = {} plan = None if not ctx.settings.review_ensemble: # legacy kill-switch: single pass result, output = await run_agent_step(ctx, **common) @@ -231,7 +244,7 @@ async def _review_diff(ctx: StepContext) -> StepResult: # protocol; measured, that cost it ~70% of its anchored findings result, output = await run_agent_step( ctx, max_iters=ctx.settings.review_light_max_iters, - **{**common, "guidance": guidance + _REVIEW_LIGHT_PROTOCOL}) + **{**common, "guidance": common["guidance"] + _REVIEW_LIGHT_PROTOCOL}) if ctx.settings.review_light_zero_yield_escalate \ and not (output.get("review_comments") or []): # Silence from the cheapest tier is the one result it is least @@ -240,6 +253,7 @@ async def _review_diff(ctx: StepContext) -> StepResult: ctx.trace.record("review_depth_escalated", step="agent.review_diff", depth_from="light", depth_to="standard", reason="light pass returned no findings") + light_output = output plan = replace(plan, depth="standard", lens_names=DEFAULT_STANDARD_LENSES, reason=plan.reason + "; escalated: light found nothing") @@ -283,6 +297,11 @@ async def _review_diff(ctx: StepContext) -> StepResult: result, output = await run_agent_step_ensemble( ctx, lenses=lenses, merge_key="review_comments", merge_guidance=_REVIEW_MERGE, **common) + if light_output: + from ...agent_runtime.ensemble import retain_review_assessments + + retain_review_assessments(light_output, output) + assessment_partial = not result.ok or bool(output.get("_assessment_incomplete")) if not result.ok and output.get("review_comments"): # A review that FOUND defects is a successful review whose verdict is # REQUEST CHANGES — not a failed step. Agents conflate the PR's @@ -304,76 +323,6 @@ async def _review_diff(ctx: StepContext) -> StepResult: ctx, output, common=common, diff=str(diff), spec=spec, depth=plan.depth, ) - # deterministic comment budget: severity-ordered, corroboration-aware, - # capped at 8 — the low-signal tail goes first (reducers ignored a - # prompted cap; the cap is a product budget, so it applies to every - # depth). The old 5-comment, severity-only cut deleted reducer-KEPT - # findings that were literal maintainer concerns on large PRs, while a - # nit-heavy unconditional overflow read as noise to the blind judge. - # Within a severity, findings corroborated by more independent lenses go - # first; the overflow tail renders on evidence-rich reviews (≥2 - # major/blocker) or for individually verify-confirmed cut comments — a - # quiet PR with an unverified tail stays terse (a thin-GT val item - # rendering 12 findings lost 3/3 on noise). - # Apply the review's OWN selection before anything else reads the list. - # It runs ahead of the budget below so a withheld candidate cannot occupy - # one of the eight publishable slots, and ahead of every renderer so the - # summary, the body and the inline comments are all made from the same - # finalized set (#141). - all_candidates = list(output.get("review_comments") or []) - published, withheld = finalize_review_dispositions(output) - # at most three untested-function comments; the rest are named, not lost - published, ut_dropped = cap_gap_comments(published, ut_report) - output["review_comments"] = published - output["_withheld_findings"] = withheld - comments = sorted(output.get("review_comments") or [], - key=lambda c: (_SEVERITY_ORDER.get( - str(c.get("severity", "minor")).lower(), 2), - -len(c.get("corroborated_by") or []))) - for c in comments: - c.pop("corroborated_by", None) - output["review_comments"] = comments[:8] - final_selection = [ - (c.get("file"), c.get("line"), c.get("comment"), c.get("severity")) - for c in output["review_comments"] - ] - if sorted(draft_selection, key=repr) != sorted(final_selection, key=repr): - # The reducer's prose describes its draft selection. After promotion, - # verification or a budget cut it may contradict the published set. - # Let the renderer derive a truthful summary from the final comments. - output["summary"] = "" - if ut_dropped: - output["summary"] = (str(output.get("summary") or "").rstrip() - + "\n\nAlso without a unit test: " - + ", ".join(f"`{n}`" for n in ut_dropped) + ".").lstrip() - # Recorded AFTER the cut: a candidate the review chose to publish but the - # budget dropped is `over_budget`, never `excluded`. A consumer checking - # that no withheld finding was published must not trip over a healthy - # review whose ninth comment simply did not fit. - output["_finding_dispositions"] = disposition_records( - all_candidates, output["review_comments"]) - if withheld: - ctx.trace.record( - "finding_dispositions", - withheld=len(withheld), - published=len(output["review_comments"]), - dispositions=[r["disposition"] - for r in output["_finding_dispositions"]], - ) - rich = sum(1 for c in comments[:8] - if _SEVERITY_ORDER.get(str(c.get("severity", "minor")).lower(), - 2) <= _SEVERITY_ORDER["major"]) >= 2 - # Overflow renders on evidence-rich reviews (unchanged), and ALSO for any - # cut comment the verify pass individually CONFIRMED on the tree — wave-2 - # forensics measured three verify-confirmed findings (one echoing the GT - # thread) silently dying here because the kept eight were minors and the - # rich gate never opened. A confirmed tail is evidence, not noise; the - # unverified tail still renders only on rich reviews. - output["_review_overflow"] = [ - c for c in comments[8:] - if _SEVERITY_ORDER.get(str(c.get("severity", "minor")).lower(), 2) - <= _SEVERITY_ORDER["minor"] - and (rich or c.get("_verified"))][:4] if plan is not None: result.outputs["review_plan"] = {"depth": plan.depth, "planner": plan.planner, @@ -407,47 +356,31 @@ async def _review_diff(ctx: StepContext) -> StepResult: str(ctx.state.get("pr_head_sha") or ""), ) if result.ok: - # Derive each finding's line from its quoted snippet BEFORE rendering: the - # review body prints `file:line` too, so resolving later (at publish) would - # show one position in the body and anchor the inline thread at another. - if output.get("review_comments"): - resolved, anchor_stats = resolve_review_comments( - output["review_comments"], str(ctx.state.get("diff_text") or "")) - output["review_comments"] = resolved - ctx.trace.record("anchor_resolution", **anchor_stats) - review_md = _render_review_md(output, - pr_state=str(ctx.state.get("pr_state", ""))) - review_summary = _render_review_summary( - output, pr_state=str(ctx.state.get("pr_state", ""))) - review_comments = output.get("review_comments") or [] - # The verdict has existed only as a rendered `**Verdict:** …` line inside - # the Markdown. A machine consumer would have to scrape it back out of - # prose to learn the outcome, so publish it as a field — from the SAME - # helper the renderer calls, never a second copy of the calibration rules. - review_verdict = _review_verdict( - review_comments, str(ctx.state.get("pr_state", ""))) - ctx.state.update({ - "review_text": review_md, - "review_summary": review_summary, - "review_comments": review_comments, - "review_verdict": review_verdict, - }) - result.outputs["review_text"] = review_md - result.outputs["review_summary"] = review_summary - result.outputs["review_comments"] = review_comments - result.outputs.setdefault("state_updates", {}).update({ - "review_text": review_md, - "review_summary": review_summary, - "review_comments": review_comments, - "review_verdict": review_verdict, - # The audit trail crosses the contract with the result: a - # consumer can prove the published set IS the finalized set. - "review_finding_dispositions": output.get("_finding_dispositions") or [], + packet = { + "review_comments": output.get("review_comments") or [], + "findings": output.get("findings") or [], + "summary": output.get("summary") or "", + "draft_selection": draft_selection, + "ut_candidates": [asdict(d) for d in ut_report.candidates] if ut_report else [], + } + updates = result.outputs.setdefault("state_updates", {}) + updates.update(await finalize_review_publication(ctx, packet, carried, rechecks, recheck_missing)) + updates.update({ "review_carried_findings": carried, "review_finding_rechecks": rechecks, "review_recheck_missing": recheck_missing, }) + if ctx.state.get("defer_review_evidence"): + result.outputs["review_publication_input"] = packet + result.outputs["review_assessment_input"] = { + "claim_checks": output.get("claim_checks"), + "dimension_ratings": output.get("dimension_ratings"), "partial": assessment_partial, + } + else: + await apply_review_evidence(ctx, output, updates, partial=assessment_partial, records=records) + ctx.state.update(updates) + result.outputs.update(updates) depth_note = f"; depth={plan.depth} via {plan.planner}" if plan else "" - result.summary = (f"review produced ({len(output.get('review_comments') or [])} " + result.summary = (f"review produced ({len(updates['review_comments'])} " f"comments{depth_note}) — {result.summary}") return result diff --git a/src/infermatrix_copilot/engine/steps/review/utils.py b/src/infermatrix_copilot/engine/steps/review/utils.py index 0f606fa59..31934045e 100644 --- a/src/infermatrix_copilot/engine/steps/review/utils.py +++ b/src/infermatrix_copilot/engine/steps/review/utils.py @@ -459,7 +459,8 @@ def _prefix_rank(line: str) -> int: # budget-cut overflow counts in the scan too — a capped finding was still # found, and "no finding reported" over a category the lenses DID flag # misrepresents the review's coverage - for comment in list(comments) + list(output.get("_review_overflow") or []): + existing = output.get("_existing_findings") or [] + for comment in [*comments, *(output.get("_review_overflow") or []), *existing]: category = _category_of(comment) counts[category] = counts.get(category, 0) + 1 scan = ["| Category | Result |", "|---|---|"] @@ -470,6 +471,14 @@ def _prefix_rank(line: str) -> int: f"{f'{count} finding(s) below' if count else 'no finding reported'} |" ) parts = ["**Scan:**\n" + "\n".join(scan)] + if existing: + parts.append("**Findings already tracked at this revision:**\n" + "\n".join( + f"- `{_anchor(c)}` [{c.get('severity', 'minor')}] — [existing thread]({c['thread_url']})" + for c in existing)) + if output.get("_feedback_status") in {"unavailable", "stale"}: + parts.append("Could not compare inline threads at the reviewed head. All selected findings remain eligible for publication.") + if output.get("_recheck_notes"): + parts.append("**Carried findings:**\n" + "\n".join(f"- {note}" for note in output["_recheck_notes"])) if validated: parts.append( "**Validated:**\n" @@ -531,7 +540,7 @@ def finalize_review_dispositions(output: dict) -> tuple[list[dict], list[dict]]: def disposition_records(candidates: list[dict], - published: list[dict]) -> list[dict]: + published: list[dict], existing: dict | None = None) -> list[dict]: """The audit trail: one record per candidate, whatever became of it. Published as `finding_dispositions` so a consumer can prove the published @@ -545,6 +554,8 @@ def disposition_records(candidates: list[dict], declared = _disposition_of(comment) if declared in WITHHOLDING_DISPOSITIONS: disposition = declared + elif existing and id(comment) in existing: + disposition = "duplicate" elif id(comment) in survived: disposition = PUBLISH_DISPOSITION else: @@ -576,7 +587,7 @@ def negative_check_notes(withheld: list[dict]) -> list[str]: return notes -def _render_review_summary(output: dict, pr_state: str = "") -> str: +def _render_review_summary(output: dict, pr_state: str = "", *, verdict: str | None = None) -> str: """Render a concise review body; individual findings are posted inline.""" comments = output.get("review_comments") or [] parts = _review_summary_parts(output) @@ -585,6 +596,8 @@ def _render_review_summary(output: dict, pr_state: str = "") -> str: parts.append(summary) elif comments: parts.append(f"{len(comments)} actionable finding(s).") + elif output.get("_existing_findings") or output.get("_recheck_notes"): + parts.append("No new inline findings.") else: parts.append("No actionable findings.") # A negative check keeps its evidence and loses its ask: it is reported @@ -594,11 +607,11 @@ def _render_review_summary(output: dict, pr_state: str = "") -> str: if notes: parts.append("**Checked, no defect found:**\n" + "\n".join(f"- {note}" for note in notes)) - parts.append(f"**Verdict:** {_review_verdict(comments, pr_state)}") + parts.append(f"**Verdict:** {verdict or _review_verdict(comments, pr_state)}") return "\n\n".join(parts) -def _render_review_md(output: dict, pr_state: str = "") -> str: +def _render_review_md(output: dict, pr_state: str = "", *, verdict: str | None = None) -> str: """Render the review output dict as Markdown: a category scan table (finding counts per category; empty rows say `no finding reported`), comments sorted by severity as `file:line [severity] — comment`, then a @@ -636,8 +649,12 @@ def _render_review_md(output: dict, pr_state: str = "") -> str: entry += f"\n\nProposed change (not a ready patch): {suggestion}" lines.append(entry) parts = _review_summary_parts(output) - parts.append("\n\n".join(lines) if lines else - (output.get("summary") or "No actionable findings.")) + if lines: + parts.append("\n\n".join(lines)) + elif output.get("_existing_findings") or output.get("_recheck_notes"): + parts.append("No new inline findings.") + else: + parts.append(output.get("summary") or "No actionable findings.") overflow = output.get("_review_overflow") or [] if overflow: # findings the comment budget cut — one line each, so a real (often @@ -653,4 +670,4 @@ def _render_review_md(output: dict, pr_state: str = "") -> str: f"{_clip(str(c.get('comment', '')).strip(), 900)}" for c in _dedupe_comments(overflow))) body = "\n\n".join(parts) - return f"{body}\n\n**Verdict:** {_review_verdict(comments, pr_state)}" + return f"{body}\n\n**Verdict:** {verdict or _review_verdict(comments, pr_state)}" diff --git a/src/infermatrix_copilot/improve/drivers.py b/src/infermatrix_copilot/improve/drivers.py index d48610913..69115ede0 100644 --- a/src/infermatrix_copilot/improve/drivers.py +++ b/src/infermatrix_copilot/improve/drivers.py @@ -243,11 +243,12 @@ def git(*args): git("add", "-A"); git("commit", "--allow-empty", "-qm", "frozen input") revisions.append(subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip()) state = {"playbook": "pr-review", "repo_path": str(repo), "diff_text": data["diff"], + "defer_review_evidence": True, "pr_context_independent": data.get("pr_context_independent", False), "pr_base_sha": revisions[0], "pr_head_sha": revisions[1], "pr_context": data.get("context_text", ""), "gate_report": data.get("gate_report", ""), "pr_state": data.get("pr_state", ""), "task_spec": {"kind": "pr_review", "repo": data["repo"], "pr": data["pr"], "params": data.get("task_params", {})}} - settings = settings.model_copy(update={"improve_shadow": True, "run_root": Path("/tmp/runs"), + settings = settings.model_copy(update={"improve_shadow": True, "pr_context_source": "snapshot", "run_root": Path("/tmp/runs"), "knowledge_dir": Path("/tmp/knowledge"), "skills_dir": Path("/candidate/skills"), "playbooks_dir": Path("/candidate/playbooks"), "adapters_dir": Path("/candidate/adapters"), "memory_db": Path("/tmp/memory.db")}) for path, content in data.get("knowledge_files", {}).items(): @@ -256,7 +257,9 @@ def git(*args): ctx.run_dir.mkdir() result = asyncio.run(_review_diff(ctx)) if not result.ok: raise ArtifactError(result.summary) - return {"review_text": result.outputs.get("review_text") or state.get("review_text", ""), + return {"review_publication_input": result.outputs["review_publication_input"], + "review_assessment_input": result.outputs["review_assessment_input"], + "review_text": result.outputs.get("review_text") or state.get("review_text", ""), "review_comments": result.outputs.get("review_comments", []), **{k: state.get(k) for k in ("review_summary", "review_verdict", "review_finding_dispositions", "review_carried_findings", "review_finding_rechecks", "review_recheck_missing")}} raise ArtifactError(f"worker has no driver {driver}") diff --git a/src/infermatrix_copilot/improve/runtime.py b/src/infermatrix_copilot/improve/runtime.py index db3652ebf..22cc2fd01 100644 --- a/src/infermatrix_copilot/improve/runtime.py +++ b/src/infermatrix_copilot/improve/runtime.py @@ -314,10 +314,14 @@ def freeze_review(settings, state): total += p.stat().st_size if total > 16_000_000: raise artifacts.ArtifactError('knowledge snapshot exceeds replay bound') knowledge[p.relative_to(kroot).as_posix()] = p.read_text() + from ..engine.steps.review.feedback import independent_context + context = state.get('pr_context', '') + if not state.get('pr_context_independent'): + context = independent_context(context) spec = state['task_spec'] return {'repo': spec['repo'], 'pr': spec['pr'], 'base_sha': revisions[0], 'head_sha': revisions[1], 'base_files': trees[0], 'head_files': trees[1], 'diff': state['diff_text'], 'knowledge_files': knowledge, - 'context_text': state.get('pr_context', ''), 'gate_report': state.get('gate_report', ''), + 'context_text': context, 'pr_context_independent': True, 'gate_report': state.get('gate_report', ''), 'task_params': spec.get('params', {}), 'pr_state': state.get('pr_state', '')} @@ -342,14 +346,26 @@ async def review_step(ctx): return StepResult(False, FailureKind.BLOCKED, 'active review lacks a safe frozen replay input') return None if not is_active: return None + if not entry.get('disabled'): + publication = Path(entry['artifact']) / 'src/infermatrix_copilot/engine/steps/review/publication.py' + # Older workers cannot return independent candidates. Carried finding + # rechecks also require real commits, which a reconstructed tree lacks. + if not publication.is_file() or (data.get('task_params') or {}).get('carried_findings'): + return None import asyncio try: prediction = await asyncio.to_thread(execute, ctx.settings, store, workflow, data, ctx.llm) except Exception as exc: return StepResult(False, FailureKind.BLOCKED, 'autonomous review rolled back: ' + str(exc)) if prediction is None: return None - outputs = {k: prediction.get(k) for k in ('review_text', 'review_comments', 'review_summary', 'review_verdict', - 'review_finding_dispositions', 'review_carried_findings', 'review_finding_rechecks', 'review_recheck_missing')} + from ..engine.steps.review.claim_evidence import apply_review_evidence + from ..engine.steps.review.publication import finalize_review_publication + packet = prediction.get('review_publication_input') + if not isinstance(packet, dict): + return StepResult(False, FailureKind.BLOCKED, 'review worker omitted independent findings') + assessment = prediction.get('review_assessment_input') or {} + outputs = await finalize_review_publication(ctx, packet, [], [], []) + await apply_review_evidence(ctx, assessment, outputs, partial=bool(assessment.get('partial'))) ctx.state.update(outputs) return StepResult(True, summary='review produced by verified autonomous source', outputs={**outputs, 'state_updates': outputs}) diff --git a/src/infermatrix_copilot/intent.py b/src/infermatrix_copilot/intent.py index 2637f14ac..bd5ffcf57 100644 --- a/src/infermatrix_copilot/intent.py +++ b/src/infermatrix_copilot/intent.py @@ -149,12 +149,25 @@ def repo_identity(alias: str, settings) -> str | None: return _remote_full_name(str(path)) if path else None -def _depth_param(text: str) -> dict: +_SCORE_REQUEST = re.compile( + r"(?:\bwith|(?:^|[,;]|\band)\s*(?:please\s+)?(?:include|give|provide|return|add))" + r"\s+(?:me\s+)?(?:an?\s+)?(?:numeric(?:al)?\s+)?score\b" + r"|\bscore (?:it|this (?:PR|review))\b|(?:请|并|同时|给它|给这个\s*PR)\s*(?:打分|评分)|给(?:出)?(?:一个)?(?:数值)?评分", + re.IGNORECASE) +_SCORE_NEGATED = re.compile( + r"\b(?:no|without|omit|skip|never|not|don't)\b[^,.;]{0,24}\bscor(?:e|ing)\b" + r"|(?:不[要用需]?|无需|别)\s*(?:打分|评分)", re.IGNORECASE) + + +def _review_params(text: str) -> dict: + params = {} + if _SCORE_REQUEST.search(text) and not _SCORE_NEGATED.search(text): + params["include_score"] = True if _DEPTH_FULL.search(text): - return {"review_depth": "full"} - if _DEPTH_LIGHT.search(text): - return {"review_depth": "light"} - return {} + params["review_depth"] = "full" + elif _DEPTH_LIGHT.search(text): + params["review_depth"] = "light" + return params def validate_spec(spec: TaskSpec) -> str: @@ -162,6 +175,9 @@ def validate_spec(spec: TaskSpec) -> str: run_task, playbook params): return a typed error message, or '' when the spec can actually run. Applied BEFORE a run is created so failures are upfront, not a BLOCKED fetch step later.""" + if "include_score" in spec.params: + if spec.kind != "pr_review" or not isinstance(spec.params["include_score"], bool): + return "include_score must be a boolean on a PR review" if spec.kind == "pr_review" and not spec.pr: return "review needs a PR number or URL (e.g. `review pr 5134`)" if spec.kind in ("pr_rebase", "pr_debug") and not spec.pr: @@ -181,7 +197,7 @@ def pre_parse(text: str, settings) -> IntentResult | None: if not text: return None mode = "performance" if _wants_performance(text) else "eco" - params = _depth_param(text) + params = _review_params(text) post = _wants_post(text) m = _GH_URL.search(text) @@ -378,7 +394,8 @@ def _parse_llm(text: str, llm: LLM, default_repo: str, model: str | None) -> Int depth = str(obj.get("review_depth") or "").lower() if depth in _VALID_DEPTHS: params["review_depth"] = depth - params.update(_depth_param(text)) # deterministic phrase wins over the LLM + if obj.get("kind") == "pr_review": + params.update(_review_params(text)) try: return IntentResult(spec=TaskSpec( kind=obj["kind"], mode=mode, repo=default_repo, pr=obj.get("pr"), diff --git a/src/infermatrix_copilot/mcp_server.py b/src/infermatrix_copilot/mcp_server.py index fbddadf99..17633c3b3 100644 --- a/src/infermatrix_copilot/mcp_server.py +++ b/src/infermatrix_copilot/mcp_server.py @@ -52,10 +52,11 @@ def build_mcp(settings: Settings | None = None): @mcp.tool() def start_review(pr: int, repo: str = "", review_depth: str = "", mode: Literal["eco", "performance"] = "eco", - expected_head_sha: str = "") -> dict: + expected_head_sha: str = "", include_score: bool = False) -> dict: """Start a read-only review of PR `pr` in eco or performance mode. Returns {run_id}; poll get_result. `review_depth` optionally pins the adaptive depth (light|standard|full|auto; policy-validated). + Set `include_score` when the user requests a numeric advisory score. `expected_head_sha` optionally pins the review to one snapshot: pass the full 40-hex head you observed and the run stops as stale rather than reviewing a different commit if the PR moved in between.""" @@ -64,6 +65,8 @@ def start_review(pr: int, repo: str = "", review_depth: str = "", "pr": pr, "mode": mode} if review_depth: req["params"] = {"review_depth": review_depth} + if include_score: + req.setdefault("params", {})["include_score"] = include_score if expected_head_sha: req["expected_head_sha"] = expected_head_sha return _guard(lambda: {"run_id": core.start(req)}) diff --git a/src/infermatrix_copilot/sdk/v1/models.py b/src/infermatrix_copilot/sdk/v1/models.py index 7ae5de4e3..322259870 100644 --- a/src/infermatrix_copilot/sdk/v1/models.py +++ b/src/infermatrix_copilot/sdk/v1/models.py @@ -7,7 +7,7 @@ SDK_API_VERSION = "1.0.0" DIRECT_API_VERSION = "1.1.0" -STRICT_API_VERSION = "1.4.0" # StrictRuntimeConfig.max_workers +STRICT_API_VERSION = "1.5.0" # Claim evidence and optional advisory scores QUALITY_API_VERSION = "1.0.0" KNOWLEDGE_API_VERSION = "1.1.0" KNOWLEDGE_TRACE_API_VERSION = "1.0.0" @@ -320,6 +320,11 @@ class StrictReviewRequest(_Serializable): idempotency_key: str review_depth: str = "standard" carried_findings: tuple[CarriedFinding, ...] = () + include_score: bool = False + + def __post_init__(self) -> None: + if not isinstance(self.include_score, bool): + raise InvalidRequestError("include_score must be a boolean") @dataclass(frozen=True) @@ -373,6 +378,10 @@ class StrictReviewResult(_Serializable): recheck_missing: tuple[str, ...] stale: bool diagnostics: dict[str, Any] + review_claim_evidence: tuple[dict[str, Any], ...] = () + review_score: dict[str, Any] | None = None + review_feedback_status: str = "" + finding_dispositions: tuple[dict[str, Any], ...] = () @dataclass(frozen=True) diff --git a/src/infermatrix_copilot/sdk/v1/strict.py b/src/infermatrix_copilot/sdk/v1/strict.py index 3453e2a0e..8cffeb981 100644 --- a/src/infermatrix_copilot/sdk/v1/strict.py +++ b/src/infermatrix_copilot/sdk/v1/strict.py @@ -60,6 +60,9 @@ def _review_result(raw: Any) -> StrictReviewResult | None: complete = raw.get("rechecks_complete", False) if not isinstance(complete, bool): raise ResultDecodeError("rechecks_complete must be a boolean") + score = raw.get("review_score") + if score is not None and not isinstance(score, dict): + raise ResultDecodeError("review_score must be an object") return StrictReviewResult( contract_version=str(raw.get("contract_version") or ""), reviewed_head_sha=str(raw.get("reviewed_head_sha") or ""), @@ -70,6 +73,10 @@ def _review_result(raw: Any) -> StrictReviewResult | None: finding_rechecks=tuple(rechecks), rechecks_complete=complete, recheck_missing=tuple(missing), + review_claim_evidence=_object_rows(raw.get("review_claim_evidence"), "review_claim_evidence"), + review_score=score, + review_feedback_status=str(raw.get("review_feedback_status") or ""), + finding_dispositions=_object_rows(raw.get("finding_dispositions"), "finding_dispositions"), stale=bool(raw.get("stale", False)), diagnostics=_diagnostics(raw.get("diagnostics")), ) @@ -166,6 +173,8 @@ def reserve_review(self, request: StrictReviewRequest) -> StrictRunHandle: "repo_path": request.repo_path, "idempotency_key": request.idempotency_key, } + if request.include_score: + payload["params"]["include_score"] = True run_id, created = self._core.reserve_strict_review(payload) return StrictRunHandle(run_id=str(run_id), created=bool(created)) diff --git a/src/infermatrix_copilot/thin_mcp_server.py b/src/infermatrix_copilot/thin_mcp_server.py index 73bc71995..bbfdc6f80 100644 --- a/src/infermatrix_copilot/thin_mcp_server.py +++ b/src/infermatrix_copilot/thin_mcp_server.py @@ -221,6 +221,7 @@ def _strict_review_request( expected_head_sha: str = "", repo_path: str = "", idempotency_key: str = "", + include_score: bool = False, ) -> dict: """Translate the Strict public surface to the internal review TaskSpec.""" target = str(target).strip() @@ -255,6 +256,8 @@ def _strict_review_request( } if review_depth: request["params"] = {"review_depth": review_depth} + if include_score: + request.setdefault("params", {})["include_score"] = include_score if expected_head_sha: # carried as a first-class field, not a param: the policy gate validates # it as a full 40-hex sha and refuses anything else @@ -471,6 +474,7 @@ def review( knowledge_profile: str = "legacy", task_id: str = "", trace_id: str = "", + include_score: bool = False, ) -> dict: """Begin a Direct or Strict review. @@ -494,6 +498,8 @@ def review( the attempt and a repeated call returns the SAME run — including a finished one, whose result you can read — instead of starting a second review. Use a new key for a genuinely new attempt. + In Strict mode, set ``include_score=true`` only when the user requests a + numeric score. The result also reports claim evidence independently. ``post`` applies to Direct only. Strict never publishes: exactly one publisher must own a PR's review marker and head gate, so read the structured result and post it yourself (``post=true`` with @@ -507,6 +513,8 @@ def run() -> dict: if selected_mode not in {"direct", "strict"}: raise ValueError("mode must be 'direct' or 'strict'") if selected_mode == "direct": + if include_score: + raise ValueError("include_score is a Strict request option; Direct scoring is host-owned") if knowledge_profile == "adaptive": if trace_id: raise ValueError("adaptive traces are bound to their context session; omit trace_id") @@ -598,7 +606,7 @@ def run() -> dict: request = _strict_review_request( target, repo, post=post, review_depth=review_depth, settings=core.settings, expected_head_sha=expected_head_sha, - repo_path=repo_path, idempotency_key=idempotency_key) + repo_path=repo_path, idempotency_key=idempotency_key, include_score=include_score) missing = core.strict_readiness(request["repo"], repo_path) if missing: raise ValueError( diff --git a/test/test_agent_ensemble.py b/test/test_agent_ensemble.py index 37028c419..3a129e5a2 100644 --- a/test/test_agent_ensemble.py +++ b/test/test_agent_ensemble.py @@ -1472,3 +1472,19 @@ async def fake_step(ctx, **kw): lenses=[{"name": "b", "focus": "look at B"}], merge_key="items", output_extension={"items": "list"})) assert len(seen) == 1, f"a dead unrouted tier must not be re-asked: {seen}" + + +def test_reducer_keeps_evidence_from_each_investigator_when_it_drops_all_comments(settings, trace, tmp_path): + settings.ensemble_parallel = False + llm = ScriptedLLM([ + contract(items=[{"name": "a"}], claim_checks=[{"claim": "raw output"}], + dimension_ratings=[{"dimension": "validation"}]), + contract(items=[{"name": "b"}], claim_checks=[{"claim": "comparison"}], + dimension_ratings=[{"dimension": "claim_evidence"}]), + verdicts_reply({"i": 0, "action": "drop"}, {"i": 1, "action": "drop"}), + ]) + _, output = _run(_ctx(settings, trace, tmp_path, llm=llm), + output_extension={"items": "list", "claim_checks": "list", "dimension_ratings": "list"}) + assert output["items"] == [] + assert [r["claim"] for r in output["claim_checks"]] == ["raw output", "comparison"] + assert [r["dimension"] for r in output["dimension_ratings"]] == ["validation", "claim_evidence"] diff --git a/test/test_contract.py b/test/test_contract.py index f2c28dda7..abdb97008 100644 --- a/test/test_contract.py +++ b/test/test_contract.py @@ -43,6 +43,7 @@ def test_result_reads_the_verdict_as_a_field_not_from_markdown(tmp_path): assert result["verdict"] == "REQUEST CHANGES" assert result["reviewed_head_sha"] == "a" * 40 assert result["state"] == rs.DONE + assert "review_score" not in result and "review_claim_evidence" not in result assert result["contract_version"] == contract.STRICT_API_VERSION diff --git a/test/test_e2e_strict_mock.py b/test/test_e2e_strict_mock.py index a802f2cf2..251f88c52 100644 --- a/test/test_e2e_strict_mock.py +++ b/test/test_e2e_strict_mock.py @@ -330,3 +330,94 @@ def test_a_key_reused_for_a_different_pr_is_refused(strict): assert strict.run(run_id) == 0 with pytest.raises(idem.IdempotencyError, match="different request"): strict.start(pr=8, idempotency_key="k") + + +def _scored_reciprocal_reply(): + proof = {"path": "feature.py", "quote": "return 1 / x"} + ratings = {"scope": 3, "correctness": 0, "validation": 1, "claim_evidence": 3, "simplicity": 3} + return _review_reply( + review_comments=[FINDING], + claim_checks=[{"claim": "The helper returns a reciprocal", "kind": "source", + "status": "verified", "reason": "Checked the implementation.", "records": [proof]}], + dimension_ratings=[{"dimension": dimension, "rating": rating, "reason": "Checked the reciprocal path.", **proof} + for dimension, rating in ratings.items()], + ) + + +@pytest.mark.parametrize("include_score,head_moves", [(False, False), (True, False), (True, True)]) +def test_sdk_returns_pinned_claim_evidence_and_opt_in_score(strict, include_score, head_moves, monkeypatch): + from dataclasses import replace + from infermatrix_copilot.sdk.v1 import RepositoryRef, StrictReviewRequest, StrictRuntime + + strict.llm._replies = [_scored_reciprocal_reply()] + if head_moves: + def live_gh(args, cwd=None): + head = "b" * 40 if strict.llm.calls else strict.head + return _fake_gh(head)(args, cwd=cwd) + monkeypatch.setattr(fetch_mod, "_gh", live_gh) + runtime = object.__new__(StrictRuntime) + runtime._core = strict.core + request = StrictReviewRequest(RepositoryRef("widget"), 7, strict.head, "", "score-attempt", + review_depth="light", include_score=include_score) + run_id = runtime.reserve_review(request).run_id + assert strict.run(run_id) == 0 + response = runtime.get_result(run_id) + assert response.review.verdict == "REQUEST CHANGES" + assert response.review.stale is head_moves + if head_moves: + assert response.payload["result"]["actual_head_sha"] == "b" * 40 + assert response.review.review_claim_evidence[0]["status"] == "verified" + assert "The helper returns a reciprocal" in response.payload["report"] + assert response.review.finding_dispositions[0]["disposition"] == "publish" + if include_score: + score = response.review.review_score + assert score["reviewed_head_sha"] == strict.head + assert score["total"] == (None if head_moves else 62) + assert ("withheld" if head_moves else "62/100") in response.payload["report"] + else: + assert response.review.review_score is None + assert "review_score" not in response.payload["result"] + assert "Advisory score" not in response.payload["report"] + + with pytest.raises(idem.IdempotencyError, match="different request"): + runtime.reserve_review(replace(request, include_score=not include_score)) + + +def test_frozen_worker_finalizes_against_original_head(strict, tmp_path, monkeypatch): + import asyncio + from infermatrix_copilot.engine.step import StepContext + from infermatrix_copilot.improve import drivers, runtime + from infermatrix_copilot.run_trace import RunTrace + from infermatrix_copilot.trace_store import TraceStore, bind_store + + settings = strict.core.settings + settings.knowledge_dir = tmp_path / "fixture-knowledge" + state = { + "task_spec": {"kind": "pr_review", "pr": 7, "repo": "widget", "params": {"include_score": True}}, + "repo_path": str(strict.work), "pr_head_sha": strict.head, "pr_base_sha": _git("rev-parse", "main", cwd=strict.work), + "diff_text": _git("diff", "main", strict.head, cwd=strict.work), + "pr_context": "PR description\n## Review summaries\nOLD REVIEWER TEXT", + } + strict.llm._replies = [_scored_reciprocal_reply()] + entry = {"workflows": ["pr-review.agent.review_diff"], "artifact": str(REPO_ROOT)} + monkeypatch.setattr(runtime, "active", lambda _: entry) + # The production worker owns /tmp inside its sandbox. Redirect that private + # root under pytest while exercising the real worker and its synthetic Git tree. + worker_root = tmp_path / "worker" + worker_root.mkdir() + monkeypatch.setattr(drivers, "Path", lambda path: worker_root / Path(path).name) + + def isolated_worker(_settings, _store, _workflow, frozen, llm): + assert "OLD REVIEWER TEXT" not in frozen["context_text"] + return drivers.worker_run({"driver": "pr-review", "input": frozen}, _settings, llm) + + monkeypatch.setattr(runtime, "execute", isolated_worker) + context = StepContext(settings, state, {}, tmp_path, RunTrace(tmp_path / "live.jsonl"), strict.llm) + with bind_store(TraceStore(tmp_path / "store", environ={})): + result = asyncio.run(runtime.review_step(context)) + assert result.ok + assert _git("rev-parse", "HEAD", cwd=worker_root / "repository") != strict.head + assert result.outputs["review_score"]["reviewed_head_sha"] == strict.head + assert result.outputs["review_score"]["total"] == 62 + assert result.outputs["review_claim_evidence"][0]["status"] == "verified" + assert len(strict.llm.calls) == 1 diff --git a/test/test_mcp.py b/test/test_mcp.py index 8acca1d2a..bbcbc4688 100644 --- a/test/test_mcp.py +++ b/test/test_mcp.py @@ -770,3 +770,20 @@ def test_a_configured_knowledge_dir_is_pinned_not_replaced_by_the_packaged_tree( assert env["KNOWLEDGE_DIR"] == str(custom.resolve()) and KNOWLEDGE_ROOT_ENV not in env assert build_review_result(core.run_root / run_id)["diagnostics"]["knowledge_snapshot"] == "unverified" core.close() + + +def test_score_parameter_is_opt_in_for_cli_and_reserved_requests(settings): + from infermatrix_copilot.cli.utils import parse_task_params + from infermatrix_copilot.intent import pre_parse, validate_spec + from infermatrix_copilot.task_spec import TaskSpec + from infermatrix_copilot.app.request_policy import enforce_strict_review_policy + + req = {"kind": "pr_review", "repo": "widget", "pr": 7} + for words, expected in (("with a score", True), ("without a score", False), ("scoring logic", False)): + assert pre_parse("review PR 7 " + words, settings).spec.params.get("include_score", False) is expected + assert validate_spec(TaskSpec(**req, params=parse_task_params(["include_score=true"]))) == "" + assert "boolean" in validate_spec(TaskSpec(**req, params=parse_task_params(["include_score=maybe"]))) + policy = enforce_strict_review_policy + assert policy({**req, "params": {"include_score": False}}, allowed_repos=["widget"]) == policy(req, allowed_repos=["widget"]) + with pytest.raises(ValueError, match="boolean"): + policy({**req, "params": {"include_score": "false"}}, allowed_repos=["widget"]) diff --git a/test/test_quality_workstreams.py b/test/test_quality_workstreams.py index 857e458e1..beb48ba82 100644 --- a/test/test_quality_workstreams.py +++ b/test/test_quality_workstreams.py @@ -88,13 +88,18 @@ def fake_gh(args, cwd=None, timeout=120): class Ctx: def __init__(self, mode): self.settings = settings - self.state = {} + self.state = {"task_spec": {"kind": "pr_quality"}} settings.pr_context_mode = mode full = fetch_mod._pr_context_bundle(Ctx("full"), str(git_repo), 9) assert "DISCUSSION-MARKER" in full and "Linked issue #7" in full assert "do not repeat these concerns" in full + strict_ctx = Ctx("full") + strict_ctx.state["task_spec"]["kind"] = "pr_review" + strict = fetch_mod._pr_context_bundle(strict_ctx, str(git_repo), 9) + assert "DISCUSSION-MARKER" not in strict and "Linked issue #7" in strict + bare = fetch_mod._pr_context_bundle(Ctx("no_discussion"), str(git_repo), 9) assert "DISCUSSION-MARKER" not in bare # eval-leakage policy assert "Linked issue #7" in bare # linked issues stay diff --git a/test/test_replay_capture_pr_review.py b/test/test_replay_capture_pr_review.py index ab45ddad6..b6b46e61d 100644 --- a/test/test_replay_capture_pr_review.py +++ b/test/test_replay_capture_pr_review.py @@ -1,6 +1,7 @@ """Oversize replay capture preserves the PR review release boundary.""" import asyncio +from pathlib import Path from types import SimpleNamespace import pytest @@ -56,3 +57,16 @@ def test_oversize_review_replay_never_executes_or_becomes_dataset_input(tmp_path assert any(r['result'].get('type') == 'replay_capture_missing' for r in records) assert objectives.collect(settings, store, WORKFLOW) == 0 assert objectives.rows(settings, WORKFLOW) == [] + + +@pytest.mark.parametrize("carried", [False, True]) +def test_incompatible_worker_uses_native_before_model_spend(tmp_path, settings, monkeypatch, carried): + root = Path(__file__).resolve().parents[1] if carried else tmp_path + store = TraceStore(tmp_path / "traces", environ={}) + frozen = {"repo": "demo", "pr": 1, "head_sha": "a" * 40, + "task_params": {"carried_findings": [{"finding_id": "previous"}]} if carried else {}} + monkeypatch.setattr(runtime, "active", lambda _: {"workflows": [WORKFLOW], "artifact": str(root)}) + monkeypatch.setattr(runtime, "freeze_review", lambda *_: frozen) + monkeypatch.setattr(runtime, "execute", lambda *_: pytest.fail("incompatible worker reached model execution")) + with bind_store(store): + assert asyncio.run(runtime.review_step(SimpleNamespace(settings=settings, state={}))) is None diff --git a/test/test_review_step.py b/test/test_review_step.py index d9c023fae..d83f29975 100644 --- a/test/test_review_step.py +++ b/test/test_review_step.py @@ -437,3 +437,88 @@ def test_carried_findings_are_rechecked_on_frozen_head_and_persisted(settings, t structured = build_review_result(run_dir) assert structured["rechecks_complete"] assert structured["finding_rechecks"] == payload["finding_rechecks"] + + +def test_open_thread_suppresses_only_the_same_verified_finding(settings, trace, tmp_path, git_repo, monkeypatch): + from infermatrix_copilot.engine.steps.review import feedback + from infermatrix_copilot.engine.steps._common import gh_read_tools + import infermatrix_copilot.engine.steps._common as common + + head = "f" * 40 + marker = "PRIOR-THREAD-MARKER" + body = "**[major]** empty input raises\n\nEvidence: " + marker + root = {"body": body, "url": "https://github.com/org/repo/pull/9#discussion_r999"} + node = {"isResolved": False, "isOutdated": False, "path": "a.py", "line": 2, + "diffSide": "RIGHT", "comments": {"nodes": [root]}} + llm = ScriptedLLM([_contract_reply([ + {"file": "a.py", "line": 88, "anchor_snippet": "b = items[0]", "severity": "major", + "comment": "empty input raises", "evidence": "a.py:2 b = items[0]"}, + {"file": "a.py", "line": 2, "severity": "minor", "comment": "different defect", "evidence": "a.py:2"}, + ])]) + def query(args, cwd): + assert llm.calls, "feedback was fetched before source investigation" + assert args[:2] == ["api", "graphql"] + return 0, json.dumps({"data": {"repository": {"pullRequest": { + "headRefOid": head, "reviewThreads": {"nodes": [node]}}}}}) + monkeypatch.setattr(feedback, "gh", query) + state = {"diff_text": "+++ b/a.py\n@@ -1 +1,2 @@\n a = 1\n+b = items[0]\n", + "pr_head_sha": head, "repo_path": str(git_repo), "task_spec": {"pr": 9}, + "pr_context": "## PR description\nfixes #13\n\n## Review summaries\n" + marker + + "\n\n## Linked issue #13: zero length\nAcceptance criterion"} + result = asyncio.run(_registry().get("agent.review_diff").handler( + _ctx(settings, trace, tmp_path, state, llm=llm))) + assert result.ok, result.summary + prompt = str(llm.calls[0]["messages"]) + assert marker not in prompt and "Acceptance criterion" in prompt + assert [c["comment"] for c in state["review_comments"]] == ["different defect"] + assert state["review_comments"][0]["line"] == 2 + assert state["review_verdict"] == "REQUEST CHANGES" + for key in ("review_summary", "review_text"): + assert "discussion_r999" in state[key] + assert state[key].endswith("**Verdict:** REQUEST CHANGES") + assert [r["disposition"] for r in state["review_finding_dispositions"]] == ["duplicate", "publish"] + + fields = [] + monkeypatch.setattr(common, "gh", lambda args, **kw: (fields.append(args[-1]) or 0, "{}")) + gh_read_tools(git_repo, issue_comments=False)["gh_issue_view"].handler(issue=9) + assert "comments" not in fields[0].split(",") + assert feedback.independent_context("## PR description\n## Review summaries for this experiment\nkeep").endswith("keep") + + +def test_inactive_stale_and_unavailable_threads_never_suppress(settings, trace, tmp_path, git_repo, monkeypatch): + from infermatrix_copilot.engine.steps.review import feedback + + ctx = _ctx(settings, trace, tmp_path, {"repo_path": str(git_repo)}) + head = "a" * 40 + thread = {"isResolved": False, "isOutdated": False, "path": "a", "line": 1, "diffSide": "RIGHT", + "comments": {"nodes": [{"body": "issue", "url": "thread"}]}} + data = {"headRefOid": head, "reviewThreads": {"nodes": [ + dict(thread, isResolved=True), dict(thread, isOutdated=True), dict(thread, diffSide="LEFT")]}} + monkeypatch.setattr(feedback, "gh", lambda *a, **kw: (0, json.dumps( + {"data": {"repository": {"pullRequest": data}}}))) + assert feedback.existing_threads(ctx, 9, head) == ({}, "checked") + assert feedback.existing_threads(ctx, 9, "b" * 40) == ({}, "stale") + monkeypatch.setattr(feedback, "gh", lambda *a, **kw: (1, "unavailable")) + assert feedback.existing_threads(ctx, 9, head) == ({}, "unavailable") + settings.pr_context_mode = "no_discussion" + def forbidden(*args, **kwargs): + raise AssertionError("offline review opened GitHub") + monkeypatch.setattr(feedback, "gh", forbidden) + assert feedback.existing_threads(ctx, 9, head) == ({}, "disabled") + + +def test_carried_verdict_requires_a_current_head_recheck(settings, trace, tmp_path): + from infermatrix_copilot.engine.steps.review.publication import finalize_review_publication + + ctx = _ctx(settings, trace, tmp_path, {"task_spec": {"pr": 9}}) + packet = {"review_comments": [], "draft_selection": [], "ut_candidates": []} + carried = [{"finding_id": "prior", "title": "Empty batch", "severity": "major"}] + for outcome, verdict in (("fixed", "APPROVE"), ("still_affected", "REQUEST CHANGES"), + ("unverified", "COMMENT")): + checks = [{"finding_id": "prior", "outcome": outcome, "evidence": "Observed return on line 3"}] + outputs = asyncio.run(finalize_review_publication(ctx, packet, carried, checks, [])) + assert outputs["review_verdict"] == verdict + assert outputs["review_text"].endswith(f"**Verdict:** {verdict}") + outputs = asyncio.run(finalize_review_publication(ctx, packet, carried, [], ["missing recheck: prior"])) + assert outputs["review_verdict"] == "COMMENT" + assert "missing recheck" in outputs["review_summary"] diff --git a/test/test_sdk_v1.py b/test/test_sdk_v1.py index 8afc5fc71..ed10f5a22 100644 --- a/test/test_sdk_v1.py +++ b/test/test_sdk_v1.py @@ -330,6 +330,8 @@ def test_strict_facade_preserves_idempotency_and_hides_private_paths(): assert "review_depth" not in core.requests[0] assert status.to_dict()["payload"]["progress"] == {"completed": {}} assert result.to_dict()["payload"]["result"] == {"verdict": "APPROVE"} + assert result.review.review_claim_evidence == () + assert result.review.review_score is None assert result.payload["offset_seen"] == 12 assert "report_path" not in result.payload assert runtime.capabilities().distribution_version == __version__ @@ -426,7 +428,7 @@ def test_strict_runtime_public_capabilities_smoke(tmp_path): caps = runtime.capabilities() assert caps.distribution_version == __version__ - assert caps.strict_api_version == "1.4.0" + assert caps.strict_api_version == "1.5.0" assert caps.knowledge_api_version == KNOWLEDGE_API_VERSION assert caps.supports_knowledge_curation is True diff --git a/test/test_strict_claim_evidence.py b/test/test_strict_claim_evidence.py new file mode 100644 index 000000000..4da99b7f2 --- /dev/null +++ b/test/test_strict_claim_evidence.py @@ -0,0 +1,140 @@ +import asyncio +import subprocess +from types import SimpleNamespace + +import pytest + +from infermatrix_copilot.engine.steps.review import claim_evidence as evidence + + +RULE = "**Simplicity is 0/3** if the diff adds or rewrites an explanatory code\ncomment. License headers and directives are exempt." + + +@pytest.fixture +def records(tmp_path): + def run(*args): + return subprocess.check_output(["git", *args], cwd=tmp_path, text=True).strip() + + run("init", "-q") + (tmp_path / "AGENTS.md").write_text(RULE + "\nA passing review requires results/raw.tsv.\n") + (tmp_path / "design.md").write_text(RULE) + (tmp_path / "src").mkdir() + (tmp_path / "src/app.py").write_text("def value():\n return 1\n") + run("add", ".") + run("-c", "user.name=Test", "-c", "user.email=test@example.org", "commit", "-qm", "base") + base = run("rev-parse", "HEAD") + (tmp_path / "src/app.py").write_text("def value():\n # increment value\n return 2\n") + run("add", ".") + run("-c", "user.name=Test", "-c", "user.email=test@example.org", "commit", "-qm", "head") + return evidence.ReviewRecords(tmp_path, run("rev-parse", "HEAD"), base, False) + + +def claim(status="verified", **changes): + return {"claim": "Value API", "kind": "source", "status": status, "reason": "Pinned source check.", + "records": [{"path": "src/app.py", "quote": "return 2"}], **changes} + + +def ratings(**overrides): + return [{"dimension": key, "rating": overrides.get(key, 3), "reason": "Observed changed branch.", + "path": "src/app.py", "quote": "return 2"} for key in evidence.WEIGHTS] + + +def test_committed_claims_require_real_blob_quotes(records): + rows = [claim(), claim(records=[{"path": "src", "quote": "return 2"}]), + claim(records=[{"path": "src/app.py", "quote": "return 3"}]), + claim(records=[{"path": "../AGENTS.md", "quote": "EXEMPT"}])] + assert [r["status"] for r in evidence.assess_claims(rows, records)] == ["verified", "unverified", "unverified", "unverified"] + assert evidence.assess_claims([], records)[0]["status"] == "unverified" + + +def test_required_artifact_zero_differs_from_unperformed_check(records): + missing = claim("missing", records=[{"path": "results/raw.tsv", "requirement_path": "AGENTS.md", + "requirement_quote": "requires results/raw.tsv."}]) + checked = evidence.assess_claims([missing], records) + assert checked[0]["status"] == "missing" + assert evidence.score_review(ratings(), checked, records)["total"] == 70 + for bad in [claim("missing"), claim("missing", records=[{"path": "made-up"}]), claim("unverified")]: + claims = evidence.assess_claims([bad], records) + assert evidence.score_review(ratings(), claims, records)["total"] is None + records.head = "f" * 40 + assert evidence.assess_claims([missing], records)[0]["status"] == "unverified" + + +def test_comparison_needs_raw_records_from_both_actual_revisions(records): + def job_revision(job_id): + return {1: records.head, 2: records.base, 3: records.head}[job_id] + records.job_revision = job_revision + records.job_line = lambda job, quote: ("inaccessible", "") if job == 3 else ("verified", quote) + raw = [{"job_id": 1, "quote": "42 ms"}, {"job_id": 2, "quote": "76 ms", "role": "baseline"}] + def check(refs): + return evidence.assess_claims([claim(kind="runtime", comparison=True, records=refs)], records)[0]["status"] + assert check(raw) == "verified" + assert check(raw[:1]) == "unverified" + assert check(raw[1:]) == "unverified" + assert check([{"job_id": 2, "quote": "76 ms"}]) == "mismatched" + assert check([{"job_id": 3, "quote": "expired"}]) == "inaccessible" + assert check([{"path": "AGENTS.md", "quote": "requires results/raw.tsv."}]) == "unverified" + + +def test_scores_reject_hallucinated_citations_and_normalize_with_half_up_rounding(records): + checked = evidence.assess_claims([claim()], records) + unsupported = ratings() + unsupported[1]["quote"] = "invented" + assert evidence.score_review(unsupported, checked, records)["total"] is None + for bad in (True, 4, "3", {}, None): + assert evidence.score_review(ratings(validation=bad), checked, records)["total"] is None + assert evidence.score_review(ratings(claim_evidence="N/A"), checked, records)["total"] is None + excluded = evidence.assess_claims([claim("not_applicable")], records) + assert evidence.score_review(ratings(scope=2), excluded, records)["total"] == 93 + # Applicable weights sum to 80. 30 weighted points gives 12.5. + assert evidence.score_review(ratings(scope=0, correctness=0, validation="N/A", claim_evidence=1, + simplicity=0), checked, records)["total"] == 13 + + +def test_upstream_multiline_comment_rule_requires_a_governing_policy_and_changed_comment(records): + checked = evidence.assess_claims([claim()], records) + diff = "diff --git a/src/app.py b/src/app.py\n+++ b/src/app.py\n+ # increment value\n" + rows = ratings() + rows[-1].update(comment_penalty=True, policy_quote=RULE, policy_path="AGENTS.md", quote="# increment value") + assert evidence.score_review(rows, checked, records, diff=diff)["total"] == 90 + for path in ["design.md", "src/AGENTS.md"]: + rows[-1]["policy_path"] = path + assert evidence.score_review(rows, checked, records, diff=diff)["total"] is None + assert not evidence._explanatory_comment("#!/bin/sh") + assert not evidence._explanatory_comment("# noqa: F821") + assert not evidence._explanatory_comment('"""Required contract."""') + assert not evidence._requires_path("Normal reports are required but results/raw.tsv is optional.", "results/raw.tsv") + + +def test_actual_merge_verdict_only_changes_for_cited_acceptance_condition(records): + ctx = SimpleNamespace(settings=SimpleNamespace(pr_context_source="snapshot"), state={ + "pr_head_sha": records.head, "pr_base_sha": records.base, "task_spec": {"params": {}}}) + raw = claim("missing", records=[{"path": "results/raw.tsv", "requirement_path": "AGENTS.md", + "requirement_quote": "requires results/raw.tsv."}]) + for policy, state, verdict in [(False, "OPEN", "APPROVE"), (True, "OPEN", "REQUEST CHANGES"), + (True, "MERGED", "FOLLOW-UP REQUIRED (post-merge)")]: + ctx.state["pr_state"] = state + if policy: + raw.update(acceptance_path="AGENTS.md", acceptance_quote="A passing review requires results/raw.tsv.") + updates = {"review_verdict": "APPROVE", "review_summary": "**Verdict:** APPROVE"} + asyncio.run(evidence.apply_review_evidence(ctx, {"claim_checks": [raw]}, updates, records=records)) + assert updates["review_verdict"] == verdict + assert updates["review_summary"].endswith(f"**Verdict:** {verdict}") + assert "review_score" not in updates + + +def test_freshness_unavailable_or_moved_withholds_score(records, monkeypatch): + ctx = SimpleNamespace(settings=SimpleNamespace(pr_context_source="live"), state={ + "pr_head_sha": records.head, "pr_base_sha": records.base, "task_spec": {"pr": 123, "params": {"include_score": True}}}) + events = [] + ctx.trace = SimpleNamespace(record=lambda event, **details: events.append((event, details))) + monkeypatch.setattr(evidence, "repo_path", lambda ctx: records.repo) + raw = {"claim_checks": [claim()], "dimension_ratings": ratings()} + for sha, expected in [(records.head, 100), (records.base, None), ("", None)]: + monkeypatch.setattr(evidence.fetch, "_resolve_pr_head", lambda *args: ("main", sha, "")) + updates = {"review_verdict": "APPROVE"} + asyncio.run(evidence.apply_review_evidence(ctx, raw, updates, records=records)) + assert updates["review_score"]["total"] == expected + assert updates["review_summary"].endswith("**Verdict:** APPROVE") + assert events == [("expected_head_mismatch", {"pr": 123, "expected": records.head, + "actual": records.base, "step": "agent.review_diff"})] diff --git a/test/test_thin_mcp_server.py b/test/test_thin_mcp_server.py index c2a2dd609..3fdefff23 100644 --- a/test/test_thin_mcp_server.py +++ b/test/test_thin_mcp_server.py @@ -1049,3 +1049,13 @@ def status(self): mcp, _core = _fake_mcp(monkeypatch) assert mcp.tools["get_update_status"]() == { "active_release": "next-release", "running_release": "this-server-release"} + + +def test_score_request_reaches_strict_run_only(monkeypatch): + mcp, core = _fake_mcp(monkeypatch) + review = mcp.tools["review"] + review(target="17", mode="strict", include_score=True) + assert core.requests[-1]["params"] == {"include_score": True} + review(target="17", mode="strict") + assert "include_score" not in core.requests[-1].get("params", {}) + assert "Strict" in review(target="17", mode="direct", include_score=True)["error"] From b5b5f3632c2b5908189e980cc41124cc6312f316 Mon Sep 17 00:00:00 2001 From: tzhouam Date: Wed, 25 Nov 2026 21:01:57 +0800 Subject: [PATCH 2/4] Verify the affected workflow specifications against the Strict pipeline --- doc/architecture/SPEC/engine/agent_runtime.md | 2 +- doc/architecture/SPEC/engine/steps/_common.md | 2 +- doc/architecture/SPEC/engine/steps/pr.md | 2 +- doc/architecture/SPEC/engine/steps/review.md | 2 +- doc/architecture/SPEC/playbooks/PLAYBOOKS.md | 4 +++- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/doc/architecture/SPEC/engine/agent_runtime.md b/doc/architecture/SPEC/engine/agent_runtime.md index 338597a20..c6b89e2a1 100644 --- a/doc/architecture/SPEC/engine/agent_runtime.md +++ b/doc/architecture/SPEC/engine/agent_runtime.md @@ -1,6 +1,6 @@ # engine/agent_runtime/ —— 规范 - + `LOC ~1690(7 个文件) · 引擎(受治理的 agent 运行时) · refactor-status: ok` diff --git a/doc/architecture/SPEC/engine/steps/_common.md b/doc/architecture/SPEC/engine/steps/_common.md index 05e49303c..174be9d42 100644 --- a/doc/architecture/SPEC/engine/steps/_common.md +++ b/doc/architecture/SPEC/engine/steps/_common.md @@ -1,6 +1,6 @@ # engine/steps/_common.py —— 规范 - + `LOC ~300 · step 库基础设施 · refactor-status: ok` diff --git a/doc/architecture/SPEC/engine/steps/pr.md b/doc/architecture/SPEC/engine/steps/pr.md index 1570c105e..bafc0e12b 100644 --- a/doc/architecture/SPEC/engine/steps/pr.md +++ b/doc/architecture/SPEC/engine/steps/pr.md @@ -1,6 +1,6 @@ # engine/steps/pr/ —— 规范 - + `LOC ~1988(6 个文件) · step 库(PR) · refactor-status: ok` diff --git a/doc/architecture/SPEC/engine/steps/review.md b/doc/architecture/SPEC/engine/steps/review.md index e15fe7865..012928edc 100644 --- a/doc/architecture/SPEC/engine/steps/review.md +++ b/doc/architecture/SPEC/engine/steps/review.md @@ -1,6 +1,6 @@ # engine/steps/review/ —— 规范 - + `patch gate + PR review + quality(9 个源文件) · step 库(评审) · refactor-status: ok` diff --git a/doc/architecture/SPEC/playbooks/PLAYBOOKS.md b/doc/architecture/SPEC/playbooks/PLAYBOOKS.md index 32ed305ac..14776e543 100644 --- a/doc/architecture/SPEC/playbooks/PLAYBOOKS.md +++ b/doc/architecture/SPEC/playbooks/PLAYBOOKS.md @@ -1,6 +1,6 @@ # playbooks/*.yaml —— 规范 - + `9 个文件 · 声明式编排数据 · refactor-status: ok` @@ -23,6 +23,8 @@ success, steps[]`。 **不要改它的 step 列表**。 - `pr-rebase`/`pr-debug`/`pr-review`/`pr-quality`/`issue-answer`/`issue-triage` —— active, 仓库中立(`repos: []`、`requires: [repo.path]`)。 +- `pr-review` 声明可选布尔参数 `include_score`。默认按固定版本输出发现和证据, + 显式请求后附加参考分数。 - `pr-debug` 的 report-only 模式跳过 checkout 和 push;修复模式在推送前审查 已提交的变更。 - `repo-profile` —— active,仓库中立(用于接入第二个仓库)。 From d2c42b36d51884de6023cbfac5e2bf83d4706ed2 Mon Sep 17 00:00:00 2001 From: tzhouam Date: Wed, 25 Nov 2026 21:08:21 +0800 Subject: [PATCH 3/4] Require affirmative policy evidence and withhold incomplete ensemble scores --- .../engine/agent_runtime/ensemble.py | 2 + .../engine/steps/review/claim_evidence.py | 114 +++++++++++++++--- test/test_agent_ensemble.py | 5 +- test/test_strict_claim_evidence.py | 62 +++++++++- 4 files changed, 162 insertions(+), 21 deletions(-) diff --git a/src/infermatrix_copilot/engine/agent_runtime/ensemble.py b/src/infermatrix_copilot/engine/agent_runtime/ensemble.py index fe36f77f5..ee4a2e477 100644 --- a/src/infermatrix_copilot/engine/agent_runtime/ensemble.py +++ b/src/infermatrix_copilot/engine/agent_runtime/ensemble.py @@ -630,6 +630,8 @@ def _ok(obj) -> bool: if str(v.get("action", "")).lower() == "drop" ] else: + if "claim_checks" in (output_extension or {}): + merged["_assessment_incomplete"] = True merged["summary"] = (f"ensemble of {len(samples)} samples " "(merge reduction failed; unverified union)") # near-dup guard (W2): the reducer occasionally re-emits the same finding diff --git a/src/infermatrix_copilot/engine/steps/review/claim_evidence.py b/src/infermatrix_copilot/engine/steps/review/claim_evidence.py index f7a06535f..a9a17a73e 100644 --- a/src/infermatrix_copilot/engine/steps/review/claim_evidence.py +++ b/src/infermatrix_copilot/engine/steps/review/claim_evidence.py @@ -30,7 +30,7 @@ If repository acceptance explicitly requires the missing artifact, cite acceptance_path and acceptance_quote from the governing policy at the base; otherwise report the verification gap. For a missing tracked artifact use status=missing and {path,requirement_path,requirement_quote} -with the required repository location documented in the quoted requirement. For an identified CI +with the complete affirmative governing clause, including qualifiers and the exact artifact path. For an identified CI job whose log cannot be retrieved use status=inaccessible with {job_id}. For a wrong-run record use status=mismatched and cite its revision. Use unverified for checks you could not perform, including unsupported media or links. Use a single not_applicable row with rationale only when there is no applicable claim.""" @@ -130,6 +130,19 @@ def tracked(self, sha, path, quote=None): except (ValueError, OSError, subprocess.SubprocessError): return None + def governing_clause(self, sha, path, statement): + if not _text(statement) or self.tracked(sha, path) is not True: + return False + try: + rc, source = git(self.repo, "show", f"{sha}:{_safe_rel_path(path)}") + except (ValueError, OSError, subprocess.SubprocessError): + return False + return not rc and _unconditional_clause(source, statement) + + def requires_artifact(self, sha, path, statement, artifact): + statement = _text(statement) + return _requires_path(statement, artifact) and self.governing_clause(sha, path, statement) + def match(self, record, kind): if not isinstance(record, dict): return "unverified" @@ -139,7 +152,9 @@ def match(self, record, kind): return "unverified" if kind not in ("source", "runtime"): return "unverified" - if type(record.get("job_id")) is int: + if "job_id" in record: + if kind != "runtime" or type(record["job_id"]) is not int or record["job_id"] < 1: + return "unverified" actual = self.job_revision(record["job_id"]) if _sha(actual) and actual != expected: return "mismatched" @@ -168,11 +183,16 @@ def assess_claims(proposals, records): status, refs = row.get("status"), row.get("records") refs = refs if isinstance(refs, list) else [] failed_paths = [] - if status == "missing": + if "comparison" in row and type(row["comparison"]) is not bool: + status = "unverified" + elif any(not isinstance(ref, dict) or ref.get("role", "head") not in ("head", "baseline") + for ref in refs): + status = "unverified" + elif status == "missing": failed_paths = [ref["path"] for ref in refs if ( isinstance(ref, dict) and _text(ref.get("path")) - and ref["path"] in _text(ref.get("requirement_quote")) - and records.tracked(records.head, ref.get("requirement_path"), ref["requirement_quote"]) is True + and records.requires_artifact(records.head, ref.get("requirement_path"), + ref.get("requirement_quote"), ref["path"]) and records.tracked(records.head, ref["path"]) is False )] status = "missing" if failed_paths else "unverified" @@ -198,8 +218,9 @@ def assess_claims(proposals, records): policy = _text(row.get("acceptance_path")) statement = _text(row.get("acceptance_quote")) if (status in ("missing", "inaccessible", "mismatched") and statement - and _policy_path(policy, "", records) and records.tracked(records.base, policy, statement) - and any(_requires_path(statement, path) for path in failed_paths if path)): + and any(_policy_path(policy, path, records) + and records.requires_artifact(records.base, policy, statement, path) + for path in failed_paths if path)): result.update(acceptance_path=policy, acceptance_quote=statement) if result not in rows: rows.append(result) @@ -223,10 +244,9 @@ def score_review(proposals, claims, records, *, gap="", diff=""): continue if key == "simplicity" and row.get("comment_penalty") is True: rule = _text(row.get("policy_quote")) - if not (re.search(r"simplicity", rule, re.I) and re.search(r"comments?", rule, re.I) - and re.search(r"\b0\s*/\s*3\b", rule) + if not (_comment_penalty_rule(rule, row["path"]) and _policy_path(row.get("policy_path"), row["path"], records) - and records.tracked(records.base, row.get("policy_path"), rule) + and records.governing_clause(records.base, row.get("policy_path"), rule) and _introduced_comment(records, diff, row["path"], row["quote"])): continue rating = 0 @@ -259,13 +279,75 @@ def score_review(proposals, claims, records, *, gap="", diff=""): def _requires_path(statement, path): - flat = " ".join(statement.casefold().split()) - if re.search(r"\b(not|never|unless|optional|recommend(?:ed)?)\b", flat): + if not _text(path): return False - artifact = re.escape(path.casefold()) - obligation = r"(?:requires?|must (?:include|produce|attach|provide|retain)|shall (?:include|provide))" - return bool(re.search(rf"\b{obligation}\s+(?:the\s+)?`?{artifact}(?:`|\b)", flat) - or re.search(rf"{artifact}`? (?:is required|must be (?:included|present|provided))\b", flat)) + # Accept a small grammar of explicit requirements. A substring of a + # negation, alternative, example, or similarly named path is insufficient. + clause = re.sub(r"^(?:[-*+] |[0-9]+[.)] )", "", statement.strip()).strip() + artifact = rf"(?:`{re.escape(path)}`|{re.escape(path)})" + subject = r"(?:we|you|(?:all |every |each |a |the )?(?:passing )?(?:reviews?|pull requests?|PRs?|changes?|submissions?|contributors?))" + verb = r"(?:requires?|(?:must|shall) (?:include|produce|attach|provide|retain))" + return bool(re.fullmatch(rf"(?i:(?:{subject} {verb}|must (?:include|produce|attach|provide|retain)) (?:the )?){artifact}[.]?", clause) + or re.fullmatch(rf"{artifact}(?i: (?:is required|must be (?:included|present|provided)))[.]?", clause)) + + +def _comment_penalty_rule(statement, target): + rule = " ".join(statement.replace("**", "").removeprefix("- ").split()) + if "byte-preserved historical evidence" in rule.casefold(): + # The scoped rule covers maintained code. A file copied into a campaign + # archive can have a source extension without being maintained code. + if target.partition("/")[0] not in {"src", "csrc", "test", "tests", "scripts", "config"}: + return False + return bool(re.fullmatch( + r"simplicity is 0/3 if the diff adds or rewrites (?:any|an) explanatory code comment" + r"(?: in maintained source, tests, scripts, or config)?\." + r"(?: Apply this check to changed source, tests, scripts, and config\.)?" + r"(?: License headers(?:, shebangs, tool directives, and required docstrings| and directives) are exempt\.)?" + r"(?: Treat byte-preserved historical evidence as data\.)?" + r"(?: Express (?:the underlying )?behavior through code, tests, or relevant docs\.)?", rule, re.I)) + + +def _unconditional_clause(source, statement): + """Ignore quoted examples and qualifications outside the model's excerpt.""" + headings = {} + fence = "" + lines = source.splitlines() + qualifier = re.compile(r"\b(if|unless|when|except(?:ions?)?|only|optional|example[s]?|" + r"sample[s]?|obsolete|legacy|deprecated|draft|recommend(?:ed)?)\b", re.I) + clause = [line.strip() for line in statement.splitlines()] + clause[0] = clause[0].removeprefix("- ") + for index, line in enumerate(lines): + stripped = line.strip() + if stripped.startswith(("```", "~~~")): + mark = stripped[:3] + if not fence or fence == mark: + fence = "" if fence else mark + continue + if fence: + continue + heading = re.match(r"^(#{1,6}) (.+)", stripped) + if heading: + level = len(heading[1]) + headings = {k: v for k, v in headings.items() if k < level} + headings[level] = heading[2] + continue + if stripped.removeprefix("- ") != clause[0] or any(qualifier.search(h) for h in headings.values()): + continue + end = index + len(clause) + if [s.strip() for s in lines[index + 1:end]] != clause[1:]: + continue + # List-wide qualifiers may precede earlier items in the same block. + previous_block = "\n".join(lines[:index]).rstrip().rsplit("\n\n", 1)[-1] + if any(s.rstrip().endswith(":") for s in previous_block.splitlines()): + continue + if index and lines[index - 1].strip() and not re.match(r"^(?:#|[-*+] |[0-9]+[.)] )", lines[index - 1].strip()): + if not lines[index - 1].rstrip().endswith((".", "!", "?")): + continue + if end < len(lines) and (re.match(r"^(?:except|unless|if|when|only|provided|but|or)\b", lines[end].strip(), re.I) + or lines[end].startswith((" ", "\t")) and lines[end].strip()): + continue + return True + return False def _policy_path(path, target, records): diff --git a/test/test_agent_ensemble.py b/test/test_agent_ensemble.py index 3a129e5a2..a067f033e 100644 --- a/test/test_agent_ensemble.py +++ b/test/test_agent_ensemble.py @@ -151,8 +151,10 @@ def test_ensemble_empty_merge_reply_falls_open_without_repair(settings, trace, contract(items=[{"name": "y"}]), Reply(blocks=[Block(type="text", text="")]), # reducer returns nothing ]) - result, output = _run(_ctx(settings, trace, tmp_path, llm=llm)) + result, output = _run(_ctx(settings, trace, tmp_path, llm=llm), + output_extension={"items": "list", "claim_checks": "list"}) assert result.ok + assert output["_assessment_incomplete"] is True assert [i["name"] for i in output["items"]] == ["x", "x2", "y"] # union assert len(llm.calls) == 3 # no repair call happened @@ -1486,5 +1488,6 @@ def test_reducer_keeps_evidence_from_each_investigator_when_it_drops_all_comment _, output = _run(_ctx(settings, trace, tmp_path, llm=llm), output_extension={"items": "list", "claim_checks": "list", "dimension_ratings": "list"}) assert output["items"] == [] + assert output["_assessment_incomplete"] is False assert [r["claim"] for r in output["claim_checks"]] == ["raw output", "comparison"] assert [r["dimension"] for r in output["dimension_ratings"]] == ["validation", "claim_evidence"] diff --git a/test/test_strict_claim_evidence.py b/test/test_strict_claim_evidence.py index 4da99b7f2..024448286 100644 --- a/test/test_strict_claim_evidence.py +++ b/test/test_strict_claim_evidence.py @@ -49,7 +49,7 @@ def test_committed_claims_require_real_blob_quotes(records): def test_required_artifact_zero_differs_from_unperformed_check(records): missing = claim("missing", records=[{"path": "results/raw.tsv", "requirement_path": "AGENTS.md", - "requirement_quote": "requires results/raw.tsv."}]) + "requirement_quote": "A passing review requires results/raw.tsv."}]) checked = evidence.assess_claims([missing], records) assert checked[0]["status"] == "missing" assert evidence.score_review(ratings(), checked, records)["total"] == 70 @@ -60,16 +60,44 @@ def test_required_artifact_zero_differs_from_unperformed_check(records): assert evidence.assess_claims([missing], records)[0]["status"] == "unverified" +@pytest.mark.parametrize(("policy", "cited"), [ + ("We do not require results/raw.tsv.", "require results/raw.tsv."), + ("We do not require results/raw.tsv.", "We do not require results/raw.tsv."), + ("We require results/raw.tsv if the optional suite ran.", "We require results/raw.tsv"), + ("We require results/raw.tsv.old.", "We require results/raw.tsv"), + ("## Optional validation\nWe require results/raw.tsv.", "We require results/raw.tsv."), + ("For performance changes only:\n- We require results/raw.tsv.", "- We require results/raw.tsv."), + ("```text\nWe require results/raw.tsv.\n```", "We require results/raw.tsv."), +]) +def test_ambiguous_or_partial_policy_cannot_zero_score_or_block(records, policy, cited): + (records.repo / "AGENTS.md").write_text(policy + "\n") + subprocess.run(["git", "-c", "user.name=Test", "-c", "user.email=test@example.org", + "commit", "-qam", "policy"], cwd=records.repo, check=True) + records.head = records.base = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=records.repo, text=True).strip() + missing = claim("missing", records=[{"path": "results/raw.tsv", "requirement_path": "AGENTS.md", + "requirement_quote": cited}], acceptance_path="AGENTS.md", + acceptance_quote=cited) + checked = evidence.assess_claims([missing], records) + assert checked[0]["status"] == "unverified" + assert "acceptance_quote" not in checked[0] + assert evidence.score_review(ratings(), checked, records)["total"] is None + + def test_comparison_needs_raw_records_from_both_actual_revisions(records): def job_revision(job_id): return {1: records.head, 2: records.base, 3: records.head}[job_id] records.job_revision = job_revision records.job_line = lambda job, quote: ("inaccessible", "") if job == 3 else ("verified", quote) raw = [{"job_id": 1, "quote": "42 ms"}, {"job_id": 2, "quote": "76 ms", "role": "baseline"}] - def check(refs): - return evidence.assess_claims([claim(kind="runtime", comparison=True, records=refs)], records)[0]["status"] + def check(refs, comparison=True): + return evidence.assess_claims([claim(kind="runtime", comparison=comparison, records=refs)], records)[0]["status"] assert check(raw) == "verified" + assert evidence.assess_claims([claim(records=raw[:1])], records)[0]["status"] == "unverified" assert check(raw[:1]) == "unverified" + assert check(raw[:1], comparison="true") == "unverified" + assert check(raw, comparison=1) == "unverified" + assert check([*raw, {"job_id": 2, "quote": "76 ms", "role": "unknown"}]) == "unverified" assert check(raw[1:]) == "unverified" assert check([{"job_id": 2, "quote": "76 ms"}]) == "mismatched" assert check([{"job_id": 3, "quote": "expired"}]) == "inaccessible" @@ -106,11 +134,37 @@ def test_upstream_multiline_comment_rule_requires_a_governing_policy_and_changed assert not evidence._requires_path("Normal reports are required but results/raw.tsv is optional.", "results/raw.tsv") +def test_comment_penalty_rejects_negations_and_unquoted_exemptions(records): + upstream = ("- **Simplicity is 0/3** if the diff adds or rewrites any explanatory code\n" + " comment. Apply this check to changed source, tests, scripts, and config.\n" + " License headers, shebangs, tool directives, and required docstrings are exempt.\n" + " Express the underlying behavior through code, tests, or relevant docs.") + scoped = ("- **Simplicity is 0/3** if the diff adds or rewrites any explanatory code\n" + " comment in maintained source, tests, scripts, or config. License headers,\n" + " shebangs, tool directives, and required docstrings are exempt. Treat\n" + " byte-preserved historical evidence as data. Express behavior through code,\n" + " tests, or relevant docs.") + assert evidence._comment_penalty_rule(scoped, "src/app.py") + assert not evidence._comment_penalty_rule(scoped, "campaign/old/src/app.py") + negated = "Do not set simplicity to 0/3 for explanatory comments." + (records.repo / "AGENTS.md").write_text(upstream + "\n\n" + negated + "\n") + subprocess.run(["git", "-c", "user.name=Test", "-c", "user.email=test@example.org", + "commit", "-qam", "policy"], cwd=records.repo, check=True) + records.base = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=records.repo, text=True).strip() + checked = evidence.assess_claims([claim()], records) + diff = "diff --git a/src/app.py b/src/app.py\n+++ b/src/app.py\n+ # increment value\n" + rows = ratings() + rows[-1].update(comment_penalty=True, policy_path="AGENTS.md", quote="# increment value") + for rule, total in [(negated, None), (upstream.split(" License")[0].rstrip(), None), (upstream, 90)]: + rows[-1]["policy_quote"] = rule + assert evidence.score_review(rows, checked, records, diff=diff)["total"] == total + + def test_actual_merge_verdict_only_changes_for_cited_acceptance_condition(records): ctx = SimpleNamespace(settings=SimpleNamespace(pr_context_source="snapshot"), state={ "pr_head_sha": records.head, "pr_base_sha": records.base, "task_spec": {"params": {}}}) raw = claim("missing", records=[{"path": "results/raw.tsv", "requirement_path": "AGENTS.md", - "requirement_quote": "requires results/raw.tsv."}]) + "requirement_quote": "A passing review requires results/raw.tsv."}]) for policy, state, verdict in [(False, "OPEN", "APPROVE"), (True, "OPEN", "REQUEST CHANGES"), (True, "MERGED", "FOLLOW-UP REQUIRED (post-merge)")]: ctx.state["pr_state"] = state From 3ed10550525c677dcb3d4ce5eb292e94023b3864 Mon Sep 17 00:00:00 2001 From: tzhouam Date: Wed, 25 Nov 2026 21:16:05 +0800 Subject: [PATCH 4/4] Defer the POSIX trust-store lock dependency until use --- doc/architecture/SPEC/providers/zcode.md | 3 +++ src/infermatrix_copilot/providers/zcode.py | 6 +++++- test/test_e2e_strict_mock.py | 3 +++ test/test_provider_zcode.py | 11 +++++++++++ 4 files changed, 22 insertions(+), 1 deletion(-) diff --git a/doc/architecture/SPEC/providers/zcode.md b/doc/architecture/SPEC/providers/zcode.md index 654b1d18d..f6ecebd24 100644 --- a/doc/architecture/SPEC/providers/zcode.md +++ b/doc/architecture/SPEC/providers/zcode.md @@ -25,6 +25,9 @@ argv 单参数上限 128KiB)。`--mode` 按调用选:一次性调用用 `pla 实时交付原生事件,`supports_native_events=True`。`native_snapshot()` 只返回提供方实际报告的 用量与模型;缺失的 token、缓存和 USD 字段保持未知,不补造零值。 +RFC 的错误分类和无工具调用可在缺少 `fcntl` 的平台上导入。写入工作区 MCP +信任记录前必须取得 POSIX 文件锁;缺少锁支持时抛出 `FileLockingUnavailable`。 + ## 不变量(**C1**、**C2**) - **会话 cwd 永远是自有临时目录,不是 PR worktree。** zcode 从 cwd 加载 `.env`,并从 cwd 往上到 git 根发现 `zcode.json` / `.zcode/config.json`,项目配置里的 stdio MCP server 会被 diff --git a/src/infermatrix_copilot/providers/zcode.py b/src/infermatrix_copilot/providers/zcode.py index 90800b903..de8888b61 100644 --- a/src/infermatrix_copilot/providers/zcode.py +++ b/src/infermatrix_copilot/providers/zcode.py @@ -64,7 +64,6 @@ from __future__ import annotations -import fcntl import hashlib import json import logging @@ -269,6 +268,11 @@ def _seed_workspace_mcp_trust(cls, session: Path, server: str, to the host's workspace MCP trust store. Best effort: on failure the bridge stays untrusted and the engine's bridge-lifecycle check surfaces it — never a silent pass.""" + try: + import fcntl + except ImportError as exc: + from ..engine.lifecycle import FileLockingUnavailable + raise FileLockingUnavailable("ZCode workspace MCP trust requires POSIX file locking (fcntl)") from exc home = Path(sanitized_env().get("HOME") or Path.home()) store = home.joinpath(*_TRUST_STORE_REL) record = { diff --git a/test/test_e2e_strict_mock.py b/test/test_e2e_strict_mock.py index 251f88c52..ae3582b4a 100644 --- a/test/test_e2e_strict_mock.py +++ b/test/test_e2e_strict_mock.py @@ -26,6 +26,7 @@ from infermatrix_copilot.engine.agent_runtime import BASE_OUTPUT_SCHEMA from infermatrix_copilot.engine.steps import _common as common_mod from infermatrix_copilot.engine.steps.pr import fetch as fetch_mod +from infermatrix_copilot.engine.steps.review import claim_evidence, feedback from infermatrix_copilot.llm import Block, Reply from infermatrix_copilot.mcp_server import CopilotMCP @@ -169,6 +170,8 @@ def strict(settings, tmp_path, monkeypatch): monkeypatch.setattr(fetch_mod, "_gh", _fake_gh(head)) monkeypatch.setattr(common_mod, "gh", _fake_gh(head)) + monkeypatch.setattr(feedback, "gh", _fake_gh(head)) + monkeypatch.setattr(claim_evidence, "gh", _fake_gh(head)) # PR-time worktrees default to ~/.infermatrix-copilot/worktrees, which is a # developer's real scratch directory. A test must never materialize into it. monkeypatch.setattr(wt_mod.Path, "home", staticmethod(lambda: tmp_path)) diff --git a/test/test_provider_zcode.py b/test/test_provider_zcode.py index 4df5c43f8..742be82bf 100644 --- a/test/test_provider_zcode.py +++ b/test/test_provider_zcode.py @@ -3,6 +3,7 @@ import json import stat +import sys from pathlib import Path import pytest @@ -478,6 +479,16 @@ def test_workspace_mcp_trust_digest_golden(): "fc3f271d5a27e0e82f3ba633") +def test_workspace_mcp_trust_requires_lock_before_writing(tmp_path, monkeypatch): + from infermatrix_copilot.engine.lifecycle import FileLockingUnavailable + + monkeypatch.setitem(sys.modules, "fcntl", None) + monkeypatch.setattr(zcode_mod, "sanitized_env", lambda: {"HOME": str(tmp_path)}) + with pytest.raises(FileLockingUnavailable, match="ZCode workspace MCP trust"): + ZCodeTransport._seed_workspace_mcp_trust(tmp_path / "session", "server", {}) + assert not (tmp_path / ".zcode").exists() + + def test_workspace_mcp_trust_seed_is_idempotent_and_prunes_dead_sessions( tmp_path, monkeypatch): """One record per (server, digest); sessions whose dir vanished are